Code refactoring: pull SchedPreference enum from TargetLowering.h to TargetMachine...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66   default: llvm_unreachable("unknown subtarget type");
67   case X86Subtarget::isDarwin:
68     if (TM.getSubtarget<X86Subtarget>().is64Bit())
69       return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   case X86Subtarget::isELF:
72    if (TM.getSubtarget<X86Subtarget>().is64Bit())
73      return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80 }
81
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83   : TargetLowering(TM, createTLOF(TM)) {
84   Subtarget = &TM.getSubtarget<X86Subtarget>();
85   X86ScalarSSEf64 = Subtarget->hasSSE2();
86   X86ScalarSSEf32 = Subtarget->hasSSE1();
87   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88
89   RegInfo = TM.getRegisterInfo();
90   TD = getTargetData();
91
92   // Set up the TargetLowering object.
93
94   // X86 is weird, it always uses i8 for shift amounts and setcc results.
95   setShiftAmountType(MVT::i8);
96   setBooleanContents(ZeroOrOneBooleanContent);
97   setSchedulingPreference(Sched::RegPressure);
98   setStackPointerRegisterToSaveRestore(X86StackPtr);
99
100   if (Subtarget->isTargetDarwin()) {
101     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102     setUseUnderscoreSetJmp(false);
103     setUseUnderscoreLongJmp(false);
104   } else if (Subtarget->isTargetMingw()) {
105     // MS runtime is weird: it exports _setjmp, but longjmp!
106     setUseUnderscoreSetJmp(true);
107     setUseUnderscoreLongJmp(false);
108   } else {
109     setUseUnderscoreSetJmp(true);
110     setUseUnderscoreLongJmp(true);
111   }
112
113   // Set up the register classes.
114   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117   if (Subtarget->is64Bit())
118     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119
120   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121
122   // We don't accept any truncstore of integer registers.
123   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
129
130   // SETOEQ and SETUNE require checking two conditions.
131   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137
138   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139   // operation.
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
141   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
142   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
143
144   if (Subtarget->is64Bit()) {
145     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
146     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
147   } else if (!UseSoftFloat) {
148     // We have an algorithm for SSE2->double, and we turn this into a
149     // 64-bit FILD followed by conditional FADD for other targets.
150     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
151     // We have an algorithm for SSE2, and we turn this into a 64-bit
152     // FILD for other targets.
153     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
154   }
155
156   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
157   // this operation.
158   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
159   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
160
161   if (!UseSoftFloat) {
162     // SSE has no i16 to fp conversion, only i32
163     if (X86ScalarSSEf32) {
164       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
165       // f32 and f64 cases are Legal, f80 case is not
166       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
167     } else {
168       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
170     }
171   } else {
172     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
173     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
174   }
175
176   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
177   // are Legal, f80 is custom lowered.
178   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
179   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
180
181   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
182   // this operation.
183   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
184   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
185
186   if (X86ScalarSSEf32) {
187     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
188     // f32 and f64 cases are Legal, f80 case is not
189     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
190   } else {
191     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
193   }
194
195   // Handle FP_TO_UINT by promoting the destination to a larger signed
196   // conversion.
197   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
198   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
199   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
200
201   if (Subtarget->is64Bit()) {
202     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
203     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
204   } else if (!UseSoftFloat) {
205     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
206       // Expand FP_TO_UINT into a select.
207       // FIXME: We would like to use a Custom expander here eventually to do
208       // the optimal thing for SSE vs. the default expansion in the legalizer.
209       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
210     else
211       // With SSE3 we can use fisttpll to convert to a signed i64; without
212       // SSE, we're stuck with a fistpll.
213       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
214   }
215
216   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
217   if (!X86ScalarSSEf64) {
218     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
219     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
220   }
221
222   // Scalar integer divide and remainder are lowered to use operations that
223   // produce two results, to match the available instructions. This exposes
224   // the two-result form to trivial CSE, which is able to combine x/y and x%y
225   // into a single instruction.
226   //
227   // Scalar integer multiply-high is also lowered to use two-result
228   // operations, to match the available instructions. However, plain multiply
229   // (low) operations are left as Legal, as there are single-result
230   // instructions for this in x86. Using the two-result multiply instructions
231   // when both high and low results are needed must be arranged by dagcombine.
232   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
233   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
234   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
235   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
236   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
237   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
238   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
239   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
240   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
241   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
242   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
243   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
244   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
245   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
246   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
247   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
248   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
249   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
250   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
251   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
252   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
253   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
254   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
255   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
256
257   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
258   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
259   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
260   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
261   if (Subtarget->is64Bit())
262     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
266   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
267   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
268   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
269   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
270   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
271
272   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
273   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
274   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
275   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
276   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
277   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
278   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
279   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
280   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
281   if (Subtarget->is64Bit()) {
282     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
283     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
284     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
285   }
286
287   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
288   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
289
290   // These should be promoted to a larger select which is supported.
291   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
292   // X86 wants to expand cmov itself.
293   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
294   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
295   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
296   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
297   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
298   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
299   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
300   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
301   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
302   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
303   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
304   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
305   if (Subtarget->is64Bit()) {
306     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
307     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
308   }
309   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
310
311   // Darwin ABI issue.
312   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
313   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
314   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
315   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
316   if (Subtarget->is64Bit())
317     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
318   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
319   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
320   if (Subtarget->is64Bit()) {
321     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
322     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
323     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
324     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
325     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
326   }
327   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
328   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
329   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
330   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
331   if (Subtarget->is64Bit()) {
332     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
333     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
334     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
335   }
336
337   if (Subtarget->hasSSE1())
338     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
339
340   if (!Subtarget->hasSSE2())
341     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
342
343   // Expand certain atomics
344   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
345   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
346   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
347   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
348
349   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
350   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
351   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
352   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
353
354   if (!Subtarget->is64Bit()) {
355     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
356     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
357     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
358     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
359     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
360     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
361     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
362   }
363
364   // FIXME - use subtarget debug flags
365   if (!Subtarget->isTargetDarwin() &&
366       !Subtarget->isTargetELF() &&
367       !Subtarget->isTargetCygMing()) {
368     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
369   }
370
371   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
372   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
373   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
374   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
375   if (Subtarget->is64Bit()) {
376     setExceptionPointerRegister(X86::RAX);
377     setExceptionSelectorRegister(X86::RDX);
378   } else {
379     setExceptionPointerRegister(X86::EAX);
380     setExceptionSelectorRegister(X86::EDX);
381   }
382   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
383   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
384
385   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
386
387   setOperationAction(ISD::TRAP, MVT::Other, Legal);
388
389   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
390   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
391   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
392   if (Subtarget->is64Bit()) {
393     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
394     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
395   } else {
396     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
397     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
398   }
399
400   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
401   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
402   if (Subtarget->is64Bit())
403     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
404   if (Subtarget->isTargetCygMing())
405     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
406   else
407     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
408
409   if (!UseSoftFloat && X86ScalarSSEf64) {
410     // f32 and f64 use SSE.
411     // Set up the FP register classes.
412     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
413     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
414
415     // Use ANDPD to simulate FABS.
416     setOperationAction(ISD::FABS , MVT::f64, Custom);
417     setOperationAction(ISD::FABS , MVT::f32, Custom);
418
419     // Use XORP to simulate FNEG.
420     setOperationAction(ISD::FNEG , MVT::f64, Custom);
421     setOperationAction(ISD::FNEG , MVT::f32, Custom);
422
423     // Use ANDPD and ORPD to simulate FCOPYSIGN.
424     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
425     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
426
427     // We don't support sin/cos/fmod
428     setOperationAction(ISD::FSIN , MVT::f64, Expand);
429     setOperationAction(ISD::FCOS , MVT::f64, Expand);
430     setOperationAction(ISD::FSIN , MVT::f32, Expand);
431     setOperationAction(ISD::FCOS , MVT::f32, Expand);
432
433     // Expand FP immediates into loads from the stack, except for the special
434     // cases we handle.
435     addLegalFPImmediate(APFloat(+0.0)); // xorpd
436     addLegalFPImmediate(APFloat(+0.0f)); // xorps
437   } else if (!UseSoftFloat && X86ScalarSSEf32) {
438     // Use SSE for f32, x87 for f64.
439     // Set up the FP register classes.
440     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
441     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
442
443     // Use ANDPS to simulate FABS.
444     setOperationAction(ISD::FABS , MVT::f32, Custom);
445
446     // Use XORP to simulate FNEG.
447     setOperationAction(ISD::FNEG , MVT::f32, Custom);
448
449     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
450
451     // Use ANDPS and ORPS to simulate FCOPYSIGN.
452     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
453     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
454
455     // We don't support sin/cos/fmod
456     setOperationAction(ISD::FSIN , MVT::f32, Expand);
457     setOperationAction(ISD::FCOS , MVT::f32, Expand);
458
459     // Special cases we handle for FP constants.
460     addLegalFPImmediate(APFloat(+0.0f)); // xorps
461     addLegalFPImmediate(APFloat(+0.0)); // FLD0
462     addLegalFPImmediate(APFloat(+1.0)); // FLD1
463     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
464     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
465
466     if (!UnsafeFPMath) {
467       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
468       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
469     }
470   } else if (!UseSoftFloat) {
471     // f32 and f64 in x87.
472     // Set up the FP register classes.
473     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
474     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
475
476     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
477     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
478     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
479     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
480
481     if (!UnsafeFPMath) {
482       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
483       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
484     }
485     addLegalFPImmediate(APFloat(+0.0)); // FLD0
486     addLegalFPImmediate(APFloat(+1.0)); // FLD1
487     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
493   }
494
495   // Long double always uses X87.
496   if (!UseSoftFloat) {
497     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
498     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
499     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
500     {
501       bool ignored;
502       APFloat TmpFlt(+0.0);
503       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
504                      &ignored);
505       addLegalFPImmediate(TmpFlt);  // FLD0
506       TmpFlt.changeSign();
507       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
508       APFloat TmpFlt2(+1.0);
509       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
510                       &ignored);
511       addLegalFPImmediate(TmpFlt2);  // FLD1
512       TmpFlt2.changeSign();
513       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
514     }
515
516     if (!UnsafeFPMath) {
517       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
518       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
519     }
520   }
521
522   // Always use a library call for pow.
523   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
524   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
525   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
526
527   setOperationAction(ISD::FLOG, MVT::f80, Expand);
528   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
529   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
530   setOperationAction(ISD::FEXP, MVT::f80, Expand);
531   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
532
533   // First set operation action for all vector types to either promote
534   // (for widening) or expand (for scalarization). Then we will selectively
535   // turn on ones that can be effectively codegen'd.
536   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
537        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
538     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
539     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
542     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
553     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
554     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
587     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
591     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
592          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
593       setTruncStoreAction((MVT::SimpleValueType)VT,
594                           (MVT::SimpleValueType)InnerVT, Expand);
595     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
596     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
597     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
598   }
599
600   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
601   // with -msoft-float, disable use of MMX as well.
602   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
603     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
604     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
605     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
606     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
607     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
608
609     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
610     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
611     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
612     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
613
614     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
615     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
616     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
617     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
618
619     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
620     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
621
622     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
623     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
624     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
625     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
626     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
627     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
628     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
629
630     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
631     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
632     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
633     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
634     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
635     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
636     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
637
638     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
639     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
640     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
641     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
642     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
643     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
644     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
645
646     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
647     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
648     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
649     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
650     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
651     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
652     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
653     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
654     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
655
656     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
657     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
658     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
659     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
660     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
661
662     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
663     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
664     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
665     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
666
667     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
668     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
669     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
670     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
671
672     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
673
674     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
675     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
676     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
677     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
678     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
679     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
680     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
681   }
682
683   if (!UseSoftFloat && Subtarget->hasSSE1()) {
684     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
685
686     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
687     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
688     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
689     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
690     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
691     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
692     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
693     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
694     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
695     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
696     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
697     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
698   }
699
700   if (!UseSoftFloat && Subtarget->hasSSE2()) {
701     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
702
703     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
704     // registers cannot be used even for integer operations.
705     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
706     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
707     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
708     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
709
710     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
711     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
712     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
713     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
714     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
715     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
716     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
717     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
718     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
719     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
720     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
721     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
722     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
723     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
724     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
725     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
726
727     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
728     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
729     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
730     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
731
732     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
733     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
734     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
735     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
736     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
737
738     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
739     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
740     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
741     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
742     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
743
744     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
745     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
746       EVT VT = (MVT::SimpleValueType)i;
747       // Do not attempt to custom lower non-power-of-2 vectors
748       if (!isPowerOf2_32(VT.getVectorNumElements()))
749         continue;
750       // Do not attempt to custom lower non-128-bit vectors
751       if (!VT.is128BitVector())
752         continue;
753       setOperationAction(ISD::BUILD_VECTOR,
754                          VT.getSimpleVT().SimpleTy, Custom);
755       setOperationAction(ISD::VECTOR_SHUFFLE,
756                          VT.getSimpleVT().SimpleTy, Custom);
757       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
758                          VT.getSimpleVT().SimpleTy, Custom);
759     }
760
761     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
762     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
763     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
764     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
765     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
766     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
767
768     if (Subtarget->is64Bit()) {
769       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
770       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
771     }
772
773     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
774     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
775       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
776       EVT VT = SVT;
777
778       // Do not attempt to promote non-128-bit vectors
779       if (!VT.is128BitVector()) {
780         continue;
781       }
782       
783       setOperationAction(ISD::AND,    SVT, Promote);
784       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
785       setOperationAction(ISD::OR,     SVT, Promote);
786       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
787       setOperationAction(ISD::XOR,    SVT, Promote);
788       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
789       setOperationAction(ISD::LOAD,   SVT, Promote);
790       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
791       setOperationAction(ISD::SELECT, SVT, Promote);
792       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
793     }
794
795     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
796
797     // Custom lower v2i64 and v2f64 selects.
798     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
799     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
800     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
801     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
802
803     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
804     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
805     if (!DisableMMX && Subtarget->hasMMX()) {
806       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
807       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
808     }
809   }
810
811   if (Subtarget->hasSSE41()) {
812     // FIXME: Do we need to handle scalar-to-vector here?
813     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
814
815     // i8 and i16 vectors are custom , because the source register and source
816     // source memory operand types are not the same width.  f32 vectors are
817     // custom since the immediate controlling the insert encodes additional
818     // information.
819     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
820     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
821     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
822     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
823
824     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
825     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
826     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
827     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
828
829     if (Subtarget->is64Bit()) {
830       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
831       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
832     }
833   }
834
835   if (Subtarget->hasSSE42()) {
836     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
837   }
838
839   if (!UseSoftFloat && Subtarget->hasAVX()) {
840     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
841     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
842     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
843     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
844
845     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
846     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
847     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
848     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
849     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
850     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
851     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
852     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
853     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
854     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
855     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
856     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
857     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
858     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
859     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
860
861     // Operations to consider commented out -v16i16 v32i8
862     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
863     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
864     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
865     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
866     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
867     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
868     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
869     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
870     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
871     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
872     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
873     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
874     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
875     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
876
877     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
878     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
879     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
880     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
881
882     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
883     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
884     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
885     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
887
888     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
890     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
892     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
893     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
894
895 #if 0
896     // Not sure we want to do this since there are no 256-bit integer
897     // operations in AVX
898
899     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900     // This includes 256-bit vectors
901     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
902       EVT VT = (MVT::SimpleValueType)i;
903
904       // Do not attempt to custom lower non-power-of-2 vectors
905       if (!isPowerOf2_32(VT.getVectorNumElements()))
906         continue;
907
908       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
909       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911     }
912
913     if (Subtarget->is64Bit()) {
914       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
915       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
916     }
917 #endif
918
919 #if 0
920     // Not sure we want to do this since there are no 256-bit integer
921     // operations in AVX
922
923     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
924     // Including 256-bit vectors
925     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
926       EVT VT = (MVT::SimpleValueType)i;
927
928       if (!VT.is256BitVector()) {
929         continue;
930       }
931       setOperationAction(ISD::AND,    VT, Promote);
932       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
933       setOperationAction(ISD::OR,     VT, Promote);
934       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
935       setOperationAction(ISD::XOR,    VT, Promote);
936       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
937       setOperationAction(ISD::LOAD,   VT, Promote);
938       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
939       setOperationAction(ISD::SELECT, VT, Promote);
940       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
941     }
942
943     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
944 #endif
945   }
946
947   // We want to custom lower some of our intrinsics.
948   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
949
950   // Add/Sub/Mul with overflow operations are custom lowered.
951   setOperationAction(ISD::SADDO, MVT::i32, Custom);
952   setOperationAction(ISD::SADDO, MVT::i64, Custom);
953   setOperationAction(ISD::UADDO, MVT::i32, Custom);
954   setOperationAction(ISD::UADDO, MVT::i64, Custom);
955   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
956   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
957   setOperationAction(ISD::USUBO, MVT::i32, Custom);
958   setOperationAction(ISD::USUBO, MVT::i64, Custom);
959   setOperationAction(ISD::SMULO, MVT::i32, Custom);
960   setOperationAction(ISD::SMULO, MVT::i64, Custom);
961
962   if (!Subtarget->is64Bit()) {
963     // These libcalls are not available in 32-bit.
964     setLibcallName(RTLIB::SHL_I128, 0);
965     setLibcallName(RTLIB::SRL_I128, 0);
966     setLibcallName(RTLIB::SRA_I128, 0);
967   }
968
969   // We have target-specific dag combine patterns for the following nodes:
970   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
971   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
972   setTargetDAGCombine(ISD::BUILD_VECTOR);
973   setTargetDAGCombine(ISD::SELECT);
974   setTargetDAGCombine(ISD::SHL);
975   setTargetDAGCombine(ISD::SRA);
976   setTargetDAGCombine(ISD::SRL);
977   setTargetDAGCombine(ISD::OR);
978   setTargetDAGCombine(ISD::STORE);
979   setTargetDAGCombine(ISD::MEMBARRIER);
980   setTargetDAGCombine(ISD::ZERO_EXTEND);
981   if (Subtarget->is64Bit())
982     setTargetDAGCombine(ISD::MUL);
983
984   computeRegisterProperties();
985
986   // FIXME: These should be based on subtarget info. Plus, the values should
987   // be smaller when we are in optimizing for size mode.
988   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
989   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
990   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
991   setPrefLoopAlignment(16);
992   benefitFromCodePlacementOpt = true;
993 }
994
995
996 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
997   return MVT::i8;
998 }
999
1000
1001 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1002 /// the desired ByVal argument alignment.
1003 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1004   if (MaxAlign == 16)
1005     return;
1006   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1007     if (VTy->getBitWidth() == 128)
1008       MaxAlign = 16;
1009   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1010     unsigned EltAlign = 0;
1011     getMaxByValAlign(ATy->getElementType(), EltAlign);
1012     if (EltAlign > MaxAlign)
1013       MaxAlign = EltAlign;
1014   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1015     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1016       unsigned EltAlign = 0;
1017       getMaxByValAlign(STy->getElementType(i), EltAlign);
1018       if (EltAlign > MaxAlign)
1019         MaxAlign = EltAlign;
1020       if (MaxAlign == 16)
1021         break;
1022     }
1023   }
1024   return;
1025 }
1026
1027 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1028 /// function arguments in the caller parameter area. For X86, aggregates
1029 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1030 /// are at 4-byte boundaries.
1031 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1032   if (Subtarget->is64Bit()) {
1033     // Max of 8 and alignment of type.
1034     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1035     if (TyAlign > 8)
1036       return TyAlign;
1037     return 8;
1038   }
1039
1040   unsigned Align = 4;
1041   if (Subtarget->hasSSE1())
1042     getMaxByValAlign(Ty, Align);
1043   return Align;
1044 }
1045
1046 /// getOptimalMemOpType - Returns the target specific optimal type for load
1047 /// and store operations as a result of memset, memcpy, and memmove
1048 /// lowering. If DstAlign is zero that means it's safe to destination
1049 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1050 /// means there isn't a need to check it against alignment requirement,
1051 /// probably because the source does not need to be loaded. If
1052 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1053 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1054 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1055 /// constant so it does not need to be loaded.
1056 /// It returns EVT::Other if the type should be determined using generic
1057 /// target-independent logic.
1058 EVT
1059 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1060                                        unsigned DstAlign, unsigned SrcAlign,
1061                                        bool NonScalarIntSafe,
1062                                        bool MemcpyStrSrc,
1063                                        MachineFunction &MF) const {
1064   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1065   // linux.  This is because the stack realignment code can't handle certain
1066   // cases like PR2962.  This should be removed when PR2962 is fixed.
1067   const Function *F = MF.getFunction();
1068   if (NonScalarIntSafe &&
1069       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1070     if (Size >= 16 &&
1071         (Subtarget->isUnalignedMemAccessFast() ||
1072          ((DstAlign == 0 || DstAlign >= 16) &&
1073           (SrcAlign == 0 || SrcAlign >= 16))) &&
1074         Subtarget->getStackAlignment() >= 16) {
1075       if (Subtarget->hasSSE2())
1076         return MVT::v4i32;
1077       if (Subtarget->hasSSE1())
1078         return MVT::v4f32;
1079     } else if (!MemcpyStrSrc && Size >= 8 &&
1080                !Subtarget->is64Bit() &&
1081                Subtarget->getStackAlignment() >= 8 &&
1082                Subtarget->hasSSE2()) {
1083       // Do not use f64 to lower memcpy if source is string constant. It's
1084       // better to use i32 to avoid the loads.
1085       return MVT::f64;
1086     }
1087   }
1088   if (Subtarget->is64Bit() && Size >= 8)
1089     return MVT::i64;
1090   return MVT::i32;
1091 }
1092
1093 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1094 /// current function.  The returned value is a member of the
1095 /// MachineJumpTableInfo::JTEntryKind enum.
1096 unsigned X86TargetLowering::getJumpTableEncoding() const {
1097   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1098   // symbol.
1099   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1100       Subtarget->isPICStyleGOT())
1101     return MachineJumpTableInfo::EK_Custom32;
1102   
1103   // Otherwise, use the normal jump table encoding heuristics.
1104   return TargetLowering::getJumpTableEncoding();
1105 }
1106
1107 /// getPICBaseSymbol - Return the X86-32 PIC base.
1108 MCSymbol *
1109 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1110                                     MCContext &Ctx) const {
1111   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1112   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1113                                Twine(MF->getFunctionNumber())+"$pb");
1114 }
1115
1116
1117 const MCExpr *
1118 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1119                                              const MachineBasicBlock *MBB,
1120                                              unsigned uid,MCContext &Ctx) const{
1121   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1122          Subtarget->isPICStyleGOT());
1123   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1124   // entries.
1125   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1126                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1127 }
1128
1129 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1130 /// jumptable.
1131 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1132                                                     SelectionDAG &DAG) const {
1133   if (!Subtarget->is64Bit())
1134     // This doesn't have DebugLoc associated with it, but is not really the
1135     // same as a Register.
1136     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1137   return Table;
1138 }
1139
1140 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1141 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1142 /// MCExpr.
1143 const MCExpr *X86TargetLowering::
1144 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1145                              MCContext &Ctx) const {
1146   // X86-64 uses RIP relative addressing based on the jump table label.
1147   if (Subtarget->isPICStyleRIPRel())
1148     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1149
1150   // Otherwise, the reference is relative to the PIC base.
1151   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1152 }
1153
1154 /// getFunctionAlignment - Return the Log2 alignment of this function.
1155 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1156   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1157 }
1158
1159 //===----------------------------------------------------------------------===//
1160 //               Return Value Calling Convention Implementation
1161 //===----------------------------------------------------------------------===//
1162
1163 #include "X86GenCallingConv.inc"
1164
1165 bool 
1166 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1167                         const SmallVectorImpl<EVT> &OutTys,
1168                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1169                         SelectionDAG &DAG) const {
1170   SmallVector<CCValAssign, 16> RVLocs;
1171   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1172                  RVLocs, *DAG.getContext());
1173   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1174 }
1175
1176 SDValue
1177 X86TargetLowering::LowerReturn(SDValue Chain,
1178                                CallingConv::ID CallConv, bool isVarArg,
1179                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1180                                DebugLoc dl, SelectionDAG &DAG) const {
1181   MachineFunction &MF = DAG.getMachineFunction();
1182   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1183
1184   SmallVector<CCValAssign, 16> RVLocs;
1185   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1186                  RVLocs, *DAG.getContext());
1187   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1188
1189   // Add the regs to the liveout set for the function.
1190   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1191   for (unsigned i = 0; i != RVLocs.size(); ++i)
1192     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1193       MRI.addLiveOut(RVLocs[i].getLocReg());
1194
1195   SDValue Flag;
1196
1197   SmallVector<SDValue, 6> RetOps;
1198   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1199   // Operand #1 = Bytes To Pop
1200   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1201                    MVT::i16));
1202
1203   // Copy the result values into the output registers.
1204   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1205     CCValAssign &VA = RVLocs[i];
1206     assert(VA.isRegLoc() && "Can only return in registers!");
1207     SDValue ValToCopy = Outs[i].Val;
1208
1209     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1210     // the RET instruction and handled by the FP Stackifier.
1211     if (VA.getLocReg() == X86::ST0 ||
1212         VA.getLocReg() == X86::ST1) {
1213       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1214       // change the value to the FP stack register class.
1215       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1216         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1217       RetOps.push_back(ValToCopy);
1218       // Don't emit a copytoreg.
1219       continue;
1220     }
1221
1222     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1223     // which is returned in RAX / RDX.
1224     if (Subtarget->is64Bit()) {
1225       EVT ValVT = ValToCopy.getValueType();
1226       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1227         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1228         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1229           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1230       }
1231     }
1232
1233     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1234     Flag = Chain.getValue(1);
1235   }
1236
1237   // The x86-64 ABI for returning structs by value requires that we copy
1238   // the sret argument into %rax for the return. We saved the argument into
1239   // a virtual register in the entry block, so now we copy the value out
1240   // and into %rax.
1241   if (Subtarget->is64Bit() &&
1242       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1243     MachineFunction &MF = DAG.getMachineFunction();
1244     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1245     unsigned Reg = FuncInfo->getSRetReturnReg();
1246     if (!Reg) {
1247       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1248       FuncInfo->setSRetReturnReg(Reg);
1249     }
1250     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1251
1252     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1253     Flag = Chain.getValue(1);
1254
1255     // RAX now acts like a return value.
1256     MRI.addLiveOut(X86::RAX);
1257   }
1258
1259   RetOps[0] = Chain;  // Update chain.
1260
1261   // Add the flag if we have it.
1262   if (Flag.getNode())
1263     RetOps.push_back(Flag);
1264
1265   return DAG.getNode(X86ISD::RET_FLAG, dl,
1266                      MVT::Other, &RetOps[0], RetOps.size());
1267 }
1268
1269 /// LowerCallResult - Lower the result values of a call into the
1270 /// appropriate copies out of appropriate physical registers.
1271 ///
1272 SDValue
1273 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1274                                    CallingConv::ID CallConv, bool isVarArg,
1275                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1276                                    DebugLoc dl, SelectionDAG &DAG,
1277                                    SmallVectorImpl<SDValue> &InVals) const {
1278
1279   // Assign locations to each value returned by this call.
1280   SmallVector<CCValAssign, 16> RVLocs;
1281   bool Is64Bit = Subtarget->is64Bit();
1282   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1283                  RVLocs, *DAG.getContext());
1284   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1285
1286   // Copy all of the result registers out of their specified physreg.
1287   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1288     CCValAssign &VA = RVLocs[i];
1289     EVT CopyVT = VA.getValVT();
1290
1291     // If this is x86-64, and we disabled SSE, we can't return FP values
1292     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1293         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1294       report_fatal_error("SSE register return with SSE disabled");
1295     }
1296
1297     // If this is a call to a function that returns an fp value on the floating
1298     // point stack, but where we prefer to use the value in xmm registers, copy
1299     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1300     if ((VA.getLocReg() == X86::ST0 ||
1301          VA.getLocReg() == X86::ST1) &&
1302         isScalarFPTypeInSSEReg(VA.getValVT())) {
1303       CopyVT = MVT::f80;
1304     }
1305
1306     SDValue Val;
1307     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1308       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1309       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1310         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1311                                    MVT::v2i64, InFlag).getValue(1);
1312         Val = Chain.getValue(0);
1313         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1314                           Val, DAG.getConstant(0, MVT::i64));
1315       } else {
1316         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1317                                    MVT::i64, InFlag).getValue(1);
1318         Val = Chain.getValue(0);
1319       }
1320       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1321     } else {
1322       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1323                                  CopyVT, InFlag).getValue(1);
1324       Val = Chain.getValue(0);
1325     }
1326     InFlag = Chain.getValue(2);
1327
1328     if (CopyVT != VA.getValVT()) {
1329       // Round the F80 the right size, which also moves to the appropriate xmm
1330       // register.
1331       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1332                         // This truncation won't change the value.
1333                         DAG.getIntPtrConstant(1));
1334     }
1335
1336     InVals.push_back(Val);
1337   }
1338
1339   return Chain;
1340 }
1341
1342
1343 //===----------------------------------------------------------------------===//
1344 //                C & StdCall & Fast Calling Convention implementation
1345 //===----------------------------------------------------------------------===//
1346 //  StdCall calling convention seems to be standard for many Windows' API
1347 //  routines and around. It differs from C calling convention just a little:
1348 //  callee should clean up the stack, not caller. Symbols should be also
1349 //  decorated in some fancy way :) It doesn't support any vector arguments.
1350 //  For info on fast calling convention see Fast Calling Convention (tail call)
1351 //  implementation LowerX86_32FastCCCallTo.
1352
1353 /// CallIsStructReturn - Determines whether a call uses struct return
1354 /// semantics.
1355 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1356   if (Outs.empty())
1357     return false;
1358
1359   return Outs[0].Flags.isSRet();
1360 }
1361
1362 /// ArgsAreStructReturn - Determines whether a function uses struct
1363 /// return semantics.
1364 static bool
1365 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1366   if (Ins.empty())
1367     return false;
1368
1369   return Ins[0].Flags.isSRet();
1370 }
1371
1372 /// IsCalleePop - Determines whether the callee is required to pop its
1373 /// own arguments. Callee pop is necessary to support tail calls.
1374 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1375                                     CallingConv::ID CallingConv) const {
1376   if (IsVarArg)
1377     return false;
1378
1379   switch (CallingConv) {
1380   default:
1381     return false;
1382   case CallingConv::X86_StdCall:
1383     return !Subtarget->is64Bit();
1384   case CallingConv::X86_FastCall:
1385     return !Subtarget->is64Bit();
1386   case CallingConv::X86_ThisCall:
1387     return !Subtarget->is64Bit();
1388   case CallingConv::Fast:
1389     return GuaranteedTailCallOpt;
1390   case CallingConv::GHC:
1391     return GuaranteedTailCallOpt;
1392   }
1393 }
1394
1395 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1396 /// given CallingConvention value.
1397 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1398   if (Subtarget->is64Bit()) {
1399     if (CC == CallingConv::GHC)
1400       return CC_X86_64_GHC;
1401     else if (Subtarget->isTargetWin64())
1402       return CC_X86_Win64_C;
1403     else
1404       return CC_X86_64_C;
1405   }
1406
1407   if (CC == CallingConv::X86_FastCall)
1408     return CC_X86_32_FastCall;
1409   else if (CC == CallingConv::X86_ThisCall)
1410     return CC_X86_32_ThisCall;
1411   else if (CC == CallingConv::Fast)
1412     return CC_X86_32_FastCC;
1413   else if (CC == CallingConv::GHC)
1414     return CC_X86_32_GHC;
1415   else
1416     return CC_X86_32_C;
1417 }
1418
1419 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1420 /// by "Src" to address "Dst" with size and alignment information specified by
1421 /// the specific parameter attribute. The copy will be passed as a byval
1422 /// function parameter.
1423 static SDValue
1424 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1425                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1426                           DebugLoc dl) {
1427   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1428   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1429                        /*isVolatile*/false, /*AlwaysInline=*/true,
1430                        NULL, 0, NULL, 0);
1431 }
1432
1433 /// IsTailCallConvention - Return true if the calling convention is one that
1434 /// supports tail call optimization.
1435 static bool IsTailCallConvention(CallingConv::ID CC) {
1436   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1437 }
1438
1439 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1440 /// a tailcall target by changing its ABI.
1441 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1442   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1443 }
1444
1445 SDValue
1446 X86TargetLowering::LowerMemArgument(SDValue Chain,
1447                                     CallingConv::ID CallConv,
1448                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1449                                     DebugLoc dl, SelectionDAG &DAG,
1450                                     const CCValAssign &VA,
1451                                     MachineFrameInfo *MFI,
1452                                     unsigned i) const {
1453   // Create the nodes corresponding to a load from this parameter slot.
1454   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1455   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1456   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1457   EVT ValVT;
1458
1459   // If value is passed by pointer we have address passed instead of the value
1460   // itself.
1461   if (VA.getLocInfo() == CCValAssign::Indirect)
1462     ValVT = VA.getLocVT();
1463   else
1464     ValVT = VA.getValVT();
1465
1466   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1467   // changed with more analysis.
1468   // In case of tail call optimization mark all arguments mutable. Since they
1469   // could be overwritten by lowering of arguments in case of a tail call.
1470   if (Flags.isByVal()) {
1471     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1472                                     VA.getLocMemOffset(), isImmutable, false);
1473     return DAG.getFrameIndex(FI, getPointerTy());
1474   } else {
1475     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1476                                     VA.getLocMemOffset(), isImmutable, false);
1477     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1478     return DAG.getLoad(ValVT, dl, Chain, FIN,
1479                        PseudoSourceValue::getFixedStack(FI), 0,
1480                        false, false, 0);
1481   }
1482 }
1483
1484 SDValue
1485 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1486                                         CallingConv::ID CallConv,
1487                                         bool isVarArg,
1488                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1489                                         DebugLoc dl,
1490                                         SelectionDAG &DAG,
1491                                         SmallVectorImpl<SDValue> &InVals)
1492                                           const {
1493   MachineFunction &MF = DAG.getMachineFunction();
1494   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1495
1496   const Function* Fn = MF.getFunction();
1497   if (Fn->hasExternalLinkage() &&
1498       Subtarget->isTargetCygMing() &&
1499       Fn->getName() == "main")
1500     FuncInfo->setForceFramePointer(true);
1501
1502   MachineFrameInfo *MFI = MF.getFrameInfo();
1503   bool Is64Bit = Subtarget->is64Bit();
1504   bool IsWin64 = Subtarget->isTargetWin64();
1505
1506   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1507          "Var args not supported with calling convention fastcc or ghc");
1508
1509   // Assign locations to all of the incoming arguments.
1510   SmallVector<CCValAssign, 16> ArgLocs;
1511   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1512                  ArgLocs, *DAG.getContext());
1513   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1514
1515   unsigned LastVal = ~0U;
1516   SDValue ArgValue;
1517   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1518     CCValAssign &VA = ArgLocs[i];
1519     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1520     // places.
1521     assert(VA.getValNo() != LastVal &&
1522            "Don't support value assigned to multiple locs yet");
1523     LastVal = VA.getValNo();
1524
1525     if (VA.isRegLoc()) {
1526       EVT RegVT = VA.getLocVT();
1527       TargetRegisterClass *RC = NULL;
1528       if (RegVT == MVT::i32)
1529         RC = X86::GR32RegisterClass;
1530       else if (Is64Bit && RegVT == MVT::i64)
1531         RC = X86::GR64RegisterClass;
1532       else if (RegVT == MVT::f32)
1533         RC = X86::FR32RegisterClass;
1534       else if (RegVT == MVT::f64)
1535         RC = X86::FR64RegisterClass;
1536       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1537         RC = X86::VR128RegisterClass;
1538       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1539         RC = X86::VR64RegisterClass;
1540       else
1541         llvm_unreachable("Unknown argument type!");
1542
1543       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1544       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1545
1546       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1547       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1548       // right size.
1549       if (VA.getLocInfo() == CCValAssign::SExt)
1550         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1551                                DAG.getValueType(VA.getValVT()));
1552       else if (VA.getLocInfo() == CCValAssign::ZExt)
1553         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1554                                DAG.getValueType(VA.getValVT()));
1555       else if (VA.getLocInfo() == CCValAssign::BCvt)
1556         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1557
1558       if (VA.isExtInLoc()) {
1559         // Handle MMX values passed in XMM regs.
1560         if (RegVT.isVector()) {
1561           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1562                                  ArgValue, DAG.getConstant(0, MVT::i64));
1563           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1564         } else
1565           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1566       }
1567     } else {
1568       assert(VA.isMemLoc());
1569       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1570     }
1571
1572     // If value is passed via pointer - do a load.
1573     if (VA.getLocInfo() == CCValAssign::Indirect)
1574       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1575                              false, false, 0);
1576
1577     InVals.push_back(ArgValue);
1578   }
1579
1580   // The x86-64 ABI for returning structs by value requires that we copy
1581   // the sret argument into %rax for the return. Save the argument into
1582   // a virtual register so that we can access it from the return points.
1583   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1584     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1585     unsigned Reg = FuncInfo->getSRetReturnReg();
1586     if (!Reg) {
1587       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1588       FuncInfo->setSRetReturnReg(Reg);
1589     }
1590     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1591     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1592   }
1593
1594   unsigned StackSize = CCInfo.getNextStackOffset();
1595   // Align stack specially for tail calls.
1596   if (FuncIsMadeTailCallSafe(CallConv))
1597     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1598
1599   // If the function takes variable number of arguments, make a frame index for
1600   // the start of the first vararg value... for expansion of llvm.va_start.
1601   if (isVarArg) {
1602     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1603                     CallConv != CallingConv::X86_ThisCall)) {
1604       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1605                                                             true, false));
1606     }
1607     if (Is64Bit) {
1608       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1609
1610       // FIXME: We should really autogenerate these arrays
1611       static const unsigned GPR64ArgRegsWin64[] = {
1612         X86::RCX, X86::RDX, X86::R8,  X86::R9
1613       };
1614       static const unsigned XMMArgRegsWin64[] = {
1615         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1616       };
1617       static const unsigned GPR64ArgRegs64Bit[] = {
1618         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1619       };
1620       static const unsigned XMMArgRegs64Bit[] = {
1621         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1622         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1623       };
1624       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1625
1626       if (IsWin64) {
1627         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1628         GPR64ArgRegs = GPR64ArgRegsWin64;
1629         XMMArgRegs = XMMArgRegsWin64;
1630       } else {
1631         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1632         GPR64ArgRegs = GPR64ArgRegs64Bit;
1633         XMMArgRegs = XMMArgRegs64Bit;
1634       }
1635       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1636                                                        TotalNumIntRegs);
1637       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1638                                                        TotalNumXMMRegs);
1639
1640       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1641       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1642              "SSE register cannot be used when SSE is disabled!");
1643       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1644              "SSE register cannot be used when SSE is disabled!");
1645       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1646         // Kernel mode asks for SSE to be disabled, so don't push them
1647         // on the stack.
1648         TotalNumXMMRegs = 0;
1649
1650       // For X86-64, if there are vararg parameters that are passed via
1651       // registers, then we must store them to their spots on the stack so they
1652       // may be loaded by deferencing the result of va_next.
1653       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1654       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1655       FuncInfo->setRegSaveFrameIndex(
1656         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1657                                false));
1658
1659       // Store the integer parameter registers.
1660       SmallVector<SDValue, 8> MemOps;
1661       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1662                                         getPointerTy());
1663       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1664       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1665         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1666                                   DAG.getIntPtrConstant(Offset));
1667         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1668                                      X86::GR64RegisterClass);
1669         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1670         SDValue Store =
1671           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1672                        PseudoSourceValue::getFixedStack(
1673                          FuncInfo->getRegSaveFrameIndex()),
1674                        Offset, false, false, 0);
1675         MemOps.push_back(Store);
1676         Offset += 8;
1677       }
1678
1679       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1680         // Now store the XMM (fp + vector) parameter registers.
1681         SmallVector<SDValue, 11> SaveXMMOps;
1682         SaveXMMOps.push_back(Chain);
1683
1684         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1685         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1686         SaveXMMOps.push_back(ALVal);
1687
1688         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1689                                FuncInfo->getRegSaveFrameIndex()));
1690         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1691                                FuncInfo->getVarArgsFPOffset()));
1692
1693         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1694           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1695                                        X86::VR128RegisterClass);
1696           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1697           SaveXMMOps.push_back(Val);
1698         }
1699         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1700                                      MVT::Other,
1701                                      &SaveXMMOps[0], SaveXMMOps.size()));
1702       }
1703
1704       if (!MemOps.empty())
1705         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1706                             &MemOps[0], MemOps.size());
1707     }
1708   }
1709
1710   // Some CCs need callee pop.
1711   if (IsCalleePop(isVarArg, CallConv)) {
1712     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1713   } else {
1714     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1715     // If this is an sret function, the return should pop the hidden pointer.
1716     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1717       FuncInfo->setBytesToPopOnReturn(4);
1718   }
1719
1720   if (!Is64Bit) {
1721     // RegSaveFrameIndex is X86-64 only.
1722     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1723     if (CallConv == CallingConv::X86_FastCall ||
1724         CallConv == CallingConv::X86_ThisCall)
1725       // fastcc functions can't have varargs.
1726       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1727   }
1728
1729   return Chain;
1730 }
1731
1732 SDValue
1733 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1734                                     SDValue StackPtr, SDValue Arg,
1735                                     DebugLoc dl, SelectionDAG &DAG,
1736                                     const CCValAssign &VA,
1737                                     ISD::ArgFlagsTy Flags) const {
1738   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1739   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1740   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1741   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1742   if (Flags.isByVal()) {
1743     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1744   }
1745   return DAG.getStore(Chain, dl, Arg, PtrOff,
1746                       PseudoSourceValue::getStack(), LocMemOffset,
1747                       false, false, 0);
1748 }
1749
1750 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1751 /// optimization is performed and it is required.
1752 SDValue
1753 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1754                                            SDValue &OutRetAddr, SDValue Chain,
1755                                            bool IsTailCall, bool Is64Bit,
1756                                            int FPDiff, DebugLoc dl) const {
1757   // Adjust the Return address stack slot.
1758   EVT VT = getPointerTy();
1759   OutRetAddr = getReturnAddressFrameIndex(DAG);
1760
1761   // Load the "old" Return address.
1762   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1763   return SDValue(OutRetAddr.getNode(), 1);
1764 }
1765
1766 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1767 /// optimization is performed and it is required (FPDiff!=0).
1768 static SDValue
1769 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1770                          SDValue Chain, SDValue RetAddrFrIdx,
1771                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1772   // Store the return address to the appropriate stack slot.
1773   if (!FPDiff) return Chain;
1774   // Calculate the new stack slot for the return address.
1775   int SlotSize = Is64Bit ? 8 : 4;
1776   int NewReturnAddrFI =
1777     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1778   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1779   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1780   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1781                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1782                        false, false, 0);
1783   return Chain;
1784 }
1785
1786 SDValue
1787 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1788                              CallingConv::ID CallConv, bool isVarArg,
1789                              bool &isTailCall,
1790                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1791                              const SmallVectorImpl<ISD::InputArg> &Ins,
1792                              DebugLoc dl, SelectionDAG &DAG,
1793                              SmallVectorImpl<SDValue> &InVals) const {
1794   MachineFunction &MF = DAG.getMachineFunction();
1795   bool Is64Bit        = Subtarget->is64Bit();
1796   bool IsStructRet    = CallIsStructReturn(Outs);
1797   bool IsSibcall      = false;
1798
1799   if (isTailCall) {
1800     // Check if it's really possible to do a tail call.
1801     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1802                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1803                                                    Outs, Ins, DAG);
1804
1805     // Sibcalls are automatically detected tailcalls which do not require
1806     // ABI changes.
1807     if (!GuaranteedTailCallOpt && isTailCall)
1808       IsSibcall = true;
1809
1810     if (isTailCall)
1811       ++NumTailCalls;
1812   }
1813
1814   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1815          "Var args not supported with calling convention fastcc or ghc");
1816
1817   // Analyze operands of the call, assigning locations to each operand.
1818   SmallVector<CCValAssign, 16> ArgLocs;
1819   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1820                  ArgLocs, *DAG.getContext());
1821   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1822
1823   // Get a count of how many bytes are to be pushed on the stack.
1824   unsigned NumBytes = CCInfo.getNextStackOffset();
1825   if (IsSibcall)
1826     // This is a sibcall. The memory operands are available in caller's
1827     // own caller's stack.
1828     NumBytes = 0;
1829   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1830     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1831
1832   int FPDiff = 0;
1833   if (isTailCall && !IsSibcall) {
1834     // Lower arguments at fp - stackoffset + fpdiff.
1835     unsigned NumBytesCallerPushed =
1836       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1837     FPDiff = NumBytesCallerPushed - NumBytes;
1838
1839     // Set the delta of movement of the returnaddr stackslot.
1840     // But only set if delta is greater than previous delta.
1841     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1842       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1843   }
1844
1845   if (!IsSibcall)
1846     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1847
1848   SDValue RetAddrFrIdx;
1849   // Load return adress for tail calls.
1850   if (isTailCall && FPDiff)
1851     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1852                                     Is64Bit, FPDiff, dl);
1853
1854   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1855   SmallVector<SDValue, 8> MemOpChains;
1856   SDValue StackPtr;
1857
1858   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1859   // of tail call optimization arguments are handle later.
1860   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1861     CCValAssign &VA = ArgLocs[i];
1862     EVT RegVT = VA.getLocVT();
1863     SDValue Arg = Outs[i].Val;
1864     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1865     bool isByVal = Flags.isByVal();
1866
1867     // Promote the value if needed.
1868     switch (VA.getLocInfo()) {
1869     default: llvm_unreachable("Unknown loc info!");
1870     case CCValAssign::Full: break;
1871     case CCValAssign::SExt:
1872       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1873       break;
1874     case CCValAssign::ZExt:
1875       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1876       break;
1877     case CCValAssign::AExt:
1878       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1879         // Special case: passing MMX values in XMM registers.
1880         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1881         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1882         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1883       } else
1884         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1885       break;
1886     case CCValAssign::BCvt:
1887       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1888       break;
1889     case CCValAssign::Indirect: {
1890       // Store the argument.
1891       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1892       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1893       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1894                            PseudoSourceValue::getFixedStack(FI), 0,
1895                            false, false, 0);
1896       Arg = SpillSlot;
1897       break;
1898     }
1899     }
1900
1901     if (VA.isRegLoc()) {
1902       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1903     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1904       assert(VA.isMemLoc());
1905       if (StackPtr.getNode() == 0)
1906         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1907       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1908                                              dl, DAG, VA, Flags));
1909     }
1910   }
1911
1912   if (!MemOpChains.empty())
1913     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1914                         &MemOpChains[0], MemOpChains.size());
1915
1916   // Build a sequence of copy-to-reg nodes chained together with token chain
1917   // and flag operands which copy the outgoing args into registers.
1918   SDValue InFlag;
1919   // Tail call byval lowering might overwrite argument registers so in case of
1920   // tail call optimization the copies to registers are lowered later.
1921   if (!isTailCall)
1922     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1923       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1924                                RegsToPass[i].second, InFlag);
1925       InFlag = Chain.getValue(1);
1926     }
1927
1928   if (Subtarget->isPICStyleGOT()) {
1929     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1930     // GOT pointer.
1931     if (!isTailCall) {
1932       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1933                                DAG.getNode(X86ISD::GlobalBaseReg,
1934                                            DebugLoc(), getPointerTy()),
1935                                InFlag);
1936       InFlag = Chain.getValue(1);
1937     } else {
1938       // If we are tail calling and generating PIC/GOT style code load the
1939       // address of the callee into ECX. The value in ecx is used as target of
1940       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1941       // for tail calls on PIC/GOT architectures. Normally we would just put the
1942       // address of GOT into ebx and then call target@PLT. But for tail calls
1943       // ebx would be restored (since ebx is callee saved) before jumping to the
1944       // target@PLT.
1945
1946       // Note: The actual moving to ECX is done further down.
1947       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1948       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1949           !G->getGlobal()->hasProtectedVisibility())
1950         Callee = LowerGlobalAddress(Callee, DAG);
1951       else if (isa<ExternalSymbolSDNode>(Callee))
1952         Callee = LowerExternalSymbol(Callee, DAG);
1953     }
1954   }
1955
1956   if (Is64Bit && isVarArg) {
1957     // From AMD64 ABI document:
1958     // For calls that may call functions that use varargs or stdargs
1959     // (prototype-less calls or calls to functions containing ellipsis (...) in
1960     // the declaration) %al is used as hidden argument to specify the number
1961     // of SSE registers used. The contents of %al do not need to match exactly
1962     // the number of registers, but must be an ubound on the number of SSE
1963     // registers used and is in the range 0 - 8 inclusive.
1964
1965     // FIXME: Verify this on Win64
1966     // Count the number of XMM registers allocated.
1967     static const unsigned XMMArgRegs[] = {
1968       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1969       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1970     };
1971     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1972     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1973            && "SSE registers cannot be used when SSE is disabled");
1974
1975     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1976                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1977     InFlag = Chain.getValue(1);
1978   }
1979
1980
1981   // For tail calls lower the arguments to the 'real' stack slot.
1982   if (isTailCall) {
1983     // Force all the incoming stack arguments to be loaded from the stack
1984     // before any new outgoing arguments are stored to the stack, because the
1985     // outgoing stack slots may alias the incoming argument stack slots, and
1986     // the alias isn't otherwise explicit. This is slightly more conservative
1987     // than necessary, because it means that each store effectively depends
1988     // on every argument instead of just those arguments it would clobber.
1989     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1990
1991     SmallVector<SDValue, 8> MemOpChains2;
1992     SDValue FIN;
1993     int FI = 0;
1994     // Do not flag preceeding copytoreg stuff together with the following stuff.
1995     InFlag = SDValue();
1996     if (GuaranteedTailCallOpt) {
1997       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1998         CCValAssign &VA = ArgLocs[i];
1999         if (VA.isRegLoc())
2000           continue;
2001         assert(VA.isMemLoc());
2002         SDValue Arg = Outs[i].Val;
2003         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2004         // Create frame index.
2005         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2006         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2007         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2008         FIN = DAG.getFrameIndex(FI, getPointerTy());
2009
2010         if (Flags.isByVal()) {
2011           // Copy relative to framepointer.
2012           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2013           if (StackPtr.getNode() == 0)
2014             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2015                                           getPointerTy());
2016           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2017
2018           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2019                                                            ArgChain,
2020                                                            Flags, DAG, dl));
2021         } else {
2022           // Store relative to framepointer.
2023           MemOpChains2.push_back(
2024             DAG.getStore(ArgChain, dl, Arg, FIN,
2025                          PseudoSourceValue::getFixedStack(FI), 0,
2026                          false, false, 0));
2027         }
2028       }
2029     }
2030
2031     if (!MemOpChains2.empty())
2032       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2033                           &MemOpChains2[0], MemOpChains2.size());
2034
2035     // Copy arguments to their registers.
2036     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2037       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2038                                RegsToPass[i].second, InFlag);
2039       InFlag = Chain.getValue(1);
2040     }
2041     InFlag =SDValue();
2042
2043     // Store the return address to the appropriate stack slot.
2044     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2045                                      FPDiff, dl);
2046   }
2047
2048   bool WasGlobalOrExternal = false;
2049   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2050     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2051     // In the 64-bit large code model, we have to make all calls
2052     // through a register, since the call instruction's 32-bit
2053     // pc-relative offset may not be large enough to hold the whole
2054     // address.
2055   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2056     WasGlobalOrExternal = true;
2057     // If the callee is a GlobalAddress node (quite common, every direct call
2058     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2059     // it.
2060
2061     // We should use extra load for direct calls to dllimported functions in
2062     // non-JIT mode.
2063     const GlobalValue *GV = G->getGlobal();
2064     if (!GV->hasDLLImportLinkage()) {
2065       unsigned char OpFlags = 0;
2066
2067       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2068       // external symbols most go through the PLT in PIC mode.  If the symbol
2069       // has hidden or protected visibility, or if it is static or local, then
2070       // we don't need to use the PLT - we can directly call it.
2071       if (Subtarget->isTargetELF() &&
2072           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2073           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2074         OpFlags = X86II::MO_PLT;
2075       } else if (Subtarget->isPICStyleStubAny() &&
2076                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2077                Subtarget->getDarwinVers() < 9) {
2078         // PC-relative references to external symbols should go through $stub,
2079         // unless we're building with the leopard linker or later, which
2080         // automatically synthesizes these stubs.
2081         OpFlags = X86II::MO_DARWIN_STUB;
2082       }
2083
2084       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2085                                           G->getOffset(), OpFlags);
2086     }
2087   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2088     WasGlobalOrExternal = true;
2089     unsigned char OpFlags = 0;
2090
2091     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2092     // symbols should go through the PLT.
2093     if (Subtarget->isTargetELF() &&
2094         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2095       OpFlags = X86II::MO_PLT;
2096     } else if (Subtarget->isPICStyleStubAny() &&
2097              Subtarget->getDarwinVers() < 9) {
2098       // PC-relative references to external symbols should go through $stub,
2099       // unless we're building with the leopard linker or later, which
2100       // automatically synthesizes these stubs.
2101       OpFlags = X86II::MO_DARWIN_STUB;
2102     }
2103
2104     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2105                                          OpFlags);
2106   }
2107
2108   // Returns a chain & a flag for retval copy to use.
2109   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2110   SmallVector<SDValue, 8> Ops;
2111
2112   if (!IsSibcall && isTailCall) {
2113     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2114                            DAG.getIntPtrConstant(0, true), InFlag);
2115     InFlag = Chain.getValue(1);
2116   }
2117
2118   Ops.push_back(Chain);
2119   Ops.push_back(Callee);
2120
2121   if (isTailCall)
2122     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2123
2124   // Add argument registers to the end of the list so that they are known live
2125   // into the call.
2126   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2127     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2128                                   RegsToPass[i].second.getValueType()));
2129
2130   // Add an implicit use GOT pointer in EBX.
2131   if (!isTailCall && Subtarget->isPICStyleGOT())
2132     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2133
2134   // Add an implicit use of AL for x86 vararg functions.
2135   if (Is64Bit && isVarArg)
2136     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2137
2138   if (InFlag.getNode())
2139     Ops.push_back(InFlag);
2140
2141   if (isTailCall) {
2142     // If this is the first return lowered for this function, add the regs
2143     // to the liveout set for the function.
2144     if (MF.getRegInfo().liveout_empty()) {
2145       SmallVector<CCValAssign, 16> RVLocs;
2146       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2147                      *DAG.getContext());
2148       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2149       for (unsigned i = 0; i != RVLocs.size(); ++i)
2150         if (RVLocs[i].isRegLoc())
2151           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2152     }
2153     return DAG.getNode(X86ISD::TC_RETURN, dl,
2154                        NodeTys, &Ops[0], Ops.size());
2155   }
2156
2157   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2158   InFlag = Chain.getValue(1);
2159
2160   // Create the CALLSEQ_END node.
2161   unsigned NumBytesForCalleeToPush;
2162   if (IsCalleePop(isVarArg, CallConv))
2163     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2164   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2165     // If this is a call to a struct-return function, the callee
2166     // pops the hidden struct pointer, so we have to push it back.
2167     // This is common for Darwin/X86, Linux & Mingw32 targets.
2168     NumBytesForCalleeToPush = 4;
2169   else
2170     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2171
2172   // Returns a flag for retval copy to use.
2173   if (!IsSibcall) {
2174     Chain = DAG.getCALLSEQ_END(Chain,
2175                                DAG.getIntPtrConstant(NumBytes, true),
2176                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2177                                                      true),
2178                                InFlag);
2179     InFlag = Chain.getValue(1);
2180   }
2181
2182   // Handle result values, copying them out of physregs into vregs that we
2183   // return.
2184   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2185                          Ins, dl, DAG, InVals);
2186 }
2187
2188
2189 //===----------------------------------------------------------------------===//
2190 //                Fast Calling Convention (tail call) implementation
2191 //===----------------------------------------------------------------------===//
2192
2193 //  Like std call, callee cleans arguments, convention except that ECX is
2194 //  reserved for storing the tail called function address. Only 2 registers are
2195 //  free for argument passing (inreg). Tail call optimization is performed
2196 //  provided:
2197 //                * tailcallopt is enabled
2198 //                * caller/callee are fastcc
2199 //  On X86_64 architecture with GOT-style position independent code only local
2200 //  (within module) calls are supported at the moment.
2201 //  To keep the stack aligned according to platform abi the function
2202 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2203 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2204 //  If a tail called function callee has more arguments than the caller the
2205 //  caller needs to make sure that there is room to move the RETADDR to. This is
2206 //  achieved by reserving an area the size of the argument delta right after the
2207 //  original REtADDR, but before the saved framepointer or the spilled registers
2208 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2209 //  stack layout:
2210 //    arg1
2211 //    arg2
2212 //    RETADDR
2213 //    [ new RETADDR
2214 //      move area ]
2215 //    (possible EBP)
2216 //    ESI
2217 //    EDI
2218 //    local1 ..
2219
2220 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2221 /// for a 16 byte align requirement.
2222 unsigned
2223 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2224                                                SelectionDAG& DAG) const {
2225   MachineFunction &MF = DAG.getMachineFunction();
2226   const TargetMachine &TM = MF.getTarget();
2227   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2228   unsigned StackAlignment = TFI.getStackAlignment();
2229   uint64_t AlignMask = StackAlignment - 1;
2230   int64_t Offset = StackSize;
2231   uint64_t SlotSize = TD->getPointerSize();
2232   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2233     // Number smaller than 12 so just add the difference.
2234     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2235   } else {
2236     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2237     Offset = ((~AlignMask) & Offset) + StackAlignment +
2238       (StackAlignment-SlotSize);
2239   }
2240   return Offset;
2241 }
2242
2243 /// MatchingStackOffset - Return true if the given stack call argument is
2244 /// already available in the same position (relatively) of the caller's
2245 /// incoming argument stack.
2246 static
2247 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2248                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2249                          const X86InstrInfo *TII) {
2250   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2251   int FI = INT_MAX;
2252   if (Arg.getOpcode() == ISD::CopyFromReg) {
2253     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2254     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2255       return false;
2256     MachineInstr *Def = MRI->getVRegDef(VR);
2257     if (!Def)
2258       return false;
2259     if (!Flags.isByVal()) {
2260       if (!TII->isLoadFromStackSlot(Def, FI))
2261         return false;
2262     } else {
2263       unsigned Opcode = Def->getOpcode();
2264       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2265           Def->getOperand(1).isFI()) {
2266         FI = Def->getOperand(1).getIndex();
2267         Bytes = Flags.getByValSize();
2268       } else
2269         return false;
2270     }
2271   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2272     if (Flags.isByVal())
2273       // ByVal argument is passed in as a pointer but it's now being
2274       // dereferenced. e.g.
2275       // define @foo(%struct.X* %A) {
2276       //   tail call @bar(%struct.X* byval %A)
2277       // }
2278       return false;
2279     SDValue Ptr = Ld->getBasePtr();
2280     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2281     if (!FINode)
2282       return false;
2283     FI = FINode->getIndex();
2284   } else
2285     return false;
2286
2287   assert(FI != INT_MAX);
2288   if (!MFI->isFixedObjectIndex(FI))
2289     return false;
2290   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2291 }
2292
2293 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2294 /// for tail call optimization. Targets which want to do tail call
2295 /// optimization should implement this function.
2296 bool
2297 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2298                                                      CallingConv::ID CalleeCC,
2299                                                      bool isVarArg,
2300                                                      bool isCalleeStructRet,
2301                                                      bool isCallerStructRet,
2302                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2303                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2304                                                      SelectionDAG& DAG) const {
2305   if (!IsTailCallConvention(CalleeCC) &&
2306       CalleeCC != CallingConv::C)
2307     return false;
2308
2309   // If -tailcallopt is specified, make fastcc functions tail-callable.
2310   const MachineFunction &MF = DAG.getMachineFunction();
2311   const Function *CallerF = DAG.getMachineFunction().getFunction();
2312   CallingConv::ID CallerCC = CallerF->getCallingConv();
2313   bool CCMatch = CallerCC == CalleeCC;
2314
2315   if (GuaranteedTailCallOpt) {
2316     if (IsTailCallConvention(CalleeCC) && CCMatch)
2317       return true;
2318     return false;
2319   }
2320
2321   // Look for obvious safe cases to perform tail call optimization that does not
2322   // requite ABI changes. This is what gcc calls sibcall.
2323
2324   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2325   // emit a special epilogue.
2326   if (RegInfo->needsStackRealignment(MF))
2327     return false;
2328
2329   // Do not sibcall optimize vararg calls unless the call site is not passing any
2330   // arguments.
2331   if (isVarArg && !Outs.empty())
2332     return false;
2333
2334   // Also avoid sibcall optimization if either caller or callee uses struct
2335   // return semantics.
2336   if (isCalleeStructRet || isCallerStructRet)
2337     return false;
2338
2339   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2340   // Therefore if it's not used by the call it is not safe to optimize this into
2341   // a sibcall.
2342   bool Unused = false;
2343   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2344     if (!Ins[i].Used) {
2345       Unused = true;
2346       break;
2347     }
2348   }
2349   if (Unused) {
2350     SmallVector<CCValAssign, 16> RVLocs;
2351     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2352                    RVLocs, *DAG.getContext());
2353     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2354     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2355       CCValAssign &VA = RVLocs[i];
2356       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2357         return false;
2358     }
2359   }
2360
2361   // If the calling conventions do not match, then we'd better make sure the
2362   // results are returned in the same way as what the caller expects.
2363   if (!CCMatch) {
2364     SmallVector<CCValAssign, 16> RVLocs1;
2365     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2366                     RVLocs1, *DAG.getContext());
2367     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2368
2369     SmallVector<CCValAssign, 16> RVLocs2;
2370     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2371                     RVLocs2, *DAG.getContext());
2372     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2373
2374     if (RVLocs1.size() != RVLocs2.size())
2375       return false;
2376     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2377       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2378         return false;
2379       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2380         return false;
2381       if (RVLocs1[i].isRegLoc()) {
2382         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2383           return false;
2384       } else {
2385         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2386           return false;
2387       }
2388     }
2389   }
2390
2391   // If the callee takes no arguments then go on to check the results of the
2392   // call.
2393   if (!Outs.empty()) {
2394     // Check if stack adjustment is needed. For now, do not do this if any
2395     // argument is passed on the stack.
2396     SmallVector<CCValAssign, 16> ArgLocs;
2397     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2398                    ArgLocs, *DAG.getContext());
2399     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2400     if (CCInfo.getNextStackOffset()) {
2401       MachineFunction &MF = DAG.getMachineFunction();
2402       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2403         return false;
2404       if (Subtarget->isTargetWin64())
2405         // Win64 ABI has additional complications.
2406         return false;
2407
2408       // Check if the arguments are already laid out in the right way as
2409       // the caller's fixed stack objects.
2410       MachineFrameInfo *MFI = MF.getFrameInfo();
2411       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2412       const X86InstrInfo *TII =
2413         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2414       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2415         CCValAssign &VA = ArgLocs[i];
2416         EVT RegVT = VA.getLocVT();
2417         SDValue Arg = Outs[i].Val;
2418         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419         if (VA.getLocInfo() == CCValAssign::Indirect)
2420           return false;
2421         if (!VA.isRegLoc()) {
2422           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2423                                    MFI, MRI, TII))
2424             return false;
2425         }
2426       }
2427     }
2428   }
2429
2430   return true;
2431 }
2432
2433 FastISel *
2434 X86TargetLowering::createFastISel(MachineFunction &mf,
2435                             DenseMap<const Value *, unsigned> &vm,
2436                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2437                             DenseMap<const AllocaInst *, int> &am,
2438                             std::vector<std::pair<MachineInstr*, unsigned> > &pn
2439 #ifndef NDEBUG
2440                           , SmallSet<const Instruction *, 8> &cil
2441 #endif
2442                                   ) const {
2443   return X86::createFastISel(mf, vm, bm, am, pn
2444 #ifndef NDEBUG
2445                              , cil
2446 #endif
2447                              );
2448 }
2449
2450
2451 //===----------------------------------------------------------------------===//
2452 //                           Other Lowering Hooks
2453 //===----------------------------------------------------------------------===//
2454
2455
2456 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2457   MachineFunction &MF = DAG.getMachineFunction();
2458   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2459   int ReturnAddrIndex = FuncInfo->getRAIndex();
2460
2461   if (ReturnAddrIndex == 0) {
2462     // Set up a frame object for the return address.
2463     uint64_t SlotSize = TD->getPointerSize();
2464     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2465                                                            false, false);
2466     FuncInfo->setRAIndex(ReturnAddrIndex);
2467   }
2468
2469   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2470 }
2471
2472
2473 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2474                                        bool hasSymbolicDisplacement) {
2475   // Offset should fit into 32 bit immediate field.
2476   if (!isInt<32>(Offset))
2477     return false;
2478
2479   // If we don't have a symbolic displacement - we don't have any extra
2480   // restrictions.
2481   if (!hasSymbolicDisplacement)
2482     return true;
2483
2484   // FIXME: Some tweaks might be needed for medium code model.
2485   if (M != CodeModel::Small && M != CodeModel::Kernel)
2486     return false;
2487
2488   // For small code model we assume that latest object is 16MB before end of 31
2489   // bits boundary. We may also accept pretty large negative constants knowing
2490   // that all objects are in the positive half of address space.
2491   if (M == CodeModel::Small && Offset < 16*1024*1024)
2492     return true;
2493
2494   // For kernel code model we know that all object resist in the negative half
2495   // of 32bits address space. We may not accept negative offsets, since they may
2496   // be just off and we may accept pretty large positive ones.
2497   if (M == CodeModel::Kernel && Offset > 0)
2498     return true;
2499
2500   return false;
2501 }
2502
2503 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2504 /// specific condition code, returning the condition code and the LHS/RHS of the
2505 /// comparison to make.
2506 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2507                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2508   if (!isFP) {
2509     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2510       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2511         // X > -1   -> X == 0, jump !sign.
2512         RHS = DAG.getConstant(0, RHS.getValueType());
2513         return X86::COND_NS;
2514       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2515         // X < 0   -> X == 0, jump on sign.
2516         return X86::COND_S;
2517       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2518         // X < 1   -> X <= 0
2519         RHS = DAG.getConstant(0, RHS.getValueType());
2520         return X86::COND_LE;
2521       }
2522     }
2523
2524     switch (SetCCOpcode) {
2525     default: llvm_unreachable("Invalid integer condition!");
2526     case ISD::SETEQ:  return X86::COND_E;
2527     case ISD::SETGT:  return X86::COND_G;
2528     case ISD::SETGE:  return X86::COND_GE;
2529     case ISD::SETLT:  return X86::COND_L;
2530     case ISD::SETLE:  return X86::COND_LE;
2531     case ISD::SETNE:  return X86::COND_NE;
2532     case ISD::SETULT: return X86::COND_B;
2533     case ISD::SETUGT: return X86::COND_A;
2534     case ISD::SETULE: return X86::COND_BE;
2535     case ISD::SETUGE: return X86::COND_AE;
2536     }
2537   }
2538
2539   // First determine if it is required or is profitable to flip the operands.
2540
2541   // If LHS is a foldable load, but RHS is not, flip the condition.
2542   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2543       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2544     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2545     std::swap(LHS, RHS);
2546   }
2547
2548   switch (SetCCOpcode) {
2549   default: break;
2550   case ISD::SETOLT:
2551   case ISD::SETOLE:
2552   case ISD::SETUGT:
2553   case ISD::SETUGE:
2554     std::swap(LHS, RHS);
2555     break;
2556   }
2557
2558   // On a floating point condition, the flags are set as follows:
2559   // ZF  PF  CF   op
2560   //  0 | 0 | 0 | X > Y
2561   //  0 | 0 | 1 | X < Y
2562   //  1 | 0 | 0 | X == Y
2563   //  1 | 1 | 1 | unordered
2564   switch (SetCCOpcode) {
2565   default: llvm_unreachable("Condcode should be pre-legalized away");
2566   case ISD::SETUEQ:
2567   case ISD::SETEQ:   return X86::COND_E;
2568   case ISD::SETOLT:              // flipped
2569   case ISD::SETOGT:
2570   case ISD::SETGT:   return X86::COND_A;
2571   case ISD::SETOLE:              // flipped
2572   case ISD::SETOGE:
2573   case ISD::SETGE:   return X86::COND_AE;
2574   case ISD::SETUGT:              // flipped
2575   case ISD::SETULT:
2576   case ISD::SETLT:   return X86::COND_B;
2577   case ISD::SETUGE:              // flipped
2578   case ISD::SETULE:
2579   case ISD::SETLE:   return X86::COND_BE;
2580   case ISD::SETONE:
2581   case ISD::SETNE:   return X86::COND_NE;
2582   case ISD::SETUO:   return X86::COND_P;
2583   case ISD::SETO:    return X86::COND_NP;
2584   case ISD::SETOEQ:
2585   case ISD::SETUNE:  return X86::COND_INVALID;
2586   }
2587 }
2588
2589 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2590 /// code. Current x86 isa includes the following FP cmov instructions:
2591 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2592 static bool hasFPCMov(unsigned X86CC) {
2593   switch (X86CC) {
2594   default:
2595     return false;
2596   case X86::COND_B:
2597   case X86::COND_BE:
2598   case X86::COND_E:
2599   case X86::COND_P:
2600   case X86::COND_A:
2601   case X86::COND_AE:
2602   case X86::COND_NE:
2603   case X86::COND_NP:
2604     return true;
2605   }
2606 }
2607
2608 /// isFPImmLegal - Returns true if the target can instruction select the
2609 /// specified FP immediate natively. If false, the legalizer will
2610 /// materialize the FP immediate as a load from a constant pool.
2611 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2612   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2613     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2614       return true;
2615   }
2616   return false;
2617 }
2618
2619 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2620 /// the specified range (L, H].
2621 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2622   return (Val < 0) || (Val >= Low && Val < Hi);
2623 }
2624
2625 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2626 /// specified value.
2627 static bool isUndefOrEqual(int Val, int CmpVal) {
2628   if (Val < 0 || Val == CmpVal)
2629     return true;
2630   return false;
2631 }
2632
2633 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2634 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2635 /// the second operand.
2636 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2637   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2638     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2639   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2640     return (Mask[0] < 2 && Mask[1] < 2);
2641   return false;
2642 }
2643
2644 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2645   SmallVector<int, 8> M;
2646   N->getMask(M);
2647   return ::isPSHUFDMask(M, N->getValueType(0));
2648 }
2649
2650 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2651 /// is suitable for input to PSHUFHW.
2652 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2653   if (VT != MVT::v8i16)
2654     return false;
2655
2656   // Lower quadword copied in order or undef.
2657   for (int i = 0; i != 4; ++i)
2658     if (Mask[i] >= 0 && Mask[i] != i)
2659       return false;
2660
2661   // Upper quadword shuffled.
2662   for (int i = 4; i != 8; ++i)
2663     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2664       return false;
2665
2666   return true;
2667 }
2668
2669 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2670   SmallVector<int, 8> M;
2671   N->getMask(M);
2672   return ::isPSHUFHWMask(M, N->getValueType(0));
2673 }
2674
2675 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2676 /// is suitable for input to PSHUFLW.
2677 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2678   if (VT != MVT::v8i16)
2679     return false;
2680
2681   // Upper quadword copied in order.
2682   for (int i = 4; i != 8; ++i)
2683     if (Mask[i] >= 0 && Mask[i] != i)
2684       return false;
2685
2686   // Lower quadword shuffled.
2687   for (int i = 0; i != 4; ++i)
2688     if (Mask[i] >= 4)
2689       return false;
2690
2691   return true;
2692 }
2693
2694 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2695   SmallVector<int, 8> M;
2696   N->getMask(M);
2697   return ::isPSHUFLWMask(M, N->getValueType(0));
2698 }
2699
2700 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2701 /// is suitable for input to PALIGNR.
2702 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2703                           bool hasSSSE3) {
2704   int i, e = VT.getVectorNumElements();
2705   
2706   // Do not handle v2i64 / v2f64 shuffles with palignr.
2707   if (e < 4 || !hasSSSE3)
2708     return false;
2709   
2710   for (i = 0; i != e; ++i)
2711     if (Mask[i] >= 0)
2712       break;
2713   
2714   // All undef, not a palignr.
2715   if (i == e)
2716     return false;
2717
2718   // Determine if it's ok to perform a palignr with only the LHS, since we
2719   // don't have access to the actual shuffle elements to see if RHS is undef.
2720   bool Unary = Mask[i] < (int)e;
2721   bool NeedsUnary = false;
2722
2723   int s = Mask[i] - i;
2724   
2725   // Check the rest of the elements to see if they are consecutive.
2726   for (++i; i != e; ++i) {
2727     int m = Mask[i];
2728     if (m < 0) 
2729       continue;
2730     
2731     Unary = Unary && (m < (int)e);
2732     NeedsUnary = NeedsUnary || (m < s);
2733
2734     if (NeedsUnary && !Unary)
2735       return false;
2736     if (Unary && m != ((s+i) & (e-1)))
2737       return false;
2738     if (!Unary && m != (s+i))
2739       return false;
2740   }
2741   return true;
2742 }
2743
2744 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2745   SmallVector<int, 8> M;
2746   N->getMask(M);
2747   return ::isPALIGNRMask(M, N->getValueType(0), true);
2748 }
2749
2750 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2751 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2752 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2753   int NumElems = VT.getVectorNumElements();
2754   if (NumElems != 2 && NumElems != 4)
2755     return false;
2756
2757   int Half = NumElems / 2;
2758   for (int i = 0; i < Half; ++i)
2759     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2760       return false;
2761   for (int i = Half; i < NumElems; ++i)
2762     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2763       return false;
2764
2765   return true;
2766 }
2767
2768 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2769   SmallVector<int, 8> M;
2770   N->getMask(M);
2771   return ::isSHUFPMask(M, N->getValueType(0));
2772 }
2773
2774 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2775 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2776 /// half elements to come from vector 1 (which would equal the dest.) and
2777 /// the upper half to come from vector 2.
2778 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2779   int NumElems = VT.getVectorNumElements();
2780
2781   if (NumElems != 2 && NumElems != 4)
2782     return false;
2783
2784   int Half = NumElems / 2;
2785   for (int i = 0; i < Half; ++i)
2786     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2787       return false;
2788   for (int i = Half; i < NumElems; ++i)
2789     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2790       return false;
2791   return true;
2792 }
2793
2794 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2795   SmallVector<int, 8> M;
2796   N->getMask(M);
2797   return isCommutedSHUFPMask(M, N->getValueType(0));
2798 }
2799
2800 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2801 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2802 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2803   if (N->getValueType(0).getVectorNumElements() != 4)
2804     return false;
2805
2806   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2807   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2808          isUndefOrEqual(N->getMaskElt(1), 7) &&
2809          isUndefOrEqual(N->getMaskElt(2), 2) &&
2810          isUndefOrEqual(N->getMaskElt(3), 3);
2811 }
2812
2813 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2814 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2815 /// <2, 3, 2, 3>
2816 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2817   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2818   
2819   if (NumElems != 4)
2820     return false;
2821   
2822   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2823   isUndefOrEqual(N->getMaskElt(1), 3) &&
2824   isUndefOrEqual(N->getMaskElt(2), 2) &&
2825   isUndefOrEqual(N->getMaskElt(3), 3);
2826 }
2827
2828 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2829 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2830 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2831   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2832
2833   if (NumElems != 2 && NumElems != 4)
2834     return false;
2835
2836   for (unsigned i = 0; i < NumElems/2; ++i)
2837     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2838       return false;
2839
2840   for (unsigned i = NumElems/2; i < NumElems; ++i)
2841     if (!isUndefOrEqual(N->getMaskElt(i), i))
2842       return false;
2843
2844   return true;
2845 }
2846
2847 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2848 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2849 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2850   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2851
2852   if (NumElems != 2 && NumElems != 4)
2853     return false;
2854
2855   for (unsigned i = 0; i < NumElems/2; ++i)
2856     if (!isUndefOrEqual(N->getMaskElt(i), i))
2857       return false;
2858
2859   for (unsigned i = 0; i < NumElems/2; ++i)
2860     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2861       return false;
2862
2863   return true;
2864 }
2865
2866 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2867 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2868 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2869                          bool V2IsSplat = false) {
2870   int NumElts = VT.getVectorNumElements();
2871   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2872     return false;
2873
2874   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2875     int BitI  = Mask[i];
2876     int BitI1 = Mask[i+1];
2877     if (!isUndefOrEqual(BitI, j))
2878       return false;
2879     if (V2IsSplat) {
2880       if (!isUndefOrEqual(BitI1, NumElts))
2881         return false;
2882     } else {
2883       if (!isUndefOrEqual(BitI1, j + NumElts))
2884         return false;
2885     }
2886   }
2887   return true;
2888 }
2889
2890 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2891   SmallVector<int, 8> M;
2892   N->getMask(M);
2893   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2894 }
2895
2896 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2897 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2898 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2899                          bool V2IsSplat = false) {
2900   int NumElts = VT.getVectorNumElements();
2901   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2902     return false;
2903
2904   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2905     int BitI  = Mask[i];
2906     int BitI1 = Mask[i+1];
2907     if (!isUndefOrEqual(BitI, j + NumElts/2))
2908       return false;
2909     if (V2IsSplat) {
2910       if (isUndefOrEqual(BitI1, NumElts))
2911         return false;
2912     } else {
2913       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2914         return false;
2915     }
2916   }
2917   return true;
2918 }
2919
2920 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2921   SmallVector<int, 8> M;
2922   N->getMask(M);
2923   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2924 }
2925
2926 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2927 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2928 /// <0, 0, 1, 1>
2929 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2930   int NumElems = VT.getVectorNumElements();
2931   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2932     return false;
2933
2934   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2935     int BitI  = Mask[i];
2936     int BitI1 = Mask[i+1];
2937     if (!isUndefOrEqual(BitI, j))
2938       return false;
2939     if (!isUndefOrEqual(BitI1, j))
2940       return false;
2941   }
2942   return true;
2943 }
2944
2945 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2946   SmallVector<int, 8> M;
2947   N->getMask(M);
2948   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2949 }
2950
2951 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2952 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2953 /// <2, 2, 3, 3>
2954 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2955   int NumElems = VT.getVectorNumElements();
2956   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2957     return false;
2958
2959   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2960     int BitI  = Mask[i];
2961     int BitI1 = Mask[i+1];
2962     if (!isUndefOrEqual(BitI, j))
2963       return false;
2964     if (!isUndefOrEqual(BitI1, j))
2965       return false;
2966   }
2967   return true;
2968 }
2969
2970 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2971   SmallVector<int, 8> M;
2972   N->getMask(M);
2973   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2974 }
2975
2976 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2977 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2978 /// MOVSD, and MOVD, i.e. setting the lowest element.
2979 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2980   if (VT.getVectorElementType().getSizeInBits() < 32)
2981     return false;
2982
2983   int NumElts = VT.getVectorNumElements();
2984
2985   if (!isUndefOrEqual(Mask[0], NumElts))
2986     return false;
2987
2988   for (int i = 1; i < NumElts; ++i)
2989     if (!isUndefOrEqual(Mask[i], i))
2990       return false;
2991
2992   return true;
2993 }
2994
2995 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2996   SmallVector<int, 8> M;
2997   N->getMask(M);
2998   return ::isMOVLMask(M, N->getValueType(0));
2999 }
3000
3001 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3002 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3003 /// element of vector 2 and the other elements to come from vector 1 in order.
3004 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3005                                bool V2IsSplat = false, bool V2IsUndef = false) {
3006   int NumOps = VT.getVectorNumElements();
3007   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3008     return false;
3009
3010   if (!isUndefOrEqual(Mask[0], 0))
3011     return false;
3012
3013   for (int i = 1; i < NumOps; ++i)
3014     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3015           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3016           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3017       return false;
3018
3019   return true;
3020 }
3021
3022 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3023                            bool V2IsUndef = false) {
3024   SmallVector<int, 8> M;
3025   N->getMask(M);
3026   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3027 }
3028
3029 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3030 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3031 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3032   if (N->getValueType(0).getVectorNumElements() != 4)
3033     return false;
3034
3035   // Expect 1, 1, 3, 3
3036   for (unsigned i = 0; i < 2; ++i) {
3037     int Elt = N->getMaskElt(i);
3038     if (Elt >= 0 && Elt != 1)
3039       return false;
3040   }
3041
3042   bool HasHi = false;
3043   for (unsigned i = 2; i < 4; ++i) {
3044     int Elt = N->getMaskElt(i);
3045     if (Elt >= 0 && Elt != 3)
3046       return false;
3047     if (Elt == 3)
3048       HasHi = true;
3049   }
3050   // Don't use movshdup if it can be done with a shufps.
3051   // FIXME: verify that matching u, u, 3, 3 is what we want.
3052   return HasHi;
3053 }
3054
3055 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3056 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3057 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3058   if (N->getValueType(0).getVectorNumElements() != 4)
3059     return false;
3060
3061   // Expect 0, 0, 2, 2
3062   for (unsigned i = 0; i < 2; ++i)
3063     if (N->getMaskElt(i) > 0)
3064       return false;
3065
3066   bool HasHi = false;
3067   for (unsigned i = 2; i < 4; ++i) {
3068     int Elt = N->getMaskElt(i);
3069     if (Elt >= 0 && Elt != 2)
3070       return false;
3071     if (Elt == 2)
3072       HasHi = true;
3073   }
3074   // Don't use movsldup if it can be done with a shufps.
3075   return HasHi;
3076 }
3077
3078 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3079 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3080 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3081   int e = N->getValueType(0).getVectorNumElements() / 2;
3082
3083   for (int i = 0; i < e; ++i)
3084     if (!isUndefOrEqual(N->getMaskElt(i), i))
3085       return false;
3086   for (int i = 0; i < e; ++i)
3087     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3088       return false;
3089   return true;
3090 }
3091
3092 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3093 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3094 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3095   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3096   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3097
3098   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3099   unsigned Mask = 0;
3100   for (int i = 0; i < NumOperands; ++i) {
3101     int Val = SVOp->getMaskElt(NumOperands-i-1);
3102     if (Val < 0) Val = 0;
3103     if (Val >= NumOperands) Val -= NumOperands;
3104     Mask |= Val;
3105     if (i != NumOperands - 1)
3106       Mask <<= Shift;
3107   }
3108   return Mask;
3109 }
3110
3111 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3112 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3113 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3114   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3115   unsigned Mask = 0;
3116   // 8 nodes, but we only care about the last 4.
3117   for (unsigned i = 7; i >= 4; --i) {
3118     int Val = SVOp->getMaskElt(i);
3119     if (Val >= 0)
3120       Mask |= (Val - 4);
3121     if (i != 4)
3122       Mask <<= 2;
3123   }
3124   return Mask;
3125 }
3126
3127 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3128 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3129 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3131   unsigned Mask = 0;
3132   // 8 nodes, but we only care about the first 4.
3133   for (int i = 3; i >= 0; --i) {
3134     int Val = SVOp->getMaskElt(i);
3135     if (Val >= 0)
3136       Mask |= Val;
3137     if (i != 0)
3138       Mask <<= 2;
3139   }
3140   return Mask;
3141 }
3142
3143 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3144 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3145 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3146   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3147   EVT VVT = N->getValueType(0);
3148   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3149   int Val = 0;
3150
3151   unsigned i, e;
3152   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3153     Val = SVOp->getMaskElt(i);
3154     if (Val >= 0)
3155       break;
3156   }
3157   return (Val - i) * EltSize;
3158 }
3159
3160 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3161 /// constant +0.0.
3162 bool X86::isZeroNode(SDValue Elt) {
3163   return ((isa<ConstantSDNode>(Elt) &&
3164            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3165           (isa<ConstantFPSDNode>(Elt) &&
3166            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3167 }
3168
3169 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3170 /// their permute mask.
3171 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3172                                     SelectionDAG &DAG) {
3173   EVT VT = SVOp->getValueType(0);
3174   unsigned NumElems = VT.getVectorNumElements();
3175   SmallVector<int, 8> MaskVec;
3176
3177   for (unsigned i = 0; i != NumElems; ++i) {
3178     int idx = SVOp->getMaskElt(i);
3179     if (idx < 0)
3180       MaskVec.push_back(idx);
3181     else if (idx < (int)NumElems)
3182       MaskVec.push_back(idx + NumElems);
3183     else
3184       MaskVec.push_back(idx - NumElems);
3185   }
3186   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3187                               SVOp->getOperand(0), &MaskVec[0]);
3188 }
3189
3190 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3191 /// the two vector operands have swapped position.
3192 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3193   unsigned NumElems = VT.getVectorNumElements();
3194   for (unsigned i = 0; i != NumElems; ++i) {
3195     int idx = Mask[i];
3196     if (idx < 0)
3197       continue;
3198     else if (idx < (int)NumElems)
3199       Mask[i] = idx + NumElems;
3200     else
3201       Mask[i] = idx - NumElems;
3202   }
3203 }
3204
3205 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3206 /// match movhlps. The lower half elements should come from upper half of
3207 /// V1 (and in order), and the upper half elements should come from the upper
3208 /// half of V2 (and in order).
3209 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3210   if (Op->getValueType(0).getVectorNumElements() != 4)
3211     return false;
3212   for (unsigned i = 0, e = 2; i != e; ++i)
3213     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3214       return false;
3215   for (unsigned i = 2; i != 4; ++i)
3216     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3217       return false;
3218   return true;
3219 }
3220
3221 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3222 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3223 /// required.
3224 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3225   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3226     return false;
3227   N = N->getOperand(0).getNode();
3228   if (!ISD::isNON_EXTLoad(N))
3229     return false;
3230   if (LD)
3231     *LD = cast<LoadSDNode>(N);
3232   return true;
3233 }
3234
3235 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3236 /// match movlp{s|d}. The lower half elements should come from lower half of
3237 /// V1 (and in order), and the upper half elements should come from the upper
3238 /// half of V2 (and in order). And since V1 will become the source of the
3239 /// MOVLP, it must be either a vector load or a scalar load to vector.
3240 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3241                                ShuffleVectorSDNode *Op) {
3242   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3243     return false;
3244   // Is V2 is a vector load, don't do this transformation. We will try to use
3245   // load folding shufps op.
3246   if (ISD::isNON_EXTLoad(V2))
3247     return false;
3248
3249   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3250
3251   if (NumElems != 2 && NumElems != 4)
3252     return false;
3253   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3254     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3255       return false;
3256   for (unsigned i = NumElems/2; i != NumElems; ++i)
3257     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3258       return false;
3259   return true;
3260 }
3261
3262 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3263 /// all the same.
3264 static bool isSplatVector(SDNode *N) {
3265   if (N->getOpcode() != ISD::BUILD_VECTOR)
3266     return false;
3267
3268   SDValue SplatValue = N->getOperand(0);
3269   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3270     if (N->getOperand(i) != SplatValue)
3271       return false;
3272   return true;
3273 }
3274
3275 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3276 /// to an zero vector.
3277 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3278 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3279   SDValue V1 = N->getOperand(0);
3280   SDValue V2 = N->getOperand(1);
3281   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3282   for (unsigned i = 0; i != NumElems; ++i) {
3283     int Idx = N->getMaskElt(i);
3284     if (Idx >= (int)NumElems) {
3285       unsigned Opc = V2.getOpcode();
3286       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3287         continue;
3288       if (Opc != ISD::BUILD_VECTOR ||
3289           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3290         return false;
3291     } else if (Idx >= 0) {
3292       unsigned Opc = V1.getOpcode();
3293       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3294         continue;
3295       if (Opc != ISD::BUILD_VECTOR ||
3296           !X86::isZeroNode(V1.getOperand(Idx)))
3297         return false;
3298     }
3299   }
3300   return true;
3301 }
3302
3303 /// getZeroVector - Returns a vector of specified type with all zero elements.
3304 ///
3305 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3306                              DebugLoc dl) {
3307   assert(VT.isVector() && "Expected a vector type");
3308
3309   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3310   // type.  This ensures they get CSE'd.
3311   SDValue Vec;
3312   if (VT.getSizeInBits() == 64) { // MMX
3313     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3314     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3315   } else if (HasSSE2) {  // SSE2
3316     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3317     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3318   } else { // SSE1
3319     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3320     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3321   }
3322   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3323 }
3324
3325 /// getOnesVector - Returns a vector of specified type with all bits set.
3326 ///
3327 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3328   assert(VT.isVector() && "Expected a vector type");
3329
3330   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3331   // type.  This ensures they get CSE'd.
3332   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3333   SDValue Vec;
3334   if (VT.getSizeInBits() == 64)  // MMX
3335     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3336   else                                              // SSE
3337     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3338   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3339 }
3340
3341
3342 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3343 /// that point to V2 points to its first element.
3344 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3345   EVT VT = SVOp->getValueType(0);
3346   unsigned NumElems = VT.getVectorNumElements();
3347
3348   bool Changed = false;
3349   SmallVector<int, 8> MaskVec;
3350   SVOp->getMask(MaskVec);
3351
3352   for (unsigned i = 0; i != NumElems; ++i) {
3353     if (MaskVec[i] > (int)NumElems) {
3354       MaskVec[i] = NumElems;
3355       Changed = true;
3356     }
3357   }
3358   if (Changed)
3359     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3360                                 SVOp->getOperand(1), &MaskVec[0]);
3361   return SDValue(SVOp, 0);
3362 }
3363
3364 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3365 /// operation of specified width.
3366 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3367                        SDValue V2) {
3368   unsigned NumElems = VT.getVectorNumElements();
3369   SmallVector<int, 8> Mask;
3370   Mask.push_back(NumElems);
3371   for (unsigned i = 1; i != NumElems; ++i)
3372     Mask.push_back(i);
3373   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3374 }
3375
3376 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3377 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3378                           SDValue V2) {
3379   unsigned NumElems = VT.getVectorNumElements();
3380   SmallVector<int, 8> Mask;
3381   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3382     Mask.push_back(i);
3383     Mask.push_back(i + NumElems);
3384   }
3385   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3386 }
3387
3388 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3389 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3390                           SDValue V2) {
3391   unsigned NumElems = VT.getVectorNumElements();
3392   unsigned Half = NumElems/2;
3393   SmallVector<int, 8> Mask;
3394   for (unsigned i = 0; i != Half; ++i) {
3395     Mask.push_back(i + Half);
3396     Mask.push_back(i + NumElems + Half);
3397   }
3398   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3399 }
3400
3401 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3402 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3403                             bool HasSSE2) {
3404   if (SV->getValueType(0).getVectorNumElements() <= 4)
3405     return SDValue(SV, 0);
3406
3407   EVT PVT = MVT::v4f32;
3408   EVT VT = SV->getValueType(0);
3409   DebugLoc dl = SV->getDebugLoc();
3410   SDValue V1 = SV->getOperand(0);
3411   int NumElems = VT.getVectorNumElements();
3412   int EltNo = SV->getSplatIndex();
3413
3414   // unpack elements to the correct location
3415   while (NumElems > 4) {
3416     if (EltNo < NumElems/2) {
3417       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3418     } else {
3419       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3420       EltNo -= NumElems/2;
3421     }
3422     NumElems >>= 1;
3423   }
3424
3425   // Perform the splat.
3426   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3427   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3428   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3429   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3430 }
3431
3432 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3433 /// vector of zero or undef vector.  This produces a shuffle where the low
3434 /// element of V2 is swizzled into the zero/undef vector, landing at element
3435 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3436 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3437                                              bool isZero, bool HasSSE2,
3438                                              SelectionDAG &DAG) {
3439   EVT VT = V2.getValueType();
3440   SDValue V1 = isZero
3441     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3442   unsigned NumElems = VT.getVectorNumElements();
3443   SmallVector<int, 16> MaskVec;
3444   for (unsigned i = 0; i != NumElems; ++i)
3445     // If this is the insertion idx, put the low elt of V2 here.
3446     MaskVec.push_back(i == Idx ? NumElems : i);
3447   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3448 }
3449
3450 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3451 /// a shuffle that is zero.
3452 static
3453 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3454                                   bool Low, SelectionDAG &DAG) {
3455   unsigned NumZeros = 0;
3456   for (int i = 0; i < NumElems; ++i) {
3457     unsigned Index = Low ? i : NumElems-i-1;
3458     int Idx = SVOp->getMaskElt(Index);
3459     if (Idx < 0) {
3460       ++NumZeros;
3461       continue;
3462     }
3463     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3464     if (Elt.getNode() && X86::isZeroNode(Elt))
3465       ++NumZeros;
3466     else
3467       break;
3468   }
3469   return NumZeros;
3470 }
3471
3472 /// isVectorShift - Returns true if the shuffle can be implemented as a
3473 /// logical left or right shift of a vector.
3474 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3475 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3476                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3477   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3478
3479   isLeft = true;
3480   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3481   if (!NumZeros) {
3482     isLeft = false;
3483     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3484     if (!NumZeros)
3485       return false;
3486   }
3487   bool SeenV1 = false;
3488   bool SeenV2 = false;
3489   for (unsigned i = NumZeros; i < NumElems; ++i) {
3490     unsigned Val = isLeft ? (i - NumZeros) : i;
3491     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3492     if (Idx_ < 0)
3493       continue;
3494     unsigned Idx = (unsigned) Idx_;
3495     if (Idx < NumElems)
3496       SeenV1 = true;
3497     else {
3498       Idx -= NumElems;
3499       SeenV2 = true;
3500     }
3501     if (Idx != Val)
3502       return false;
3503   }
3504   if (SeenV1 && SeenV2)
3505     return false;
3506
3507   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3508   ShAmt = NumZeros;
3509   return true;
3510 }
3511
3512
3513 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3514 ///
3515 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3516                                        unsigned NumNonZero, unsigned NumZero,
3517                                        SelectionDAG &DAG,
3518                                        const TargetLowering &TLI) {
3519   if (NumNonZero > 8)
3520     return SDValue();
3521
3522   DebugLoc dl = Op.getDebugLoc();
3523   SDValue V(0, 0);
3524   bool First = true;
3525   for (unsigned i = 0; i < 16; ++i) {
3526     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3527     if (ThisIsNonZero && First) {
3528       if (NumZero)
3529         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3530       else
3531         V = DAG.getUNDEF(MVT::v8i16);
3532       First = false;
3533     }
3534
3535     if ((i & 1) != 0) {
3536       SDValue ThisElt(0, 0), LastElt(0, 0);
3537       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3538       if (LastIsNonZero) {
3539         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3540                               MVT::i16, Op.getOperand(i-1));
3541       }
3542       if (ThisIsNonZero) {
3543         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3544         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3545                               ThisElt, DAG.getConstant(8, MVT::i8));
3546         if (LastIsNonZero)
3547           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3548       } else
3549         ThisElt = LastElt;
3550
3551       if (ThisElt.getNode())
3552         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3553                         DAG.getIntPtrConstant(i/2));
3554     }
3555   }
3556
3557   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3558 }
3559
3560 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3561 ///
3562 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3563                                      unsigned NumNonZero, unsigned NumZero,
3564                                      SelectionDAG &DAG,
3565                                      const TargetLowering &TLI) {
3566   if (NumNonZero > 4)
3567     return SDValue();
3568
3569   DebugLoc dl = Op.getDebugLoc();
3570   SDValue V(0, 0);
3571   bool First = true;
3572   for (unsigned i = 0; i < 8; ++i) {
3573     bool isNonZero = (NonZeros & (1 << i)) != 0;
3574     if (isNonZero) {
3575       if (First) {
3576         if (NumZero)
3577           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3578         else
3579           V = DAG.getUNDEF(MVT::v8i16);
3580         First = false;
3581       }
3582       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3583                       MVT::v8i16, V, Op.getOperand(i),
3584                       DAG.getIntPtrConstant(i));
3585     }
3586   }
3587
3588   return V;
3589 }
3590
3591 /// getVShift - Return a vector logical shift node.
3592 ///
3593 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3594                          unsigned NumBits, SelectionDAG &DAG,
3595                          const TargetLowering &TLI, DebugLoc dl) {
3596   bool isMMX = VT.getSizeInBits() == 64;
3597   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3598   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3599   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3600   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3601                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3602                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3603 }
3604
3605 SDValue
3606 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3607                                           SelectionDAG &DAG) const {
3608   
3609   // Check if the scalar load can be widened into a vector load. And if
3610   // the address is "base + cst" see if the cst can be "absorbed" into
3611   // the shuffle mask.
3612   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3613     SDValue Ptr = LD->getBasePtr();
3614     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3615       return SDValue();
3616     EVT PVT = LD->getValueType(0);
3617     if (PVT != MVT::i32 && PVT != MVT::f32)
3618       return SDValue();
3619
3620     int FI = -1;
3621     int64_t Offset = 0;
3622     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3623       FI = FINode->getIndex();
3624       Offset = 0;
3625     } else if (Ptr.getOpcode() == ISD::ADD &&
3626                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3627                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3628       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3629       Offset = Ptr.getConstantOperandVal(1);
3630       Ptr = Ptr.getOperand(0);
3631     } else {
3632       return SDValue();
3633     }
3634
3635     SDValue Chain = LD->getChain();
3636     // Make sure the stack object alignment is at least 16.
3637     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3638     if (DAG.InferPtrAlignment(Ptr) < 16) {
3639       if (MFI->isFixedObjectIndex(FI)) {
3640         // Can't change the alignment. FIXME: It's possible to compute
3641         // the exact stack offset and reference FI + adjust offset instead.
3642         // If someone *really* cares about this. That's the way to implement it.
3643         return SDValue();
3644       } else {
3645         MFI->setObjectAlignment(FI, 16);
3646       }
3647     }
3648
3649     // (Offset % 16) must be multiple of 4. Then address is then
3650     // Ptr + (Offset & ~15).
3651     if (Offset < 0)
3652       return SDValue();
3653     if ((Offset % 16) & 3)
3654       return SDValue();
3655     int64_t StartOffset = Offset & ~15;
3656     if (StartOffset)
3657       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3658                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3659
3660     int EltNo = (Offset - StartOffset) >> 2;
3661     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3662     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3663     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3664                              false, false, 0);
3665     // Canonicalize it to a v4i32 shuffle.
3666     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3667     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3668                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3669                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3670   }
3671
3672   return SDValue();
3673 }
3674
3675 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3676 /// vector of type 'VT', see if the elements can be replaced by a single large 
3677 /// load which has the same value as a build_vector whose operands are 'elts'.
3678 ///
3679 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3680 /// 
3681 /// FIXME: we'd also like to handle the case where the last elements are zero
3682 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3683 /// There's even a handy isZeroNode for that purpose.
3684 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3685                                         DebugLoc &dl, SelectionDAG &DAG) {
3686   EVT EltVT = VT.getVectorElementType();
3687   unsigned NumElems = Elts.size();
3688   
3689   LoadSDNode *LDBase = NULL;
3690   unsigned LastLoadedElt = -1U;
3691   
3692   // For each element in the initializer, see if we've found a load or an undef.
3693   // If we don't find an initial load element, or later load elements are 
3694   // non-consecutive, bail out.
3695   for (unsigned i = 0; i < NumElems; ++i) {
3696     SDValue Elt = Elts[i];
3697     
3698     if (!Elt.getNode() ||
3699         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3700       return SDValue();
3701     if (!LDBase) {
3702       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3703         return SDValue();
3704       LDBase = cast<LoadSDNode>(Elt.getNode());
3705       LastLoadedElt = i;
3706       continue;
3707     }
3708     if (Elt.getOpcode() == ISD::UNDEF)
3709       continue;
3710
3711     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3712     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3713       return SDValue();
3714     LastLoadedElt = i;
3715   }
3716
3717   // If we have found an entire vector of loads and undefs, then return a large
3718   // load of the entire vector width starting at the base pointer.  If we found
3719   // consecutive loads for the low half, generate a vzext_load node.
3720   if (LastLoadedElt == NumElems - 1) {
3721     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3722       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3723                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3724                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3725     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3726                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3727                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3728                        LDBase->getAlignment());
3729   } else if (NumElems == 4 && LastLoadedElt == 1) {
3730     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3731     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3732     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3733     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3734   }
3735   return SDValue();
3736 }
3737
3738 SDValue
3739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3740   DebugLoc dl = Op.getDebugLoc();
3741   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3742   if (ISD::isBuildVectorAllZeros(Op.getNode())
3743       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3744     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3745     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3746     // eliminated on x86-32 hosts.
3747     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3748       return Op;
3749
3750     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3751       return getOnesVector(Op.getValueType(), DAG, dl);
3752     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3753   }
3754
3755   EVT VT = Op.getValueType();
3756   EVT ExtVT = VT.getVectorElementType();
3757   unsigned EVTBits = ExtVT.getSizeInBits();
3758
3759   unsigned NumElems = Op.getNumOperands();
3760   unsigned NumZero  = 0;
3761   unsigned NumNonZero = 0;
3762   unsigned NonZeros = 0;
3763   bool IsAllConstants = true;
3764   SmallSet<SDValue, 8> Values;
3765   for (unsigned i = 0; i < NumElems; ++i) {
3766     SDValue Elt = Op.getOperand(i);
3767     if (Elt.getOpcode() == ISD::UNDEF)
3768       continue;
3769     Values.insert(Elt);
3770     if (Elt.getOpcode() != ISD::Constant &&
3771         Elt.getOpcode() != ISD::ConstantFP)
3772       IsAllConstants = false;
3773     if (X86::isZeroNode(Elt))
3774       NumZero++;
3775     else {
3776       NonZeros |= (1 << i);
3777       NumNonZero++;
3778     }
3779   }
3780
3781   if (NumNonZero == 0) {
3782     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3783     return DAG.getUNDEF(VT);
3784   }
3785
3786   // Special case for single non-zero, non-undef, element.
3787   if (NumNonZero == 1) {
3788     unsigned Idx = CountTrailingZeros_32(NonZeros);
3789     SDValue Item = Op.getOperand(Idx);
3790
3791     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3792     // the value are obviously zero, truncate the value to i32 and do the
3793     // insertion that way.  Only do this if the value is non-constant or if the
3794     // value is a constant being inserted into element 0.  It is cheaper to do
3795     // a constant pool load than it is to do a movd + shuffle.
3796     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3797         (!IsAllConstants || Idx == 0)) {
3798       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3799         // Handle MMX and SSE both.
3800         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3801         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3802
3803         // Truncate the value (which may itself be a constant) to i32, and
3804         // convert it to a vector with movd (S2V+shuffle to zero extend).
3805         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3806         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3807         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3808                                            Subtarget->hasSSE2(), DAG);
3809
3810         // Now we have our 32-bit value zero extended in the low element of
3811         // a vector.  If Idx != 0, swizzle it into place.
3812         if (Idx != 0) {
3813           SmallVector<int, 4> Mask;
3814           Mask.push_back(Idx);
3815           for (unsigned i = 1; i != VecElts; ++i)
3816             Mask.push_back(i);
3817           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3818                                       DAG.getUNDEF(Item.getValueType()),
3819                                       &Mask[0]);
3820         }
3821         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3822       }
3823     }
3824
3825     // If we have a constant or non-constant insertion into the low element of
3826     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3827     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3828     // depending on what the source datatype is.
3829     if (Idx == 0) {
3830       if (NumZero == 0) {
3831         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3832       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3833           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3834         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3835         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3836         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3837                                            DAG);
3838       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3839         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3840         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3841         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3842         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3843                                            Subtarget->hasSSE2(), DAG);
3844         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3845       }
3846     }
3847
3848     // Is it a vector logical left shift?
3849     if (NumElems == 2 && Idx == 1 &&
3850         X86::isZeroNode(Op.getOperand(0)) &&
3851         !X86::isZeroNode(Op.getOperand(1))) {
3852       unsigned NumBits = VT.getSizeInBits();
3853       return getVShift(true, VT,
3854                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3855                                    VT, Op.getOperand(1)),
3856                        NumBits/2, DAG, *this, dl);
3857     }
3858
3859     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3860       return SDValue();
3861
3862     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3863     // is a non-constant being inserted into an element other than the low one,
3864     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3865     // movd/movss) to move this into the low element, then shuffle it into
3866     // place.
3867     if (EVTBits == 32) {
3868       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3869
3870       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3871       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3872                                          Subtarget->hasSSE2(), DAG);
3873       SmallVector<int, 8> MaskVec;
3874       for (unsigned i = 0; i < NumElems; i++)
3875         MaskVec.push_back(i == Idx ? 0 : 1);
3876       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3877     }
3878   }
3879
3880   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3881   if (Values.size() == 1) {
3882     if (EVTBits == 32) {
3883       // Instead of a shuffle like this:
3884       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3885       // Check if it's possible to issue this instead.
3886       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3887       unsigned Idx = CountTrailingZeros_32(NonZeros);
3888       SDValue Item = Op.getOperand(Idx);
3889       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3890         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3891     }
3892     return SDValue();
3893   }
3894
3895   // A vector full of immediates; various special cases are already
3896   // handled, so this is best done with a single constant-pool load.
3897   if (IsAllConstants)
3898     return SDValue();
3899
3900   // Let legalizer expand 2-wide build_vectors.
3901   if (EVTBits == 64) {
3902     if (NumNonZero == 1) {
3903       // One half is zero or undef.
3904       unsigned Idx = CountTrailingZeros_32(NonZeros);
3905       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3906                                  Op.getOperand(Idx));
3907       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3908                                          Subtarget->hasSSE2(), DAG);
3909     }
3910     return SDValue();
3911   }
3912
3913   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3914   if (EVTBits == 8 && NumElems == 16) {
3915     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3916                                         *this);
3917     if (V.getNode()) return V;
3918   }
3919
3920   if (EVTBits == 16 && NumElems == 8) {
3921     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3922                                         *this);
3923     if (V.getNode()) return V;
3924   }
3925
3926   // If element VT is == 32 bits, turn it into a number of shuffles.
3927   SmallVector<SDValue, 8> V;
3928   V.resize(NumElems);
3929   if (NumElems == 4 && NumZero > 0) {
3930     for (unsigned i = 0; i < 4; ++i) {
3931       bool isZero = !(NonZeros & (1 << i));
3932       if (isZero)
3933         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3934       else
3935         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3936     }
3937
3938     for (unsigned i = 0; i < 2; ++i) {
3939       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3940         default: break;
3941         case 0:
3942           V[i] = V[i*2];  // Must be a zero vector.
3943           break;
3944         case 1:
3945           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3946           break;
3947         case 2:
3948           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3949           break;
3950         case 3:
3951           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3952           break;
3953       }
3954     }
3955
3956     SmallVector<int, 8> MaskVec;
3957     bool Reverse = (NonZeros & 0x3) == 2;
3958     for (unsigned i = 0; i < 2; ++i)
3959       MaskVec.push_back(Reverse ? 1-i : i);
3960     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3961     for (unsigned i = 0; i < 2; ++i)
3962       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3963     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3964   }
3965
3966   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3967     // Check for a build vector of consecutive loads.
3968     for (unsigned i = 0; i < NumElems; ++i)
3969       V[i] = Op.getOperand(i);
3970     
3971     // Check for elements which are consecutive loads.
3972     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3973     if (LD.getNode())
3974       return LD;
3975     
3976     // For SSE 4.1, use inserts into undef.  
3977     if (getSubtarget()->hasSSE41()) {
3978       V[0] = DAG.getUNDEF(VT);
3979       for (unsigned i = 0; i < NumElems; ++i)
3980         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3981           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3982                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3983       return V[0];
3984     }
3985     
3986     // Otherwise, expand into a number of unpckl*
3987     // e.g. for v4f32
3988     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3989     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3990     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3991     for (unsigned i = 0; i < NumElems; ++i)
3992       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3993     NumElems >>= 1;
3994     while (NumElems != 0) {
3995       for (unsigned i = 0; i < NumElems; ++i)
3996         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3997       NumElems >>= 1;
3998     }
3999     return V[0];
4000   }
4001   return SDValue();
4002 }
4003
4004 SDValue
4005 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4006   // We support concatenate two MMX registers and place them in a MMX
4007   // register.  This is better than doing a stack convert.
4008   DebugLoc dl = Op.getDebugLoc();
4009   EVT ResVT = Op.getValueType();
4010   assert(Op.getNumOperands() == 2);
4011   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4012          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4013   int Mask[2];
4014   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4015   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4016   InVec = Op.getOperand(1);
4017   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4018     unsigned NumElts = ResVT.getVectorNumElements();
4019     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4020     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4021                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4022   } else {
4023     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4024     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4025     Mask[0] = 0; Mask[1] = 2;
4026     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4027   }
4028   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4029 }
4030
4031 // v8i16 shuffles - Prefer shuffles in the following order:
4032 // 1. [all]   pshuflw, pshufhw, optional move
4033 // 2. [ssse3] 1 x pshufb
4034 // 3. [ssse3] 2 x pshufb + 1 x por
4035 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4036 static
4037 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4038                                  SelectionDAG &DAG,
4039                                  const X86TargetLowering &TLI) {
4040   SDValue V1 = SVOp->getOperand(0);
4041   SDValue V2 = SVOp->getOperand(1);
4042   DebugLoc dl = SVOp->getDebugLoc();
4043   SmallVector<int, 8> MaskVals;
4044
4045   // Determine if more than 1 of the words in each of the low and high quadwords
4046   // of the result come from the same quadword of one of the two inputs.  Undef
4047   // mask values count as coming from any quadword, for better codegen.
4048   SmallVector<unsigned, 4> LoQuad(4);
4049   SmallVector<unsigned, 4> HiQuad(4);
4050   BitVector InputQuads(4);
4051   for (unsigned i = 0; i < 8; ++i) {
4052     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4053     int EltIdx = SVOp->getMaskElt(i);
4054     MaskVals.push_back(EltIdx);
4055     if (EltIdx < 0) {
4056       ++Quad[0];
4057       ++Quad[1];
4058       ++Quad[2];
4059       ++Quad[3];
4060       continue;
4061     }
4062     ++Quad[EltIdx / 4];
4063     InputQuads.set(EltIdx / 4);
4064   }
4065
4066   int BestLoQuad = -1;
4067   unsigned MaxQuad = 1;
4068   for (unsigned i = 0; i < 4; ++i) {
4069     if (LoQuad[i] > MaxQuad) {
4070       BestLoQuad = i;
4071       MaxQuad = LoQuad[i];
4072     }
4073   }
4074
4075   int BestHiQuad = -1;
4076   MaxQuad = 1;
4077   for (unsigned i = 0; i < 4; ++i) {
4078     if (HiQuad[i] > MaxQuad) {
4079       BestHiQuad = i;
4080       MaxQuad = HiQuad[i];
4081     }
4082   }
4083
4084   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4085   // of the two input vectors, shuffle them into one input vector so only a
4086   // single pshufb instruction is necessary. If There are more than 2 input
4087   // quads, disable the next transformation since it does not help SSSE3.
4088   bool V1Used = InputQuads[0] || InputQuads[1];
4089   bool V2Used = InputQuads[2] || InputQuads[3];
4090   if (TLI.getSubtarget()->hasSSSE3()) {
4091     if (InputQuads.count() == 2 && V1Used && V2Used) {
4092       BestLoQuad = InputQuads.find_first();
4093       BestHiQuad = InputQuads.find_next(BestLoQuad);
4094     }
4095     if (InputQuads.count() > 2) {
4096       BestLoQuad = -1;
4097       BestHiQuad = -1;
4098     }
4099   }
4100
4101   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4102   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4103   // words from all 4 input quadwords.
4104   SDValue NewV;
4105   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4106     SmallVector<int, 8> MaskV;
4107     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4108     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4109     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4110                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4111                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4112     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4113
4114     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4115     // source words for the shuffle, to aid later transformations.
4116     bool AllWordsInNewV = true;
4117     bool InOrder[2] = { true, true };
4118     for (unsigned i = 0; i != 8; ++i) {
4119       int idx = MaskVals[i];
4120       if (idx != (int)i)
4121         InOrder[i/4] = false;
4122       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4123         continue;
4124       AllWordsInNewV = false;
4125       break;
4126     }
4127
4128     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4129     if (AllWordsInNewV) {
4130       for (int i = 0; i != 8; ++i) {
4131         int idx = MaskVals[i];
4132         if (idx < 0)
4133           continue;
4134         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4135         if ((idx != i) && idx < 4)
4136           pshufhw = false;
4137         if ((idx != i) && idx > 3)
4138           pshuflw = false;
4139       }
4140       V1 = NewV;
4141       V2Used = false;
4142       BestLoQuad = 0;
4143       BestHiQuad = 1;
4144     }
4145
4146     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4147     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4148     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4149       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4150                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4151     }
4152   }
4153
4154   // If we have SSSE3, and all words of the result are from 1 input vector,
4155   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4156   // is present, fall back to case 4.
4157   if (TLI.getSubtarget()->hasSSSE3()) {
4158     SmallVector<SDValue,16> pshufbMask;
4159
4160     // If we have elements from both input vectors, set the high bit of the
4161     // shuffle mask element to zero out elements that come from V2 in the V1
4162     // mask, and elements that come from V1 in the V2 mask, so that the two
4163     // results can be OR'd together.
4164     bool TwoInputs = V1Used && V2Used;
4165     for (unsigned i = 0; i != 8; ++i) {
4166       int EltIdx = MaskVals[i] * 2;
4167       if (TwoInputs && (EltIdx >= 16)) {
4168         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4169         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4170         continue;
4171       }
4172       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4173       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4174     }
4175     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4176     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4177                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4178                                  MVT::v16i8, &pshufbMask[0], 16));
4179     if (!TwoInputs)
4180       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4181
4182     // Calculate the shuffle mask for the second input, shuffle it, and
4183     // OR it with the first shuffled input.
4184     pshufbMask.clear();
4185     for (unsigned i = 0; i != 8; ++i) {
4186       int EltIdx = MaskVals[i] * 2;
4187       if (EltIdx < 16) {
4188         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4189         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4190         continue;
4191       }
4192       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4193       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4194     }
4195     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4196     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4197                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4198                                  MVT::v16i8, &pshufbMask[0], 16));
4199     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4200     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4201   }
4202
4203   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4204   // and update MaskVals with new element order.
4205   BitVector InOrder(8);
4206   if (BestLoQuad >= 0) {
4207     SmallVector<int, 8> MaskV;
4208     for (int i = 0; i != 4; ++i) {
4209       int idx = MaskVals[i];
4210       if (idx < 0) {
4211         MaskV.push_back(-1);
4212         InOrder.set(i);
4213       } else if ((idx / 4) == BestLoQuad) {
4214         MaskV.push_back(idx & 3);
4215         InOrder.set(i);
4216       } else {
4217         MaskV.push_back(-1);
4218       }
4219     }
4220     for (unsigned i = 4; i != 8; ++i)
4221       MaskV.push_back(i);
4222     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4223                                 &MaskV[0]);
4224   }
4225
4226   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4227   // and update MaskVals with the new element order.
4228   if (BestHiQuad >= 0) {
4229     SmallVector<int, 8> MaskV;
4230     for (unsigned i = 0; i != 4; ++i)
4231       MaskV.push_back(i);
4232     for (unsigned i = 4; i != 8; ++i) {
4233       int idx = MaskVals[i];
4234       if (idx < 0) {
4235         MaskV.push_back(-1);
4236         InOrder.set(i);
4237       } else if ((idx / 4) == BestHiQuad) {
4238         MaskV.push_back((idx & 3) + 4);
4239         InOrder.set(i);
4240       } else {
4241         MaskV.push_back(-1);
4242       }
4243     }
4244     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4245                                 &MaskV[0]);
4246   }
4247
4248   // In case BestHi & BestLo were both -1, which means each quadword has a word
4249   // from each of the four input quadwords, calculate the InOrder bitvector now
4250   // before falling through to the insert/extract cleanup.
4251   if (BestLoQuad == -1 && BestHiQuad == -1) {
4252     NewV = V1;
4253     for (int i = 0; i != 8; ++i)
4254       if (MaskVals[i] < 0 || MaskVals[i] == i)
4255         InOrder.set(i);
4256   }
4257
4258   // The other elements are put in the right place using pextrw and pinsrw.
4259   for (unsigned i = 0; i != 8; ++i) {
4260     if (InOrder[i])
4261       continue;
4262     int EltIdx = MaskVals[i];
4263     if (EltIdx < 0)
4264       continue;
4265     SDValue ExtOp = (EltIdx < 8)
4266     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4267                   DAG.getIntPtrConstant(EltIdx))
4268     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4269                   DAG.getIntPtrConstant(EltIdx - 8));
4270     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4271                        DAG.getIntPtrConstant(i));
4272   }
4273   return NewV;
4274 }
4275
4276 // v16i8 shuffles - Prefer shuffles in the following order:
4277 // 1. [ssse3] 1 x pshufb
4278 // 2. [ssse3] 2 x pshufb + 1 x por
4279 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4280 static
4281 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4282                                  SelectionDAG &DAG,
4283                                  const X86TargetLowering &TLI) {
4284   SDValue V1 = SVOp->getOperand(0);
4285   SDValue V2 = SVOp->getOperand(1);
4286   DebugLoc dl = SVOp->getDebugLoc();
4287   SmallVector<int, 16> MaskVals;
4288   SVOp->getMask(MaskVals);
4289
4290   // If we have SSSE3, case 1 is generated when all result bytes come from
4291   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4292   // present, fall back to case 3.
4293   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4294   bool V1Only = true;
4295   bool V2Only = true;
4296   for (unsigned i = 0; i < 16; ++i) {
4297     int EltIdx = MaskVals[i];
4298     if (EltIdx < 0)
4299       continue;
4300     if (EltIdx < 16)
4301       V2Only = false;
4302     else
4303       V1Only = false;
4304   }
4305
4306   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4307   if (TLI.getSubtarget()->hasSSSE3()) {
4308     SmallVector<SDValue,16> pshufbMask;
4309
4310     // If all result elements are from one input vector, then only translate
4311     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4312     //
4313     // Otherwise, we have elements from both input vectors, and must zero out
4314     // elements that come from V2 in the first mask, and V1 in the second mask
4315     // so that we can OR them together.
4316     bool TwoInputs = !(V1Only || V2Only);
4317     for (unsigned i = 0; i != 16; ++i) {
4318       int EltIdx = MaskVals[i];
4319       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4320         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4321         continue;
4322       }
4323       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4324     }
4325     // If all the elements are from V2, assign it to V1 and return after
4326     // building the first pshufb.
4327     if (V2Only)
4328       V1 = V2;
4329     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4330                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4331                                  MVT::v16i8, &pshufbMask[0], 16));
4332     if (!TwoInputs)
4333       return V1;
4334
4335     // Calculate the shuffle mask for the second input, shuffle it, and
4336     // OR it with the first shuffled input.
4337     pshufbMask.clear();
4338     for (unsigned i = 0; i != 16; ++i) {
4339       int EltIdx = MaskVals[i];
4340       if (EltIdx < 16) {
4341         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4342         continue;
4343       }
4344       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4345     }
4346     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4347                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4348                                  MVT::v16i8, &pshufbMask[0], 16));
4349     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4350   }
4351
4352   // No SSSE3 - Calculate in place words and then fix all out of place words
4353   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4354   // the 16 different words that comprise the two doublequadword input vectors.
4355   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4356   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4357   SDValue NewV = V2Only ? V2 : V1;
4358   for (int i = 0; i != 8; ++i) {
4359     int Elt0 = MaskVals[i*2];
4360     int Elt1 = MaskVals[i*2+1];
4361
4362     // This word of the result is all undef, skip it.
4363     if (Elt0 < 0 && Elt1 < 0)
4364       continue;
4365
4366     // This word of the result is already in the correct place, skip it.
4367     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4368       continue;
4369     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4370       continue;
4371
4372     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4373     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4374     SDValue InsElt;
4375
4376     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4377     // using a single extract together, load it and store it.
4378     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4379       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4380                            DAG.getIntPtrConstant(Elt1 / 2));
4381       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4382                         DAG.getIntPtrConstant(i));
4383       continue;
4384     }
4385
4386     // If Elt1 is defined, extract it from the appropriate source.  If the
4387     // source byte is not also odd, shift the extracted word left 8 bits
4388     // otherwise clear the bottom 8 bits if we need to do an or.
4389     if (Elt1 >= 0) {
4390       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4391                            DAG.getIntPtrConstant(Elt1 / 2));
4392       if ((Elt1 & 1) == 0)
4393         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4394                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4395       else if (Elt0 >= 0)
4396         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4397                              DAG.getConstant(0xFF00, MVT::i16));
4398     }
4399     // If Elt0 is defined, extract it from the appropriate source.  If the
4400     // source byte is not also even, shift the extracted word right 8 bits. If
4401     // Elt1 was also defined, OR the extracted values together before
4402     // inserting them in the result.
4403     if (Elt0 >= 0) {
4404       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4405                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4406       if ((Elt0 & 1) != 0)
4407         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4408                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4409       else if (Elt1 >= 0)
4410         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4411                              DAG.getConstant(0x00FF, MVT::i16));
4412       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4413                          : InsElt0;
4414     }
4415     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4416                        DAG.getIntPtrConstant(i));
4417   }
4418   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4419 }
4420
4421 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4422 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4423 /// done when every pair / quad of shuffle mask elements point to elements in
4424 /// the right sequence. e.g.
4425 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4426 static
4427 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4428                                  SelectionDAG &DAG,
4429                                  const TargetLowering &TLI, DebugLoc dl) {
4430   EVT VT = SVOp->getValueType(0);
4431   SDValue V1 = SVOp->getOperand(0);
4432   SDValue V2 = SVOp->getOperand(1);
4433   unsigned NumElems = VT.getVectorNumElements();
4434   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4435   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4436   EVT MaskEltVT = MaskVT.getVectorElementType();
4437   EVT NewVT = MaskVT;
4438   switch (VT.getSimpleVT().SimpleTy) {
4439   default: assert(false && "Unexpected!");
4440   case MVT::v4f32: NewVT = MVT::v2f64; break;
4441   case MVT::v4i32: NewVT = MVT::v2i64; break;
4442   case MVT::v8i16: NewVT = MVT::v4i32; break;
4443   case MVT::v16i8: NewVT = MVT::v4i32; break;
4444   }
4445
4446   if (NewWidth == 2) {
4447     if (VT.isInteger())
4448       NewVT = MVT::v2i64;
4449     else
4450       NewVT = MVT::v2f64;
4451   }
4452   int Scale = NumElems / NewWidth;
4453   SmallVector<int, 8> MaskVec;
4454   for (unsigned i = 0; i < NumElems; i += Scale) {
4455     int StartIdx = -1;
4456     for (int j = 0; j < Scale; ++j) {
4457       int EltIdx = SVOp->getMaskElt(i+j);
4458       if (EltIdx < 0)
4459         continue;
4460       if (StartIdx == -1)
4461         StartIdx = EltIdx - (EltIdx % Scale);
4462       if (EltIdx != StartIdx + j)
4463         return SDValue();
4464     }
4465     if (StartIdx == -1)
4466       MaskVec.push_back(-1);
4467     else
4468       MaskVec.push_back(StartIdx / Scale);
4469   }
4470
4471   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4472   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4473   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4474 }
4475
4476 /// getVZextMovL - Return a zero-extending vector move low node.
4477 ///
4478 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4479                             SDValue SrcOp, SelectionDAG &DAG,
4480                             const X86Subtarget *Subtarget, DebugLoc dl) {
4481   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4482     LoadSDNode *LD = NULL;
4483     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4484       LD = dyn_cast<LoadSDNode>(SrcOp);
4485     if (!LD) {
4486       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4487       // instead.
4488       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4489       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4490           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4491           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4492           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4493         // PR2108
4494         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4495         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4496                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4497                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4498                                                    OpVT,
4499                                                    SrcOp.getOperand(0)
4500                                                           .getOperand(0))));
4501       }
4502     }
4503   }
4504
4505   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4506                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4507                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4508                                              OpVT, SrcOp)));
4509 }
4510
4511 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4512 /// shuffles.
4513 static SDValue
4514 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4515   SDValue V1 = SVOp->getOperand(0);
4516   SDValue V2 = SVOp->getOperand(1);
4517   DebugLoc dl = SVOp->getDebugLoc();
4518   EVT VT = SVOp->getValueType(0);
4519
4520   SmallVector<std::pair<int, int>, 8> Locs;
4521   Locs.resize(4);
4522   SmallVector<int, 8> Mask1(4U, -1);
4523   SmallVector<int, 8> PermMask;
4524   SVOp->getMask(PermMask);
4525
4526   unsigned NumHi = 0;
4527   unsigned NumLo = 0;
4528   for (unsigned i = 0; i != 4; ++i) {
4529     int Idx = PermMask[i];
4530     if (Idx < 0) {
4531       Locs[i] = std::make_pair(-1, -1);
4532     } else {
4533       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4534       if (Idx < 4) {
4535         Locs[i] = std::make_pair(0, NumLo);
4536         Mask1[NumLo] = Idx;
4537         NumLo++;
4538       } else {
4539         Locs[i] = std::make_pair(1, NumHi);
4540         if (2+NumHi < 4)
4541           Mask1[2+NumHi] = Idx;
4542         NumHi++;
4543       }
4544     }
4545   }
4546
4547   if (NumLo <= 2 && NumHi <= 2) {
4548     // If no more than two elements come from either vector. This can be
4549     // implemented with two shuffles. First shuffle gather the elements.
4550     // The second shuffle, which takes the first shuffle as both of its
4551     // vector operands, put the elements into the right order.
4552     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4553
4554     SmallVector<int, 8> Mask2(4U, -1);
4555
4556     for (unsigned i = 0; i != 4; ++i) {
4557       if (Locs[i].first == -1)
4558         continue;
4559       else {
4560         unsigned Idx = (i < 2) ? 0 : 4;
4561         Idx += Locs[i].first * 2 + Locs[i].second;
4562         Mask2[i] = Idx;
4563       }
4564     }
4565
4566     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4567   } else if (NumLo == 3 || NumHi == 3) {
4568     // Otherwise, we must have three elements from one vector, call it X, and
4569     // one element from the other, call it Y.  First, use a shufps to build an
4570     // intermediate vector with the one element from Y and the element from X
4571     // that will be in the same half in the final destination (the indexes don't
4572     // matter). Then, use a shufps to build the final vector, taking the half
4573     // containing the element from Y from the intermediate, and the other half
4574     // from X.
4575     if (NumHi == 3) {
4576       // Normalize it so the 3 elements come from V1.
4577       CommuteVectorShuffleMask(PermMask, VT);
4578       std::swap(V1, V2);
4579     }
4580
4581     // Find the element from V2.
4582     unsigned HiIndex;
4583     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4584       int Val = PermMask[HiIndex];
4585       if (Val < 0)
4586         continue;
4587       if (Val >= 4)
4588         break;
4589     }
4590
4591     Mask1[0] = PermMask[HiIndex];
4592     Mask1[1] = -1;
4593     Mask1[2] = PermMask[HiIndex^1];
4594     Mask1[3] = -1;
4595     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4596
4597     if (HiIndex >= 2) {
4598       Mask1[0] = PermMask[0];
4599       Mask1[1] = PermMask[1];
4600       Mask1[2] = HiIndex & 1 ? 6 : 4;
4601       Mask1[3] = HiIndex & 1 ? 4 : 6;
4602       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4603     } else {
4604       Mask1[0] = HiIndex & 1 ? 2 : 0;
4605       Mask1[1] = HiIndex & 1 ? 0 : 2;
4606       Mask1[2] = PermMask[2];
4607       Mask1[3] = PermMask[3];
4608       if (Mask1[2] >= 0)
4609         Mask1[2] += 4;
4610       if (Mask1[3] >= 0)
4611         Mask1[3] += 4;
4612       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4613     }
4614   }
4615
4616   // Break it into (shuffle shuffle_hi, shuffle_lo).
4617   Locs.clear();
4618   SmallVector<int,8> LoMask(4U, -1);
4619   SmallVector<int,8> HiMask(4U, -1);
4620
4621   SmallVector<int,8> *MaskPtr = &LoMask;
4622   unsigned MaskIdx = 0;
4623   unsigned LoIdx = 0;
4624   unsigned HiIdx = 2;
4625   for (unsigned i = 0; i != 4; ++i) {
4626     if (i == 2) {
4627       MaskPtr = &HiMask;
4628       MaskIdx = 1;
4629       LoIdx = 0;
4630       HiIdx = 2;
4631     }
4632     int Idx = PermMask[i];
4633     if (Idx < 0) {
4634       Locs[i] = std::make_pair(-1, -1);
4635     } else if (Idx < 4) {
4636       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4637       (*MaskPtr)[LoIdx] = Idx;
4638       LoIdx++;
4639     } else {
4640       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4641       (*MaskPtr)[HiIdx] = Idx;
4642       HiIdx++;
4643     }
4644   }
4645
4646   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4647   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4648   SmallVector<int, 8> MaskOps;
4649   for (unsigned i = 0; i != 4; ++i) {
4650     if (Locs[i].first == -1) {
4651       MaskOps.push_back(-1);
4652     } else {
4653       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4654       MaskOps.push_back(Idx);
4655     }
4656   }
4657   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4658 }
4659
4660 SDValue
4661 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4663   SDValue V1 = Op.getOperand(0);
4664   SDValue V2 = Op.getOperand(1);
4665   EVT VT = Op.getValueType();
4666   DebugLoc dl = Op.getDebugLoc();
4667   unsigned NumElems = VT.getVectorNumElements();
4668   bool isMMX = VT.getSizeInBits() == 64;
4669   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4670   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4671   bool V1IsSplat = false;
4672   bool V2IsSplat = false;
4673
4674   if (isZeroShuffle(SVOp))
4675     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4676
4677   // Promote splats to v4f32.
4678   if (SVOp->isSplat()) {
4679     if (isMMX || NumElems < 4)
4680       return Op;
4681     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4682   }
4683
4684   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4685   // do it!
4686   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4687     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4688     if (NewOp.getNode())
4689       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4690                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4691   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4692     // FIXME: Figure out a cleaner way to do this.
4693     // Try to make use of movq to zero out the top part.
4694     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4695       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4696       if (NewOp.getNode()) {
4697         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4698           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4699                               DAG, Subtarget, dl);
4700       }
4701     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4702       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4703       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4704         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4705                             DAG, Subtarget, dl);
4706     }
4707   }
4708
4709   if (X86::isPSHUFDMask(SVOp))
4710     return Op;
4711
4712   // Check if this can be converted into a logical shift.
4713   bool isLeft = false;
4714   unsigned ShAmt = 0;
4715   SDValue ShVal;
4716   bool isShift = getSubtarget()->hasSSE2() &&
4717     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4718   if (isShift && ShVal.hasOneUse()) {
4719     // If the shifted value has multiple uses, it may be cheaper to use
4720     // v_set0 + movlhps or movhlps, etc.
4721     EVT EltVT = VT.getVectorElementType();
4722     ShAmt *= EltVT.getSizeInBits();
4723     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4724   }
4725
4726   if (X86::isMOVLMask(SVOp)) {
4727     if (V1IsUndef)
4728       return V2;
4729     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4730       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4731     if (!isMMX)
4732       return Op;
4733   }
4734
4735   // FIXME: fold these into legal mask.
4736   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4737                  X86::isMOVSLDUPMask(SVOp) ||
4738                  X86::isMOVHLPSMask(SVOp) ||
4739                  X86::isMOVLHPSMask(SVOp) ||
4740                  X86::isMOVLPMask(SVOp)))
4741     return Op;
4742
4743   if (ShouldXformToMOVHLPS(SVOp) ||
4744       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4745     return CommuteVectorShuffle(SVOp, DAG);
4746
4747   if (isShift) {
4748     // No better options. Use a vshl / vsrl.
4749     EVT EltVT = VT.getVectorElementType();
4750     ShAmt *= EltVT.getSizeInBits();
4751     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4752   }
4753
4754   bool Commuted = false;
4755   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4756   // 1,1,1,1 -> v8i16 though.
4757   V1IsSplat = isSplatVector(V1.getNode());
4758   V2IsSplat = isSplatVector(V2.getNode());
4759
4760   // Canonicalize the splat or undef, if present, to be on the RHS.
4761   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4762     Op = CommuteVectorShuffle(SVOp, DAG);
4763     SVOp = cast<ShuffleVectorSDNode>(Op);
4764     V1 = SVOp->getOperand(0);
4765     V2 = SVOp->getOperand(1);
4766     std::swap(V1IsSplat, V2IsSplat);
4767     std::swap(V1IsUndef, V2IsUndef);
4768     Commuted = true;
4769   }
4770
4771   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4772     // Shuffling low element of v1 into undef, just return v1.
4773     if (V2IsUndef)
4774       return V1;
4775     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4776     // the instruction selector will not match, so get a canonical MOVL with
4777     // swapped operands to undo the commute.
4778     return getMOVL(DAG, dl, VT, V2, V1);
4779   }
4780
4781   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4782       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4783       X86::isUNPCKLMask(SVOp) ||
4784       X86::isUNPCKHMask(SVOp))
4785     return Op;
4786
4787   if (V2IsSplat) {
4788     // Normalize mask so all entries that point to V2 points to its first
4789     // element then try to match unpck{h|l} again. If match, return a
4790     // new vector_shuffle with the corrected mask.
4791     SDValue NewMask = NormalizeMask(SVOp, DAG);
4792     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4793     if (NSVOp != SVOp) {
4794       if (X86::isUNPCKLMask(NSVOp, true)) {
4795         return NewMask;
4796       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4797         return NewMask;
4798       }
4799     }
4800   }
4801
4802   if (Commuted) {
4803     // Commute is back and try unpck* again.
4804     // FIXME: this seems wrong.
4805     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4806     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4807     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4808         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4809         X86::isUNPCKLMask(NewSVOp) ||
4810         X86::isUNPCKHMask(NewSVOp))
4811       return NewOp;
4812   }
4813
4814   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4815
4816   // Normalize the node to match x86 shuffle ops if needed
4817   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4818     return CommuteVectorShuffle(SVOp, DAG);
4819
4820   // Check for legal shuffle and return?
4821   SmallVector<int, 16> PermMask;
4822   SVOp->getMask(PermMask);
4823   if (isShuffleMaskLegal(PermMask, VT))
4824     return Op;
4825
4826   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4827   if (VT == MVT::v8i16) {
4828     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4829     if (NewOp.getNode())
4830       return NewOp;
4831   }
4832
4833   if (VT == MVT::v16i8) {
4834     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4835     if (NewOp.getNode())
4836       return NewOp;
4837   }
4838
4839   // Handle all 4 wide cases with a number of shuffles except for MMX.
4840   if (NumElems == 4 && !isMMX)
4841     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4842
4843   return SDValue();
4844 }
4845
4846 SDValue
4847 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4848                                                 SelectionDAG &DAG) const {
4849   EVT VT = Op.getValueType();
4850   DebugLoc dl = Op.getDebugLoc();
4851   if (VT.getSizeInBits() == 8) {
4852     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4853                                     Op.getOperand(0), Op.getOperand(1));
4854     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4855                                     DAG.getValueType(VT));
4856     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4857   } else if (VT.getSizeInBits() == 16) {
4858     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4859     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4860     if (Idx == 0)
4861       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4862                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4863                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4864                                                  MVT::v4i32,
4865                                                  Op.getOperand(0)),
4866                                      Op.getOperand(1)));
4867     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4868                                     Op.getOperand(0), Op.getOperand(1));
4869     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4870                                     DAG.getValueType(VT));
4871     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4872   } else if (VT == MVT::f32) {
4873     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4874     // the result back to FR32 register. It's only worth matching if the
4875     // result has a single use which is a store or a bitcast to i32.  And in
4876     // the case of a store, it's not worth it if the index is a constant 0,
4877     // because a MOVSSmr can be used instead, which is smaller and faster.
4878     if (!Op.hasOneUse())
4879       return SDValue();
4880     SDNode *User = *Op.getNode()->use_begin();
4881     if ((User->getOpcode() != ISD::STORE ||
4882          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4883           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4884         (User->getOpcode() != ISD::BIT_CONVERT ||
4885          User->getValueType(0) != MVT::i32))
4886       return SDValue();
4887     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4888                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4889                                               Op.getOperand(0)),
4890                                               Op.getOperand(1));
4891     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4892   } else if (VT == MVT::i32) {
4893     // ExtractPS works with constant index.
4894     if (isa<ConstantSDNode>(Op.getOperand(1)))
4895       return Op;
4896   }
4897   return SDValue();
4898 }
4899
4900
4901 SDValue
4902 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4903                                            SelectionDAG &DAG) const {
4904   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4905     return SDValue();
4906
4907   if (Subtarget->hasSSE41()) {
4908     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4909     if (Res.getNode())
4910       return Res;
4911   }
4912
4913   EVT VT = Op.getValueType();
4914   DebugLoc dl = Op.getDebugLoc();
4915   // TODO: handle v16i8.
4916   if (VT.getSizeInBits() == 16) {
4917     SDValue Vec = Op.getOperand(0);
4918     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4919     if (Idx == 0)
4920       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4921                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4922                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4923                                                  MVT::v4i32, Vec),
4924                                      Op.getOperand(1)));
4925     // Transform it so it match pextrw which produces a 32-bit result.
4926     EVT EltVT = MVT::i32;
4927     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4928                                     Op.getOperand(0), Op.getOperand(1));
4929     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4930                                     DAG.getValueType(VT));
4931     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4932   } else if (VT.getSizeInBits() == 32) {
4933     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4934     if (Idx == 0)
4935       return Op;
4936
4937     // SHUFPS the element to the lowest double word, then movss.
4938     int Mask[4] = { Idx, -1, -1, -1 };
4939     EVT VVT = Op.getOperand(0).getValueType();
4940     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4941                                        DAG.getUNDEF(VVT), Mask);
4942     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4943                        DAG.getIntPtrConstant(0));
4944   } else if (VT.getSizeInBits() == 64) {
4945     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4946     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4947     //        to match extract_elt for f64.
4948     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4949     if (Idx == 0)
4950       return Op;
4951
4952     // UNPCKHPD the element to the lowest double word, then movsd.
4953     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4954     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4955     int Mask[2] = { 1, -1 };
4956     EVT VVT = Op.getOperand(0).getValueType();
4957     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4958                                        DAG.getUNDEF(VVT), Mask);
4959     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4960                        DAG.getIntPtrConstant(0));
4961   }
4962
4963   return SDValue();
4964 }
4965
4966 SDValue
4967 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4968                                                SelectionDAG &DAG) const {
4969   EVT VT = Op.getValueType();
4970   EVT EltVT = VT.getVectorElementType();
4971   DebugLoc dl = Op.getDebugLoc();
4972
4973   SDValue N0 = Op.getOperand(0);
4974   SDValue N1 = Op.getOperand(1);
4975   SDValue N2 = Op.getOperand(2);
4976
4977   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4978       isa<ConstantSDNode>(N2)) {
4979     unsigned Opc;
4980     if (VT == MVT::v8i16)
4981       Opc = X86ISD::PINSRW;
4982     else if (VT == MVT::v4i16)
4983       Opc = X86ISD::MMX_PINSRW;
4984     else if (VT == MVT::v16i8)
4985       Opc = X86ISD::PINSRB;
4986     else
4987       Opc = X86ISD::PINSRB;
4988
4989     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4990     // argument.
4991     if (N1.getValueType() != MVT::i32)
4992       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4993     if (N2.getValueType() != MVT::i32)
4994       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4995     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4996   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4997     // Bits [7:6] of the constant are the source select.  This will always be
4998     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4999     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5000     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5001     // Bits [5:4] of the constant are the destination select.  This is the
5002     //  value of the incoming immediate.
5003     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5004     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5005     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5006     // Create this as a scalar to vector..
5007     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5008     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5009   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5010     // PINSR* works with constant index.
5011     return Op;
5012   }
5013   return SDValue();
5014 }
5015
5016 SDValue
5017 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5018   EVT VT = Op.getValueType();
5019   EVT EltVT = VT.getVectorElementType();
5020
5021   if (Subtarget->hasSSE41())
5022     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5023
5024   if (EltVT == MVT::i8)
5025     return SDValue();
5026
5027   DebugLoc dl = Op.getDebugLoc();
5028   SDValue N0 = Op.getOperand(0);
5029   SDValue N1 = Op.getOperand(1);
5030   SDValue N2 = Op.getOperand(2);
5031
5032   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5033     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5034     // as its second argument.
5035     if (N1.getValueType() != MVT::i32)
5036       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5037     if (N2.getValueType() != MVT::i32)
5038       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5039     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5040                        dl, VT, N0, N1, N2);
5041   }
5042   return SDValue();
5043 }
5044
5045 SDValue
5046 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5047   DebugLoc dl = Op.getDebugLoc();
5048   if (Op.getValueType() == MVT::v2f32)
5049     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5050                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5051                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5052                                                Op.getOperand(0))));
5053
5054   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5055     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5056
5057   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5058   EVT VT = MVT::v2i32;
5059   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5060   default: break;
5061   case MVT::v16i8:
5062   case MVT::v8i16:
5063     VT = MVT::v4i32;
5064     break;
5065   }
5066   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5067                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5068 }
5069
5070 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5071 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5072 // one of the above mentioned nodes. It has to be wrapped because otherwise
5073 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5074 // be used to form addressing mode. These wrapped nodes will be selected
5075 // into MOV32ri.
5076 SDValue
5077 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5078   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5079
5080   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5081   // global base reg.
5082   unsigned char OpFlag = 0;
5083   unsigned WrapperKind = X86ISD::Wrapper;
5084   CodeModel::Model M = getTargetMachine().getCodeModel();
5085
5086   if (Subtarget->isPICStyleRIPRel() &&
5087       (M == CodeModel::Small || M == CodeModel::Kernel))
5088     WrapperKind = X86ISD::WrapperRIP;
5089   else if (Subtarget->isPICStyleGOT())
5090     OpFlag = X86II::MO_GOTOFF;
5091   else if (Subtarget->isPICStyleStubPIC())
5092     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5093
5094   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5095                                              CP->getAlignment(),
5096                                              CP->getOffset(), OpFlag);
5097   DebugLoc DL = CP->getDebugLoc();
5098   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5099   // With PIC, the address is actually $g + Offset.
5100   if (OpFlag) {
5101     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5102                          DAG.getNode(X86ISD::GlobalBaseReg,
5103                                      DebugLoc(), getPointerTy()),
5104                          Result);
5105   }
5106
5107   return Result;
5108 }
5109
5110 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5111   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5112
5113   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5114   // global base reg.
5115   unsigned char OpFlag = 0;
5116   unsigned WrapperKind = X86ISD::Wrapper;
5117   CodeModel::Model M = getTargetMachine().getCodeModel();
5118
5119   if (Subtarget->isPICStyleRIPRel() &&
5120       (M == CodeModel::Small || M == CodeModel::Kernel))
5121     WrapperKind = X86ISD::WrapperRIP;
5122   else if (Subtarget->isPICStyleGOT())
5123     OpFlag = X86II::MO_GOTOFF;
5124   else if (Subtarget->isPICStyleStubPIC())
5125     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5126
5127   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5128                                           OpFlag);
5129   DebugLoc DL = JT->getDebugLoc();
5130   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5131
5132   // With PIC, the address is actually $g + Offset.
5133   if (OpFlag) {
5134     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5135                          DAG.getNode(X86ISD::GlobalBaseReg,
5136                                      DebugLoc(), getPointerTy()),
5137                          Result);
5138   }
5139
5140   return Result;
5141 }
5142
5143 SDValue
5144 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5145   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5146
5147   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5148   // global base reg.
5149   unsigned char OpFlag = 0;
5150   unsigned WrapperKind = X86ISD::Wrapper;
5151   CodeModel::Model M = getTargetMachine().getCodeModel();
5152
5153   if (Subtarget->isPICStyleRIPRel() &&
5154       (M == CodeModel::Small || M == CodeModel::Kernel))
5155     WrapperKind = X86ISD::WrapperRIP;
5156   else if (Subtarget->isPICStyleGOT())
5157     OpFlag = X86II::MO_GOTOFF;
5158   else if (Subtarget->isPICStyleStubPIC())
5159     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5160
5161   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5162
5163   DebugLoc DL = Op.getDebugLoc();
5164   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5165
5166
5167   // With PIC, the address is actually $g + Offset.
5168   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5169       !Subtarget->is64Bit()) {
5170     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5171                          DAG.getNode(X86ISD::GlobalBaseReg,
5172                                      DebugLoc(), getPointerTy()),
5173                          Result);
5174   }
5175
5176   return Result;
5177 }
5178
5179 SDValue
5180 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5181   // Create the TargetBlockAddressAddress node.
5182   unsigned char OpFlags =
5183     Subtarget->ClassifyBlockAddressReference();
5184   CodeModel::Model M = getTargetMachine().getCodeModel();
5185   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5186   DebugLoc dl = Op.getDebugLoc();
5187   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5188                                        /*isTarget=*/true, OpFlags);
5189
5190   if (Subtarget->isPICStyleRIPRel() &&
5191       (M == CodeModel::Small || M == CodeModel::Kernel))
5192     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5193   else
5194     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5195
5196   // With PIC, the address is actually $g + Offset.
5197   if (isGlobalRelativeToPICBase(OpFlags)) {
5198     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5199                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5200                          Result);
5201   }
5202
5203   return Result;
5204 }
5205
5206 SDValue
5207 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5208                                       int64_t Offset,
5209                                       SelectionDAG &DAG) const {
5210   // Create the TargetGlobalAddress node, folding in the constant
5211   // offset if it is legal.
5212   unsigned char OpFlags =
5213     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5214   CodeModel::Model M = getTargetMachine().getCodeModel();
5215   SDValue Result;
5216   if (OpFlags == X86II::MO_NO_FLAG &&
5217       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5218     // A direct static reference to a global.
5219     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5220     Offset = 0;
5221   } else {
5222     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5223   }
5224
5225   if (Subtarget->isPICStyleRIPRel() &&
5226       (M == CodeModel::Small || M == CodeModel::Kernel))
5227     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5228   else
5229     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5230
5231   // With PIC, the address is actually $g + Offset.
5232   if (isGlobalRelativeToPICBase(OpFlags)) {
5233     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5234                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5235                          Result);
5236   }
5237
5238   // For globals that require a load from a stub to get the address, emit the
5239   // load.
5240   if (isGlobalStubReference(OpFlags))
5241     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5242                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5243
5244   // If there was a non-zero offset that we didn't fold, create an explicit
5245   // addition for it.
5246   if (Offset != 0)
5247     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5248                          DAG.getConstant(Offset, getPointerTy()));
5249
5250   return Result;
5251 }
5252
5253 SDValue
5254 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5255   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5256   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5257   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5258 }
5259
5260 static SDValue
5261 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5262            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5263            unsigned char OperandFlags) {
5264   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5265   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5266   DebugLoc dl = GA->getDebugLoc();
5267   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5268                                            GA->getValueType(0),
5269                                            GA->getOffset(),
5270                                            OperandFlags);
5271   if (InFlag) {
5272     SDValue Ops[] = { Chain,  TGA, *InFlag };
5273     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5274   } else {
5275     SDValue Ops[]  = { Chain, TGA };
5276     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5277   }
5278
5279   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5280   MFI->setAdjustsStack(true);
5281
5282   SDValue Flag = Chain.getValue(1);
5283   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5284 }
5285
5286 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5287 static SDValue
5288 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5289                                 const EVT PtrVT) {
5290   SDValue InFlag;
5291   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5292   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5293                                      DAG.getNode(X86ISD::GlobalBaseReg,
5294                                                  DebugLoc(), PtrVT), InFlag);
5295   InFlag = Chain.getValue(1);
5296
5297   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5298 }
5299
5300 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5301 static SDValue
5302 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5303                                 const EVT PtrVT) {
5304   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5305                     X86::RAX, X86II::MO_TLSGD);
5306 }
5307
5308 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5309 // "local exec" model.
5310 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5311                                    const EVT PtrVT, TLSModel::Model model,
5312                                    bool is64Bit) {
5313   DebugLoc dl = GA->getDebugLoc();
5314   // Get the Thread Pointer
5315   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5316                              DebugLoc(), PtrVT,
5317                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5318                                              MVT::i32));
5319
5320   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5321                                       NULL, 0, false, false, 0);
5322
5323   unsigned char OperandFlags = 0;
5324   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5325   // initialexec.
5326   unsigned WrapperKind = X86ISD::Wrapper;
5327   if (model == TLSModel::LocalExec) {
5328     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5329   } else if (is64Bit) {
5330     assert(model == TLSModel::InitialExec);
5331     OperandFlags = X86II::MO_GOTTPOFF;
5332     WrapperKind = X86ISD::WrapperRIP;
5333   } else {
5334     assert(model == TLSModel::InitialExec);
5335     OperandFlags = X86II::MO_INDNTPOFF;
5336   }
5337
5338   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5339   // exec)
5340   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5341                                            GA->getOffset(), OperandFlags);
5342   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5343
5344   if (model == TLSModel::InitialExec)
5345     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5346                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5347
5348   // The address of the thread local variable is the add of the thread
5349   // pointer with the offset of the variable.
5350   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5351 }
5352
5353 SDValue
5354 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5355   // TODO: implement the "local dynamic" model
5356   // TODO: implement the "initial exec"model for pic executables
5357   assert(Subtarget->isTargetELF() &&
5358          "TLS not implemented for non-ELF targets");
5359   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5360   const GlobalValue *GV = GA->getGlobal();
5361
5362   // If GV is an alias then use the aliasee for determining
5363   // thread-localness.
5364   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5365     GV = GA->resolveAliasedGlobal(false);
5366
5367   TLSModel::Model model = getTLSModel(GV,
5368                                       getTargetMachine().getRelocationModel());
5369
5370   switch (model) {
5371   case TLSModel::GeneralDynamic:
5372   case TLSModel::LocalDynamic: // not implemented
5373     if (Subtarget->is64Bit())
5374       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5375     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5376
5377   case TLSModel::InitialExec:
5378   case TLSModel::LocalExec:
5379     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5380                                Subtarget->is64Bit());
5381   }
5382
5383   llvm_unreachable("Unreachable");
5384   return SDValue();
5385 }
5386
5387
5388 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5389 /// take a 2 x i32 value to shift plus a shift amount.
5390 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5391   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5392   EVT VT = Op.getValueType();
5393   unsigned VTBits = VT.getSizeInBits();
5394   DebugLoc dl = Op.getDebugLoc();
5395   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5396   SDValue ShOpLo = Op.getOperand(0);
5397   SDValue ShOpHi = Op.getOperand(1);
5398   SDValue ShAmt  = Op.getOperand(2);
5399   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5400                                      DAG.getConstant(VTBits - 1, MVT::i8))
5401                        : DAG.getConstant(0, VT);
5402
5403   SDValue Tmp2, Tmp3;
5404   if (Op.getOpcode() == ISD::SHL_PARTS) {
5405     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5406     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5407   } else {
5408     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5409     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5410   }
5411
5412   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5413                                 DAG.getConstant(VTBits, MVT::i8));
5414   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5415                              AndNode, DAG.getConstant(0, MVT::i8));
5416
5417   SDValue Hi, Lo;
5418   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5419   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5420   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5421
5422   if (Op.getOpcode() == ISD::SHL_PARTS) {
5423     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5424     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5425   } else {
5426     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5427     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5428   }
5429
5430   SDValue Ops[2] = { Lo, Hi };
5431   return DAG.getMergeValues(Ops, 2, dl);
5432 }
5433
5434 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5435                                            SelectionDAG &DAG) const {
5436   EVT SrcVT = Op.getOperand(0).getValueType();
5437
5438   if (SrcVT.isVector()) {
5439     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5440       return Op;
5441     }
5442     return SDValue();
5443   }
5444
5445   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5446          "Unknown SINT_TO_FP to lower!");
5447
5448   // These are really Legal; return the operand so the caller accepts it as
5449   // Legal.
5450   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5451     return Op;
5452   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5453       Subtarget->is64Bit()) {
5454     return Op;
5455   }
5456
5457   DebugLoc dl = Op.getDebugLoc();
5458   unsigned Size = SrcVT.getSizeInBits()/8;
5459   MachineFunction &MF = DAG.getMachineFunction();
5460   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5461   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5462   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5463                                StackSlot,
5464                                PseudoSourceValue::getFixedStack(SSFI), 0,
5465                                false, false, 0);
5466   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5467 }
5468
5469 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5470                                      SDValue StackSlot, 
5471                                      SelectionDAG &DAG) const {
5472   // Build the FILD
5473   DebugLoc dl = Op.getDebugLoc();
5474   SDVTList Tys;
5475   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5476   if (useSSE)
5477     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5478   else
5479     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5480   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5481   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5482                                Tys, Ops, array_lengthof(Ops));
5483
5484   if (useSSE) {
5485     Chain = Result.getValue(1);
5486     SDValue InFlag = Result.getValue(2);
5487
5488     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5489     // shouldn't be necessary except that RFP cannot be live across
5490     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5491     MachineFunction &MF = DAG.getMachineFunction();
5492     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5493     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5494     Tys = DAG.getVTList(MVT::Other);
5495     SDValue Ops[] = {
5496       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5497     };
5498     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5499     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5500                          PseudoSourceValue::getFixedStack(SSFI), 0,
5501                          false, false, 0);
5502   }
5503
5504   return Result;
5505 }
5506
5507 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5508 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5509                                                SelectionDAG &DAG) const {
5510   // This algorithm is not obvious. Here it is in C code, more or less:
5511   /*
5512     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5513       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5514       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5515
5516       // Copy ints to xmm registers.
5517       __m128i xh = _mm_cvtsi32_si128( hi );
5518       __m128i xl = _mm_cvtsi32_si128( lo );
5519
5520       // Combine into low half of a single xmm register.
5521       __m128i x = _mm_unpacklo_epi32( xh, xl );
5522       __m128d d;
5523       double sd;
5524
5525       // Merge in appropriate exponents to give the integer bits the right
5526       // magnitude.
5527       x = _mm_unpacklo_epi32( x, exp );
5528
5529       // Subtract away the biases to deal with the IEEE-754 double precision
5530       // implicit 1.
5531       d = _mm_sub_pd( (__m128d) x, bias );
5532
5533       // All conversions up to here are exact. The correctly rounded result is
5534       // calculated using the current rounding mode using the following
5535       // horizontal add.
5536       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5537       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5538                                 // store doesn't really need to be here (except
5539                                 // maybe to zero the other double)
5540       return sd;
5541     }
5542   */
5543
5544   DebugLoc dl = Op.getDebugLoc();
5545   LLVMContext *Context = DAG.getContext();
5546
5547   // Build some magic constants.
5548   std::vector<Constant*> CV0;
5549   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5550   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5551   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5552   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5553   Constant *C0 = ConstantVector::get(CV0);
5554   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5555
5556   std::vector<Constant*> CV1;
5557   CV1.push_back(
5558     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5559   CV1.push_back(
5560     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5561   Constant *C1 = ConstantVector::get(CV1);
5562   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5563
5564   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5565                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5566                                         Op.getOperand(0),
5567                                         DAG.getIntPtrConstant(1)));
5568   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5569                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5570                                         Op.getOperand(0),
5571                                         DAG.getIntPtrConstant(0)));
5572   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5573   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5574                               PseudoSourceValue::getConstantPool(), 0,
5575                               false, false, 16);
5576   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5577   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5578   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5579                               PseudoSourceValue::getConstantPool(), 0,
5580                               false, false, 16);
5581   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5582
5583   // Add the halves; easiest way is to swap them into another reg first.
5584   int ShufMask[2] = { 1, -1 };
5585   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5586                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5587   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5588   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5589                      DAG.getIntPtrConstant(0));
5590 }
5591
5592 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5593 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5594                                                SelectionDAG &DAG) const {
5595   DebugLoc dl = Op.getDebugLoc();
5596   // FP constant to bias correct the final result.
5597   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5598                                    MVT::f64);
5599
5600   // Load the 32-bit value into an XMM register.
5601   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5602                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5603                                          Op.getOperand(0),
5604                                          DAG.getIntPtrConstant(0)));
5605
5606   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5607                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5608                      DAG.getIntPtrConstant(0));
5609
5610   // Or the load with the bias.
5611   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5612                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5613                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5614                                                    MVT::v2f64, Load)),
5615                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5616                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5617                                                    MVT::v2f64, Bias)));
5618   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5619                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5620                    DAG.getIntPtrConstant(0));
5621
5622   // Subtract the bias.
5623   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5624
5625   // Handle final rounding.
5626   EVT DestVT = Op.getValueType();
5627
5628   if (DestVT.bitsLT(MVT::f64)) {
5629     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5630                        DAG.getIntPtrConstant(0));
5631   } else if (DestVT.bitsGT(MVT::f64)) {
5632     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5633   }
5634
5635   // Handle final rounding.
5636   return Sub;
5637 }
5638
5639 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5640                                            SelectionDAG &DAG) const {
5641   SDValue N0 = Op.getOperand(0);
5642   DebugLoc dl = Op.getDebugLoc();
5643
5644   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5645   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5646   // the optimization here.
5647   if (DAG.SignBitIsZero(N0))
5648     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5649
5650   EVT SrcVT = N0.getValueType();
5651   EVT DstVT = Op.getValueType();
5652   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5653     return LowerUINT_TO_FP_i64(Op, DAG);
5654   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5655     return LowerUINT_TO_FP_i32(Op, DAG);
5656
5657   // Make a 64-bit buffer, and use it to build an FILD.
5658   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5659   if (SrcVT == MVT::i32) {
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     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5668     return Fild;
5669   }
5670
5671   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5672   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5673                                 StackSlot, NULL, 0, false, false, 0);
5674   // For i64 source, we need to add the appropriate power of 2 if the input
5675   // was negative.  This is the same as the optimization in
5676   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5677   // we must be careful to do the computation in x87 extended precision, not
5678   // in SSE. (The generic code can't know it's OK to do this, or how to.)
5679   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5680   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5681   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5682
5683   APInt FF(32, 0x5F800000ULL);
5684
5685   // Check whether the sign bit is set.
5686   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5687                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5688                                  ISD::SETLT);
5689
5690   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5691   SDValue FudgePtr = DAG.getConstantPool(
5692                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5693                                          getPointerTy());
5694
5695   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5696   SDValue Zero = DAG.getIntPtrConstant(0);
5697   SDValue Four = DAG.getIntPtrConstant(4);
5698   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5699                                Zero, Four);
5700   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5701
5702   // Load the value out, extending it from f32 to f80.
5703   // FIXME: Avoid the extend by constructing the right constant pool?
5704   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5705                                  FudgePtr, PseudoSourceValue::getConstantPool(),
5706                                  0, MVT::f32, false, false, 4);
5707   // Extend everything to 80 bits to force it to be done on x87.
5708   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5709   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5710 }
5711
5712 std::pair<SDValue,SDValue> X86TargetLowering::
5713 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5714   DebugLoc dl = Op.getDebugLoc();
5715
5716   EVT DstTy = Op.getValueType();
5717
5718   if (!IsSigned) {
5719     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5720     DstTy = MVT::i64;
5721   }
5722
5723   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5724          DstTy.getSimpleVT() >= MVT::i16 &&
5725          "Unknown FP_TO_SINT to lower!");
5726
5727   // These are really Legal.
5728   if (DstTy == MVT::i32 &&
5729       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5730     return std::make_pair(SDValue(), SDValue());
5731   if (Subtarget->is64Bit() &&
5732       DstTy == MVT::i64 &&
5733       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5734     return std::make_pair(SDValue(), SDValue());
5735
5736   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5737   // stack slot.
5738   MachineFunction &MF = DAG.getMachineFunction();
5739   unsigned MemSize = DstTy.getSizeInBits()/8;
5740   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5741   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5742
5743   unsigned Opc;
5744   switch (DstTy.getSimpleVT().SimpleTy) {
5745   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5746   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5747   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5748   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5749   }
5750
5751   SDValue Chain = DAG.getEntryNode();
5752   SDValue Value = Op.getOperand(0);
5753   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5754     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5755     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5756                          PseudoSourceValue::getFixedStack(SSFI), 0,
5757                          false, false, 0);
5758     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5759     SDValue Ops[] = {
5760       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5761     };
5762     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5763     Chain = Value.getValue(1);
5764     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5765     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5766   }
5767
5768   // Build the FP_TO_INT*_IN_MEM
5769   SDValue Ops[] = { Chain, Value, StackSlot };
5770   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5771
5772   return std::make_pair(FIST, StackSlot);
5773 }
5774
5775 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5776                                            SelectionDAG &DAG) const {
5777   if (Op.getValueType().isVector()) {
5778     if (Op.getValueType() == MVT::v2i32 &&
5779         Op.getOperand(0).getValueType() == MVT::v2f64) {
5780       return Op;
5781     }
5782     return SDValue();
5783   }
5784
5785   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5786   SDValue FIST = Vals.first, StackSlot = Vals.second;
5787   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5788   if (FIST.getNode() == 0) return Op;
5789
5790   // Load the result.
5791   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5792                      FIST, StackSlot, NULL, 0, false, false, 0);
5793 }
5794
5795 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5796                                            SelectionDAG &DAG) const {
5797   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5798   SDValue FIST = Vals.first, StackSlot = Vals.second;
5799   assert(FIST.getNode() && "Unexpected failure");
5800
5801   // Load the result.
5802   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5803                      FIST, StackSlot, NULL, 0, false, false, 0);
5804 }
5805
5806 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5807                                      SelectionDAG &DAG) const {
5808   LLVMContext *Context = DAG.getContext();
5809   DebugLoc dl = Op.getDebugLoc();
5810   EVT VT = Op.getValueType();
5811   EVT EltVT = VT;
5812   if (VT.isVector())
5813     EltVT = VT.getVectorElementType();
5814   std::vector<Constant*> CV;
5815   if (EltVT == MVT::f64) {
5816     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5817     CV.push_back(C);
5818     CV.push_back(C);
5819   } else {
5820     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5821     CV.push_back(C);
5822     CV.push_back(C);
5823     CV.push_back(C);
5824     CV.push_back(C);
5825   }
5826   Constant *C = ConstantVector::get(CV);
5827   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5828   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5829                              PseudoSourceValue::getConstantPool(), 0,
5830                              false, false, 16);
5831   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5832 }
5833
5834 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5835   LLVMContext *Context = DAG.getContext();
5836   DebugLoc dl = Op.getDebugLoc();
5837   EVT VT = Op.getValueType();
5838   EVT EltVT = VT;
5839   if (VT.isVector())
5840     EltVT = VT.getVectorElementType();
5841   std::vector<Constant*> CV;
5842   if (EltVT == MVT::f64) {
5843     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5844     CV.push_back(C);
5845     CV.push_back(C);
5846   } else {
5847     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5848     CV.push_back(C);
5849     CV.push_back(C);
5850     CV.push_back(C);
5851     CV.push_back(C);
5852   }
5853   Constant *C = ConstantVector::get(CV);
5854   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5855   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5856                              PseudoSourceValue::getConstantPool(), 0,
5857                              false, false, 16);
5858   if (VT.isVector()) {
5859     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5860                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5861                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5862                                 Op.getOperand(0)),
5863                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5864   } else {
5865     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5866   }
5867 }
5868
5869 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5870   LLVMContext *Context = DAG.getContext();
5871   SDValue Op0 = Op.getOperand(0);
5872   SDValue Op1 = Op.getOperand(1);
5873   DebugLoc dl = Op.getDebugLoc();
5874   EVT VT = Op.getValueType();
5875   EVT SrcVT = Op1.getValueType();
5876
5877   // If second operand is smaller, extend it first.
5878   if (SrcVT.bitsLT(VT)) {
5879     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5880     SrcVT = VT;
5881   }
5882   // And if it is bigger, shrink it first.
5883   if (SrcVT.bitsGT(VT)) {
5884     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5885     SrcVT = VT;
5886   }
5887
5888   // At this point the operands and the result should have the same
5889   // type, and that won't be f80 since that is not custom lowered.
5890
5891   // First get the sign bit of second operand.
5892   std::vector<Constant*> CV;
5893   if (SrcVT == MVT::f64) {
5894     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5895     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5896   } else {
5897     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5898     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5899     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5900     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5901   }
5902   Constant *C = ConstantVector::get(CV);
5903   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5904   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5905                               PseudoSourceValue::getConstantPool(), 0,
5906                               false, false, 16);
5907   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5908
5909   // Shift sign bit right or left if the two operands have different types.
5910   if (SrcVT.bitsGT(VT)) {
5911     // Op0 is MVT::f32, Op1 is MVT::f64.
5912     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5913     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5914                           DAG.getConstant(32, MVT::i32));
5915     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5916     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5917                           DAG.getIntPtrConstant(0));
5918   }
5919
5920   // Clear first operand sign bit.
5921   CV.clear();
5922   if (VT == MVT::f64) {
5923     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5924     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5925   } else {
5926     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5927     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5928     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5929     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5930   }
5931   C = ConstantVector::get(CV);
5932   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5933   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5934                               PseudoSourceValue::getConstantPool(), 0,
5935                               false, false, 16);
5936   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5937
5938   // Or the value with the sign bit.
5939   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5940 }
5941
5942 /// Emit nodes that will be selected as "test Op0,Op0", or something
5943 /// equivalent.
5944 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5945                                     SelectionDAG &DAG) const {
5946   DebugLoc dl = Op.getDebugLoc();
5947
5948   // CF and OF aren't always set the way we want. Determine which
5949   // of these we need.
5950   bool NeedCF = false;
5951   bool NeedOF = false;
5952   switch (X86CC) {
5953   case X86::COND_A: case X86::COND_AE:
5954   case X86::COND_B: case X86::COND_BE:
5955     NeedCF = true;
5956     break;
5957   case X86::COND_G: case X86::COND_GE:
5958   case X86::COND_L: case X86::COND_LE:
5959   case X86::COND_O: case X86::COND_NO:
5960     NeedOF = true;
5961     break;
5962   default: break;
5963   }
5964
5965   // See if we can use the EFLAGS value from the operand instead of
5966   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5967   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5968   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5969     unsigned Opcode = 0;
5970     unsigned NumOperands = 0;
5971     switch (Op.getNode()->getOpcode()) {
5972     case ISD::ADD:
5973       // Due to an isel shortcoming, be conservative if this add is
5974       // likely to be selected as part of a load-modify-store
5975       // instruction. When the root node in a match is a store, isel
5976       // doesn't know how to remap non-chain non-flag uses of other
5977       // nodes in the match, such as the ADD in this case. This leads
5978       // to the ADD being left around and reselected, with the result
5979       // being two adds in the output.  Alas, even if none our users
5980       // are stores, that doesn't prove we're O.K.  Ergo, if we have
5981       // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5982       // A better fix seems to require climbing the DAG back to the
5983       // root, and it doesn't seem to be worth the effort.
5984       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5985              UE = Op.getNode()->use_end(); UI != UE; ++UI)
5986         if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5987           goto default_case;
5988       if (ConstantSDNode *C =
5989             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5990         // An add of one will be selected as an INC.
5991         if (C->getAPIntValue() == 1) {
5992           Opcode = X86ISD::INC;
5993           NumOperands = 1;
5994           break;
5995         }
5996         // An add of negative one (subtract of one) will be selected as a DEC.
5997         if (C->getAPIntValue().isAllOnesValue()) {
5998           Opcode = X86ISD::DEC;
5999           NumOperands = 1;
6000           break;
6001         }
6002       }
6003       // Otherwise use a regular EFLAGS-setting add.
6004       Opcode = X86ISD::ADD;
6005       NumOperands = 2;
6006       break;
6007     case ISD::AND: {
6008       // If the primary and result isn't used, don't bother using X86ISD::AND,
6009       // because a TEST instruction will be better.
6010       bool NonFlagUse = false;
6011       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6012              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6013         SDNode *User = *UI;
6014         unsigned UOpNo = UI.getOperandNo();
6015         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6016           // Look pass truncate.
6017           UOpNo = User->use_begin().getOperandNo();
6018           User = *User->use_begin();
6019         }
6020         if (User->getOpcode() != ISD::BRCOND &&
6021             User->getOpcode() != ISD::SETCC &&
6022             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6023           NonFlagUse = true;
6024           break;
6025         }
6026       }
6027       if (!NonFlagUse)
6028         break;
6029     }
6030     // FALL THROUGH
6031     case ISD::SUB:
6032     case ISD::OR:
6033     case ISD::XOR:
6034       // Due to the ISEL shortcoming noted above, be conservative if this op is
6035       // likely to be selected as part of a load-modify-store instruction.
6036       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6037            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6038         if (UI->getOpcode() == ISD::STORE)
6039           goto default_case;
6040       // Otherwise use a regular EFLAGS-setting instruction.
6041       switch (Op.getNode()->getOpcode()) {
6042       case ISD::SUB: Opcode = X86ISD::SUB; break;
6043       case ISD::OR:  Opcode = X86ISD::OR;  break;
6044       case ISD::XOR: Opcode = X86ISD::XOR; break;
6045       case ISD::AND: Opcode = X86ISD::AND; break;
6046       default: llvm_unreachable("unexpected operator!");
6047       }
6048       NumOperands = 2;
6049       break;
6050     case X86ISD::ADD:
6051     case X86ISD::SUB:
6052     case X86ISD::INC:
6053     case X86ISD::DEC:
6054     case X86ISD::OR:
6055     case X86ISD::XOR:
6056     case X86ISD::AND:
6057       return SDValue(Op.getNode(), 1);
6058     default:
6059     default_case:
6060       break;
6061     }
6062     if (Opcode != 0) {
6063       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6064       SmallVector<SDValue, 4> Ops;
6065       for (unsigned i = 0; i != NumOperands; ++i)
6066         Ops.push_back(Op.getOperand(i));
6067       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6068       DAG.ReplaceAllUsesWith(Op, New);
6069       return SDValue(New.getNode(), 1);
6070     }
6071   }
6072
6073   // Otherwise just emit a CMP with 0, which is the TEST pattern.
6074   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6075                      DAG.getConstant(0, Op.getValueType()));
6076 }
6077
6078 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6079 /// equivalent.
6080 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6081                                    SelectionDAG &DAG) const {
6082   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6083     if (C->getAPIntValue() == 0)
6084       return EmitTest(Op0, X86CC, DAG);
6085
6086   DebugLoc dl = Op0.getDebugLoc();
6087   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6088 }
6089
6090 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6091 /// if it's possible.
6092 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6093                                      DebugLoc dl, SelectionDAG &DAG) const {
6094   SDValue Op0 = And.getOperand(0);
6095   SDValue Op1 = And.getOperand(1);
6096   if (Op0.getOpcode() == ISD::TRUNCATE)
6097     Op0 = Op0.getOperand(0);
6098   if (Op1.getOpcode() == ISD::TRUNCATE)
6099     Op1 = Op1.getOperand(0);
6100
6101   SDValue LHS, RHS;
6102   if (Op1.getOpcode() == ISD::SHL) {
6103     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6104       if (And10C->getZExtValue() == 1) {
6105         LHS = Op0;
6106         RHS = Op1.getOperand(1);
6107       }
6108   } else if (Op0.getOpcode() == ISD::SHL) {
6109     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6110       if (And00C->getZExtValue() == 1) {
6111         LHS = Op1;
6112         RHS = Op0.getOperand(1);
6113       }
6114   } else if (Op1.getOpcode() == ISD::Constant) {
6115     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6116     SDValue AndLHS = Op0;
6117     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6118       LHS = AndLHS.getOperand(0);
6119       RHS = AndLHS.getOperand(1);
6120     }
6121   }
6122
6123   if (LHS.getNode()) {
6124     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6125     // instruction.  Since the shift amount is in-range-or-undefined, we know
6126     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6127     // the encoding for the i16 version is larger than the i32 version.
6128     // Also promote i16 to i32 for performance / code size reason.
6129     if (LHS.getValueType() == MVT::i8 ||
6130         LHS.getValueType() == MVT::i16)
6131       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6132
6133     // If the operand types disagree, extend the shift amount to match.  Since
6134     // BT ignores high bits (like shifts) we can use anyextend.
6135     if (LHS.getValueType() != RHS.getValueType())
6136       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6137
6138     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6139     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6140     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6141                        DAG.getConstant(Cond, MVT::i8), BT);
6142   }
6143
6144   return SDValue();
6145 }
6146
6147 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6148   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6149   SDValue Op0 = Op.getOperand(0);
6150   SDValue Op1 = Op.getOperand(1);
6151   DebugLoc dl = Op.getDebugLoc();
6152   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6153
6154   // Optimize to BT if possible.
6155   // Lower (X & (1 << N)) == 0 to BT(X, N).
6156   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6157   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6158   if (Op0.getOpcode() == ISD::AND &&
6159       Op0.hasOneUse() &&
6160       Op1.getOpcode() == ISD::Constant &&
6161       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6162       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6163     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6164     if (NewSetCC.getNode())
6165       return NewSetCC;
6166   }
6167
6168   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6169   if (Op0.getOpcode() == X86ISD::SETCC &&
6170       Op1.getOpcode() == ISD::Constant &&
6171       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6172        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6173       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6174     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6175     bool Invert = (CC == ISD::SETNE) ^
6176       cast<ConstantSDNode>(Op1)->isNullValue();
6177     if (Invert)
6178       CCode = X86::GetOppositeBranchCondition(CCode);
6179     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6180                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6181   }
6182
6183   bool isFP = Op1.getValueType().isFloatingPoint();
6184   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6185   if (X86CC == X86::COND_INVALID)
6186     return SDValue();
6187
6188   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6189
6190   // Use sbb x, x to materialize carry bit into a GPR.
6191   if (X86CC == X86::COND_B)
6192     return DAG.getNode(ISD::AND, dl, MVT::i8,
6193                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6194                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6195                        DAG.getConstant(1, MVT::i8));
6196
6197   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6198                      DAG.getConstant(X86CC, MVT::i8), Cond);
6199 }
6200
6201 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6202   SDValue Cond;
6203   SDValue Op0 = Op.getOperand(0);
6204   SDValue Op1 = Op.getOperand(1);
6205   SDValue CC = Op.getOperand(2);
6206   EVT VT = Op.getValueType();
6207   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6208   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6209   DebugLoc dl = Op.getDebugLoc();
6210
6211   if (isFP) {
6212     unsigned SSECC = 8;
6213     EVT VT0 = Op0.getValueType();
6214     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6215     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6216     bool Swap = false;
6217
6218     switch (SetCCOpcode) {
6219     default: break;
6220     case ISD::SETOEQ:
6221     case ISD::SETEQ:  SSECC = 0; break;
6222     case ISD::SETOGT:
6223     case ISD::SETGT: Swap = true; // Fallthrough
6224     case ISD::SETLT:
6225     case ISD::SETOLT: SSECC = 1; break;
6226     case ISD::SETOGE:
6227     case ISD::SETGE: Swap = true; // Fallthrough
6228     case ISD::SETLE:
6229     case ISD::SETOLE: SSECC = 2; break;
6230     case ISD::SETUO:  SSECC = 3; break;
6231     case ISD::SETUNE:
6232     case ISD::SETNE:  SSECC = 4; break;
6233     case ISD::SETULE: Swap = true;
6234     case ISD::SETUGE: SSECC = 5; break;
6235     case ISD::SETULT: Swap = true;
6236     case ISD::SETUGT: SSECC = 6; break;
6237     case ISD::SETO:   SSECC = 7; break;
6238     }
6239     if (Swap)
6240       std::swap(Op0, Op1);
6241
6242     // In the two special cases we can't handle, emit two comparisons.
6243     if (SSECC == 8) {
6244       if (SetCCOpcode == ISD::SETUEQ) {
6245         SDValue UNORD, EQ;
6246         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6247         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6248         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6249       }
6250       else if (SetCCOpcode == ISD::SETONE) {
6251         SDValue ORD, NEQ;
6252         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6253         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6254         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6255       }
6256       llvm_unreachable("Illegal FP comparison");
6257     }
6258     // Handle all other FP comparisons here.
6259     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6260   }
6261
6262   // We are handling one of the integer comparisons here.  Since SSE only has
6263   // GT and EQ comparisons for integer, swapping operands and multiple
6264   // operations may be required for some comparisons.
6265   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6266   bool Swap = false, Invert = false, FlipSigns = false;
6267
6268   switch (VT.getSimpleVT().SimpleTy) {
6269   default: break;
6270   case MVT::v8i8:
6271   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6272   case MVT::v4i16:
6273   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6274   case MVT::v2i32:
6275   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6276   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6277   }
6278
6279   switch (SetCCOpcode) {
6280   default: break;
6281   case ISD::SETNE:  Invert = true;
6282   case ISD::SETEQ:  Opc = EQOpc; break;
6283   case ISD::SETLT:  Swap = true;
6284   case ISD::SETGT:  Opc = GTOpc; break;
6285   case ISD::SETGE:  Swap = true;
6286   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6287   case ISD::SETULT: Swap = true;
6288   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6289   case ISD::SETUGE: Swap = true;
6290   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6291   }
6292   if (Swap)
6293     std::swap(Op0, Op1);
6294
6295   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6296   // bits of the inputs before performing those operations.
6297   if (FlipSigns) {
6298     EVT EltVT = VT.getVectorElementType();
6299     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6300                                       EltVT);
6301     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6302     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6303                                     SignBits.size());
6304     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6305     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6306   }
6307
6308   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6309
6310   // If the logical-not of the result is required, perform that now.
6311   if (Invert)
6312     Result = DAG.getNOT(dl, Result, VT);
6313
6314   return Result;
6315 }
6316
6317 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6318 static bool isX86LogicalCmp(SDValue Op) {
6319   unsigned Opc = Op.getNode()->getOpcode();
6320   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6321     return true;
6322   if (Op.getResNo() == 1 &&
6323       (Opc == X86ISD::ADD ||
6324        Opc == X86ISD::SUB ||
6325        Opc == X86ISD::SMUL ||
6326        Opc == X86ISD::UMUL ||
6327        Opc == X86ISD::INC ||
6328        Opc == X86ISD::DEC ||
6329        Opc == X86ISD::OR ||
6330        Opc == X86ISD::XOR ||
6331        Opc == X86ISD::AND))
6332     return true;
6333
6334   return false;
6335 }
6336
6337 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6338   bool addTest = true;
6339   SDValue Cond  = Op.getOperand(0);
6340   DebugLoc dl = Op.getDebugLoc();
6341   SDValue CC;
6342
6343   if (Cond.getOpcode() == ISD::SETCC) {
6344     SDValue NewCond = LowerSETCC(Cond, DAG);
6345     if (NewCond.getNode())
6346       Cond = NewCond;
6347   }
6348
6349   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6350   SDValue Op1 = Op.getOperand(1);
6351   SDValue Op2 = Op.getOperand(2);
6352   if (Cond.getOpcode() == X86ISD::SETCC &&
6353       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6354     SDValue Cmp = Cond.getOperand(1);
6355     if (Cmp.getOpcode() == X86ISD::CMP) {
6356       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6357       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6358       ConstantSDNode *RHSC =
6359         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6360       if (N1C && N1C->isAllOnesValue() &&
6361           N2C && N2C->isNullValue() &&
6362           RHSC && RHSC->isNullValue()) {
6363         SDValue CmpOp0 = Cmp.getOperand(0);
6364         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6365                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6366         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6367                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6368       }
6369     }
6370   }
6371
6372   // Look pass (and (setcc_carry (cmp ...)), 1).
6373   if (Cond.getOpcode() == ISD::AND &&
6374       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6375     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6376     if (C && C->getAPIntValue() == 1) 
6377       Cond = Cond.getOperand(0);
6378   }
6379
6380   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6381   // setting operand in place of the X86ISD::SETCC.
6382   if (Cond.getOpcode() == X86ISD::SETCC ||
6383       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6384     CC = Cond.getOperand(0);
6385
6386     SDValue Cmp = Cond.getOperand(1);
6387     unsigned Opc = Cmp.getOpcode();
6388     EVT VT = Op.getValueType();
6389
6390     bool IllegalFPCMov = false;
6391     if (VT.isFloatingPoint() && !VT.isVector() &&
6392         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6393       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6394
6395     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6396         Opc == X86ISD::BT) { // FIXME
6397       Cond = Cmp;
6398       addTest = false;
6399     }
6400   }
6401
6402   if (addTest) {
6403     // Look pass the truncate.
6404     if (Cond.getOpcode() == ISD::TRUNCATE)
6405       Cond = Cond.getOperand(0);
6406
6407     // We know the result of AND is compared against zero. Try to match
6408     // it to BT.
6409     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6410       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6411       if (NewSetCC.getNode()) {
6412         CC = NewSetCC.getOperand(0);
6413         Cond = NewSetCC.getOperand(1);
6414         addTest = false;
6415       }
6416     }
6417   }
6418
6419   if (addTest) {
6420     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6421     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6422   }
6423
6424   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6425   // condition is true.
6426   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6427   SDValue Ops[] = { Op2, Op1, CC, Cond };
6428   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6429 }
6430
6431 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6432 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6433 // from the AND / OR.
6434 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6435   Opc = Op.getOpcode();
6436   if (Opc != ISD::OR && Opc != ISD::AND)
6437     return false;
6438   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6439           Op.getOperand(0).hasOneUse() &&
6440           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6441           Op.getOperand(1).hasOneUse());
6442 }
6443
6444 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6445 // 1 and that the SETCC node has a single use.
6446 static bool isXor1OfSetCC(SDValue Op) {
6447   if (Op.getOpcode() != ISD::XOR)
6448     return false;
6449   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6450   if (N1C && N1C->getAPIntValue() == 1) {
6451     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6452       Op.getOperand(0).hasOneUse();
6453   }
6454   return false;
6455 }
6456
6457 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6458   bool addTest = true;
6459   SDValue Chain = Op.getOperand(0);
6460   SDValue Cond  = Op.getOperand(1);
6461   SDValue Dest  = Op.getOperand(2);
6462   DebugLoc dl = Op.getDebugLoc();
6463   SDValue CC;
6464
6465   if (Cond.getOpcode() == ISD::SETCC) {
6466     SDValue NewCond = LowerSETCC(Cond, DAG);
6467     if (NewCond.getNode())
6468       Cond = NewCond;
6469   }
6470 #if 0
6471   // FIXME: LowerXALUO doesn't handle these!!
6472   else if (Cond.getOpcode() == X86ISD::ADD  ||
6473            Cond.getOpcode() == X86ISD::SUB  ||
6474            Cond.getOpcode() == X86ISD::SMUL ||
6475            Cond.getOpcode() == X86ISD::UMUL)
6476     Cond = LowerXALUO(Cond, DAG);
6477 #endif
6478
6479   // Look pass (and (setcc_carry (cmp ...)), 1).
6480   if (Cond.getOpcode() == ISD::AND &&
6481       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6482     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6483     if (C && C->getAPIntValue() == 1) 
6484       Cond = Cond.getOperand(0);
6485   }
6486
6487   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6488   // setting operand in place of the X86ISD::SETCC.
6489   if (Cond.getOpcode() == X86ISD::SETCC ||
6490       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6491     CC = Cond.getOperand(0);
6492
6493     SDValue Cmp = Cond.getOperand(1);
6494     unsigned Opc = Cmp.getOpcode();
6495     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6496     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6497       Cond = Cmp;
6498       addTest = false;
6499     } else {
6500       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6501       default: break;
6502       case X86::COND_O:
6503       case X86::COND_B:
6504         // These can only come from an arithmetic instruction with overflow,
6505         // e.g. SADDO, UADDO.
6506         Cond = Cond.getNode()->getOperand(1);
6507         addTest = false;
6508         break;
6509       }
6510     }
6511   } else {
6512     unsigned CondOpc;
6513     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6514       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6515       if (CondOpc == ISD::OR) {
6516         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6517         // two branches instead of an explicit OR instruction with a
6518         // separate test.
6519         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6520             isX86LogicalCmp(Cmp)) {
6521           CC = Cond.getOperand(0).getOperand(0);
6522           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6523                               Chain, Dest, CC, Cmp);
6524           CC = Cond.getOperand(1).getOperand(0);
6525           Cond = Cmp;
6526           addTest = false;
6527         }
6528       } else { // ISD::AND
6529         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6530         // two branches instead of an explicit AND instruction with a
6531         // separate test. However, we only do this if this block doesn't
6532         // have a fall-through edge, because this requires an explicit
6533         // jmp when the condition is false.
6534         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6535             isX86LogicalCmp(Cmp) &&
6536             Op.getNode()->hasOneUse()) {
6537           X86::CondCode CCode =
6538             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6539           CCode = X86::GetOppositeBranchCondition(CCode);
6540           CC = DAG.getConstant(CCode, MVT::i8);
6541           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6542           // Look for an unconditional branch following this conditional branch.
6543           // We need this because we need to reverse the successors in order
6544           // to implement FCMP_OEQ.
6545           if (User.getOpcode() == ISD::BR) {
6546             SDValue FalseBB = User.getOperand(1);
6547             SDValue NewBR =
6548               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6549             assert(NewBR == User);
6550             Dest = FalseBB;
6551
6552             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6553                                 Chain, Dest, CC, Cmp);
6554             X86::CondCode CCode =
6555               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6556             CCode = X86::GetOppositeBranchCondition(CCode);
6557             CC = DAG.getConstant(CCode, MVT::i8);
6558             Cond = Cmp;
6559             addTest = false;
6560           }
6561         }
6562       }
6563     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6564       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6565       // It should be transformed during dag combiner except when the condition
6566       // is set by a arithmetics with overflow node.
6567       X86::CondCode CCode =
6568         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6569       CCode = X86::GetOppositeBranchCondition(CCode);
6570       CC = DAG.getConstant(CCode, MVT::i8);
6571       Cond = Cond.getOperand(0).getOperand(1);
6572       addTest = false;
6573     }
6574   }
6575
6576   if (addTest) {
6577     // Look pass the truncate.
6578     if (Cond.getOpcode() == ISD::TRUNCATE)
6579       Cond = Cond.getOperand(0);
6580
6581     // We know the result of AND is compared against zero. Try to match
6582     // it to BT.
6583     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6584       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6585       if (NewSetCC.getNode()) {
6586         CC = NewSetCC.getOperand(0);
6587         Cond = NewSetCC.getOperand(1);
6588         addTest = false;
6589       }
6590     }
6591   }
6592
6593   if (addTest) {
6594     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6595     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6596   }
6597   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6598                      Chain, Dest, CC, Cond);
6599 }
6600
6601
6602 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6603 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6604 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6605 // that the guard pages used by the OS virtual memory manager are allocated in
6606 // correct sequence.
6607 SDValue
6608 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6609                                            SelectionDAG &DAG) const {
6610   assert(Subtarget->isTargetCygMing() &&
6611          "This should be used only on Cygwin/Mingw targets");
6612   DebugLoc dl = Op.getDebugLoc();
6613
6614   // Get the inputs.
6615   SDValue Chain = Op.getOperand(0);
6616   SDValue Size  = Op.getOperand(1);
6617   // FIXME: Ensure alignment here
6618
6619   SDValue Flag;
6620
6621   EVT IntPtr = getPointerTy();
6622   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6623
6624   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6625   Flag = Chain.getValue(1);
6626
6627   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6628
6629   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6630   Flag = Chain.getValue(1);
6631
6632   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6633
6634   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6635   return DAG.getMergeValues(Ops1, 2, dl);
6636 }
6637
6638 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6639   MachineFunction &MF = DAG.getMachineFunction();
6640   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6641
6642   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6643   DebugLoc dl = Op.getDebugLoc();
6644
6645   if (!Subtarget->is64Bit()) {
6646     // vastart just stores the address of the VarArgsFrameIndex slot into the
6647     // memory location argument.
6648     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6649                                    getPointerTy());
6650     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6651                         false, false, 0);
6652   }
6653
6654   // __va_list_tag:
6655   //   gp_offset         (0 - 6 * 8)
6656   //   fp_offset         (48 - 48 + 8 * 16)
6657   //   overflow_arg_area (point to parameters coming in memory).
6658   //   reg_save_area
6659   SmallVector<SDValue, 8> MemOps;
6660   SDValue FIN = Op.getOperand(1);
6661   // Store gp_offset
6662   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6663                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6664                                                MVT::i32),
6665                                FIN, SV, 0, false, false, 0);
6666   MemOps.push_back(Store);
6667
6668   // Store fp_offset
6669   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6670                     FIN, DAG.getIntPtrConstant(4));
6671   Store = DAG.getStore(Op.getOperand(0), dl,
6672                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6673                                        MVT::i32),
6674                        FIN, SV, 0, false, false, 0);
6675   MemOps.push_back(Store);
6676
6677   // Store ptr to overflow_arg_area
6678   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6679                     FIN, DAG.getIntPtrConstant(4));
6680   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6681                                     getPointerTy());
6682   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6683                        false, false, 0);
6684   MemOps.push_back(Store);
6685
6686   // Store ptr to reg_save_area.
6687   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6688                     FIN, DAG.getIntPtrConstant(8));
6689   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6690                                     getPointerTy());
6691   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6692                        false, false, 0);
6693   MemOps.push_back(Store);
6694   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6695                      &MemOps[0], MemOps.size());
6696 }
6697
6698 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6699   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6700   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6701   SDValue Chain = Op.getOperand(0);
6702   SDValue SrcPtr = Op.getOperand(1);
6703   SDValue SrcSV = Op.getOperand(2);
6704
6705   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6706   return SDValue();
6707 }
6708
6709 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6710   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6711   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6712   SDValue Chain = Op.getOperand(0);
6713   SDValue DstPtr = Op.getOperand(1);
6714   SDValue SrcPtr = Op.getOperand(2);
6715   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6716   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6717   DebugLoc dl = Op.getDebugLoc();
6718
6719   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6720                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6721                        false, DstSV, 0, SrcSV, 0);
6722 }
6723
6724 SDValue
6725 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6726   DebugLoc dl = Op.getDebugLoc();
6727   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6728   switch (IntNo) {
6729   default: return SDValue();    // Don't custom lower most intrinsics.
6730   // Comparison intrinsics.
6731   case Intrinsic::x86_sse_comieq_ss:
6732   case Intrinsic::x86_sse_comilt_ss:
6733   case Intrinsic::x86_sse_comile_ss:
6734   case Intrinsic::x86_sse_comigt_ss:
6735   case Intrinsic::x86_sse_comige_ss:
6736   case Intrinsic::x86_sse_comineq_ss:
6737   case Intrinsic::x86_sse_ucomieq_ss:
6738   case Intrinsic::x86_sse_ucomilt_ss:
6739   case Intrinsic::x86_sse_ucomile_ss:
6740   case Intrinsic::x86_sse_ucomigt_ss:
6741   case Intrinsic::x86_sse_ucomige_ss:
6742   case Intrinsic::x86_sse_ucomineq_ss:
6743   case Intrinsic::x86_sse2_comieq_sd:
6744   case Intrinsic::x86_sse2_comilt_sd:
6745   case Intrinsic::x86_sse2_comile_sd:
6746   case Intrinsic::x86_sse2_comigt_sd:
6747   case Intrinsic::x86_sse2_comige_sd:
6748   case Intrinsic::x86_sse2_comineq_sd:
6749   case Intrinsic::x86_sse2_ucomieq_sd:
6750   case Intrinsic::x86_sse2_ucomilt_sd:
6751   case Intrinsic::x86_sse2_ucomile_sd:
6752   case Intrinsic::x86_sse2_ucomigt_sd:
6753   case Intrinsic::x86_sse2_ucomige_sd:
6754   case Intrinsic::x86_sse2_ucomineq_sd: {
6755     unsigned Opc = 0;
6756     ISD::CondCode CC = ISD::SETCC_INVALID;
6757     switch (IntNo) {
6758     default: break;
6759     case Intrinsic::x86_sse_comieq_ss:
6760     case Intrinsic::x86_sse2_comieq_sd:
6761       Opc = X86ISD::COMI;
6762       CC = ISD::SETEQ;
6763       break;
6764     case Intrinsic::x86_sse_comilt_ss:
6765     case Intrinsic::x86_sse2_comilt_sd:
6766       Opc = X86ISD::COMI;
6767       CC = ISD::SETLT;
6768       break;
6769     case Intrinsic::x86_sse_comile_ss:
6770     case Intrinsic::x86_sse2_comile_sd:
6771       Opc = X86ISD::COMI;
6772       CC = ISD::SETLE;
6773       break;
6774     case Intrinsic::x86_sse_comigt_ss:
6775     case Intrinsic::x86_sse2_comigt_sd:
6776       Opc = X86ISD::COMI;
6777       CC = ISD::SETGT;
6778       break;
6779     case Intrinsic::x86_sse_comige_ss:
6780     case Intrinsic::x86_sse2_comige_sd:
6781       Opc = X86ISD::COMI;
6782       CC = ISD::SETGE;
6783       break;
6784     case Intrinsic::x86_sse_comineq_ss:
6785     case Intrinsic::x86_sse2_comineq_sd:
6786       Opc = X86ISD::COMI;
6787       CC = ISD::SETNE;
6788       break;
6789     case Intrinsic::x86_sse_ucomieq_ss:
6790     case Intrinsic::x86_sse2_ucomieq_sd:
6791       Opc = X86ISD::UCOMI;
6792       CC = ISD::SETEQ;
6793       break;
6794     case Intrinsic::x86_sse_ucomilt_ss:
6795     case Intrinsic::x86_sse2_ucomilt_sd:
6796       Opc = X86ISD::UCOMI;
6797       CC = ISD::SETLT;
6798       break;
6799     case Intrinsic::x86_sse_ucomile_ss:
6800     case Intrinsic::x86_sse2_ucomile_sd:
6801       Opc = X86ISD::UCOMI;
6802       CC = ISD::SETLE;
6803       break;
6804     case Intrinsic::x86_sse_ucomigt_ss:
6805     case Intrinsic::x86_sse2_ucomigt_sd:
6806       Opc = X86ISD::UCOMI;
6807       CC = ISD::SETGT;
6808       break;
6809     case Intrinsic::x86_sse_ucomige_ss:
6810     case Intrinsic::x86_sse2_ucomige_sd:
6811       Opc = X86ISD::UCOMI;
6812       CC = ISD::SETGE;
6813       break;
6814     case Intrinsic::x86_sse_ucomineq_ss:
6815     case Intrinsic::x86_sse2_ucomineq_sd:
6816       Opc = X86ISD::UCOMI;
6817       CC = ISD::SETNE;
6818       break;
6819     }
6820
6821     SDValue LHS = Op.getOperand(1);
6822     SDValue RHS = Op.getOperand(2);
6823     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6824     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6825     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6826     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6827                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6828     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6829   }
6830   // ptest intrinsics. The intrinsic these come from are designed to return
6831   // an integer value, not just an instruction so lower it to the ptest
6832   // pattern and a setcc for the result.
6833   case Intrinsic::x86_sse41_ptestz:
6834   case Intrinsic::x86_sse41_ptestc:
6835   case Intrinsic::x86_sse41_ptestnzc:{
6836     unsigned X86CC = 0;
6837     switch (IntNo) {
6838     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6839     case Intrinsic::x86_sse41_ptestz:
6840       // ZF = 1
6841       X86CC = X86::COND_E;
6842       break;
6843     case Intrinsic::x86_sse41_ptestc:
6844       // CF = 1
6845       X86CC = X86::COND_B;
6846       break;
6847     case Intrinsic::x86_sse41_ptestnzc:
6848       // ZF and CF = 0
6849       X86CC = X86::COND_A;
6850       break;
6851     }
6852
6853     SDValue LHS = Op.getOperand(1);
6854     SDValue RHS = Op.getOperand(2);
6855     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6856     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6857     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6858     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6859   }
6860
6861   // Fix vector shift instructions where the last operand is a non-immediate
6862   // i32 value.
6863   case Intrinsic::x86_sse2_pslli_w:
6864   case Intrinsic::x86_sse2_pslli_d:
6865   case Intrinsic::x86_sse2_pslli_q:
6866   case Intrinsic::x86_sse2_psrli_w:
6867   case Intrinsic::x86_sse2_psrli_d:
6868   case Intrinsic::x86_sse2_psrli_q:
6869   case Intrinsic::x86_sse2_psrai_w:
6870   case Intrinsic::x86_sse2_psrai_d:
6871   case Intrinsic::x86_mmx_pslli_w:
6872   case Intrinsic::x86_mmx_pslli_d:
6873   case Intrinsic::x86_mmx_pslli_q:
6874   case Intrinsic::x86_mmx_psrli_w:
6875   case Intrinsic::x86_mmx_psrli_d:
6876   case Intrinsic::x86_mmx_psrli_q:
6877   case Intrinsic::x86_mmx_psrai_w:
6878   case Intrinsic::x86_mmx_psrai_d: {
6879     SDValue ShAmt = Op.getOperand(2);
6880     if (isa<ConstantSDNode>(ShAmt))
6881       return SDValue();
6882
6883     unsigned NewIntNo = 0;
6884     EVT ShAmtVT = MVT::v4i32;
6885     switch (IntNo) {
6886     case Intrinsic::x86_sse2_pslli_w:
6887       NewIntNo = Intrinsic::x86_sse2_psll_w;
6888       break;
6889     case Intrinsic::x86_sse2_pslli_d:
6890       NewIntNo = Intrinsic::x86_sse2_psll_d;
6891       break;
6892     case Intrinsic::x86_sse2_pslli_q:
6893       NewIntNo = Intrinsic::x86_sse2_psll_q;
6894       break;
6895     case Intrinsic::x86_sse2_psrli_w:
6896       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6897       break;
6898     case Intrinsic::x86_sse2_psrli_d:
6899       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6900       break;
6901     case Intrinsic::x86_sse2_psrli_q:
6902       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6903       break;
6904     case Intrinsic::x86_sse2_psrai_w:
6905       NewIntNo = Intrinsic::x86_sse2_psra_w;
6906       break;
6907     case Intrinsic::x86_sse2_psrai_d:
6908       NewIntNo = Intrinsic::x86_sse2_psra_d;
6909       break;
6910     default: {
6911       ShAmtVT = MVT::v2i32;
6912       switch (IntNo) {
6913       case Intrinsic::x86_mmx_pslli_w:
6914         NewIntNo = Intrinsic::x86_mmx_psll_w;
6915         break;
6916       case Intrinsic::x86_mmx_pslli_d:
6917         NewIntNo = Intrinsic::x86_mmx_psll_d;
6918         break;
6919       case Intrinsic::x86_mmx_pslli_q:
6920         NewIntNo = Intrinsic::x86_mmx_psll_q;
6921         break;
6922       case Intrinsic::x86_mmx_psrli_w:
6923         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6924         break;
6925       case Intrinsic::x86_mmx_psrli_d:
6926         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6927         break;
6928       case Intrinsic::x86_mmx_psrli_q:
6929         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6930         break;
6931       case Intrinsic::x86_mmx_psrai_w:
6932         NewIntNo = Intrinsic::x86_mmx_psra_w;
6933         break;
6934       case Intrinsic::x86_mmx_psrai_d:
6935         NewIntNo = Intrinsic::x86_mmx_psra_d;
6936         break;
6937       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6938       }
6939       break;
6940     }
6941     }
6942
6943     // The vector shift intrinsics with scalars uses 32b shift amounts but
6944     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6945     // to be zero.
6946     SDValue ShOps[4];
6947     ShOps[0] = ShAmt;
6948     ShOps[1] = DAG.getConstant(0, MVT::i32);
6949     if (ShAmtVT == MVT::v4i32) {
6950       ShOps[2] = DAG.getUNDEF(MVT::i32);
6951       ShOps[3] = DAG.getUNDEF(MVT::i32);
6952       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6953     } else {
6954       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6955     }
6956
6957     EVT VT = Op.getValueType();
6958     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6959     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6960                        DAG.getConstant(NewIntNo, MVT::i32),
6961                        Op.getOperand(1), ShAmt);
6962   }
6963   }
6964 }
6965
6966 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
6967                                            SelectionDAG &DAG) const {
6968   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6969   DebugLoc dl = Op.getDebugLoc();
6970
6971   if (Depth > 0) {
6972     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6973     SDValue Offset =
6974       DAG.getConstant(TD->getPointerSize(),
6975                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6976     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6977                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6978                                    FrameAddr, Offset),
6979                        NULL, 0, false, false, 0);
6980   }
6981
6982   // Just load the return address.
6983   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6984   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6985                      RetAddrFI, NULL, 0, false, false, 0);
6986 }
6987
6988 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6989   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6990   MFI->setFrameAddressIsTaken(true);
6991   EVT VT = Op.getValueType();
6992   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6993   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6994   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6995   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6996   while (Depth--)
6997     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
6998                             false, false, 0);
6999   return FrameAddr;
7000 }
7001
7002 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7003                                                      SelectionDAG &DAG) const {
7004   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7005 }
7006
7007 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7008   MachineFunction &MF = DAG.getMachineFunction();
7009   SDValue Chain     = Op.getOperand(0);
7010   SDValue Offset    = Op.getOperand(1);
7011   SDValue Handler   = Op.getOperand(2);
7012   DebugLoc dl       = Op.getDebugLoc();
7013
7014   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7015                                   getPointerTy());
7016   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7017
7018   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7019                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7020   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7021   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7022   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7023   MF.getRegInfo().addLiveOut(StoreAddrReg);
7024
7025   return DAG.getNode(X86ISD::EH_RETURN, dl,
7026                      MVT::Other,
7027                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7028 }
7029
7030 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7031                                              SelectionDAG &DAG) const {
7032   SDValue Root = Op.getOperand(0);
7033   SDValue Trmp = Op.getOperand(1); // trampoline
7034   SDValue FPtr = Op.getOperand(2); // nested function
7035   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7036   DebugLoc dl  = Op.getDebugLoc();
7037
7038   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7039
7040   if (Subtarget->is64Bit()) {
7041     SDValue OutChains[6];
7042
7043     // Large code-model.
7044     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7045     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7046
7047     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7048     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7049
7050     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7051
7052     // Load the pointer to the nested function into R11.
7053     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7054     SDValue Addr = Trmp;
7055     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7056                                 Addr, TrmpAddr, 0, false, false, 0);
7057
7058     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7059                        DAG.getConstant(2, MVT::i64));
7060     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7061                                 false, false, 2);
7062
7063     // Load the 'nest' parameter value into R10.
7064     // R10 is specified in X86CallingConv.td
7065     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7066     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7067                        DAG.getConstant(10, MVT::i64));
7068     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7069                                 Addr, TrmpAddr, 10, false, false, 0);
7070
7071     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7072                        DAG.getConstant(12, MVT::i64));
7073     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7074                                 false, false, 2);
7075
7076     // Jump to the nested function.
7077     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7078     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7079                        DAG.getConstant(20, MVT::i64));
7080     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7081                                 Addr, TrmpAddr, 20, false, false, 0);
7082
7083     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7084     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7085                        DAG.getConstant(22, MVT::i64));
7086     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7087                                 TrmpAddr, 22, false, false, 0);
7088
7089     SDValue Ops[] =
7090       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7091     return DAG.getMergeValues(Ops, 2, dl);
7092   } else {
7093     const Function *Func =
7094       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7095     CallingConv::ID CC = Func->getCallingConv();
7096     unsigned NestReg;
7097
7098     switch (CC) {
7099     default:
7100       llvm_unreachable("Unsupported calling convention");
7101     case CallingConv::C:
7102     case CallingConv::X86_StdCall: {
7103       // Pass 'nest' parameter in ECX.
7104       // Must be kept in sync with X86CallingConv.td
7105       NestReg = X86::ECX;
7106
7107       // Check that ECX wasn't needed by an 'inreg' parameter.
7108       const FunctionType *FTy = Func->getFunctionType();
7109       const AttrListPtr &Attrs = Func->getAttributes();
7110
7111       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7112         unsigned InRegCount = 0;
7113         unsigned Idx = 1;
7114
7115         for (FunctionType::param_iterator I = FTy->param_begin(),
7116              E = FTy->param_end(); I != E; ++I, ++Idx)
7117           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7118             // FIXME: should only count parameters that are lowered to integers.
7119             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7120
7121         if (InRegCount > 2) {
7122           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7123         }
7124       }
7125       break;
7126     }
7127     case CallingConv::X86_FastCall:
7128     case CallingConv::X86_ThisCall:
7129     case CallingConv::Fast:
7130       // Pass 'nest' parameter in EAX.
7131       // Must be kept in sync with X86CallingConv.td
7132       NestReg = X86::EAX;
7133       break;
7134     }
7135
7136     SDValue OutChains[4];
7137     SDValue Addr, Disp;
7138
7139     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7140                        DAG.getConstant(10, MVT::i32));
7141     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7142
7143     // This is storing the opcode for MOV32ri.
7144     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7145     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7146     OutChains[0] = DAG.getStore(Root, dl,
7147                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7148                                 Trmp, TrmpAddr, 0, false, false, 0);
7149
7150     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7151                        DAG.getConstant(1, MVT::i32));
7152     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7153                                 false, false, 1);
7154
7155     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7156     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7157                        DAG.getConstant(5, MVT::i32));
7158     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7159                                 TrmpAddr, 5, false, false, 1);
7160
7161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7162                        DAG.getConstant(6, MVT::i32));
7163     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7164                                 false, false, 1);
7165
7166     SDValue Ops[] =
7167       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7168     return DAG.getMergeValues(Ops, 2, dl);
7169   }
7170 }
7171
7172 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7173                                             SelectionDAG &DAG) const {
7174   /*
7175    The rounding mode is in bits 11:10 of FPSR, and has the following
7176    settings:
7177      00 Round to nearest
7178      01 Round to -inf
7179      10 Round to +inf
7180      11 Round to 0
7181
7182   FLT_ROUNDS, on the other hand, expects the following:
7183     -1 Undefined
7184      0 Round to 0
7185      1 Round to nearest
7186      2 Round to +inf
7187      3 Round to -inf
7188
7189   To perform the conversion, we do:
7190     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7191   */
7192
7193   MachineFunction &MF = DAG.getMachineFunction();
7194   const TargetMachine &TM = MF.getTarget();
7195   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7196   unsigned StackAlignment = TFI.getStackAlignment();
7197   EVT VT = Op.getValueType();
7198   DebugLoc dl = Op.getDebugLoc();
7199
7200   // Save FP Control Word to stack slot
7201   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7202   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7203
7204   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7205                               DAG.getEntryNode(), StackSlot);
7206
7207   // Load FP Control Word from stack slot
7208   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7209                             false, false, 0);
7210
7211   // Transform as necessary
7212   SDValue CWD1 =
7213     DAG.getNode(ISD::SRL, dl, MVT::i16,
7214                 DAG.getNode(ISD::AND, dl, MVT::i16,
7215                             CWD, DAG.getConstant(0x800, MVT::i16)),
7216                 DAG.getConstant(11, MVT::i8));
7217   SDValue CWD2 =
7218     DAG.getNode(ISD::SRL, dl, MVT::i16,
7219                 DAG.getNode(ISD::AND, dl, MVT::i16,
7220                             CWD, DAG.getConstant(0x400, MVT::i16)),
7221                 DAG.getConstant(9, MVT::i8));
7222
7223   SDValue RetVal =
7224     DAG.getNode(ISD::AND, dl, MVT::i16,
7225                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7226                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7227                             DAG.getConstant(1, MVT::i16)),
7228                 DAG.getConstant(3, MVT::i16));
7229
7230
7231   return DAG.getNode((VT.getSizeInBits() < 16 ?
7232                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7233 }
7234
7235 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7236   EVT VT = Op.getValueType();
7237   EVT OpVT = VT;
7238   unsigned NumBits = VT.getSizeInBits();
7239   DebugLoc dl = Op.getDebugLoc();
7240
7241   Op = Op.getOperand(0);
7242   if (VT == MVT::i8) {
7243     // Zero extend to i32 since there is not an i8 bsr.
7244     OpVT = MVT::i32;
7245     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7246   }
7247
7248   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7249   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7250   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7251
7252   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7253   SDValue Ops[] = {
7254     Op,
7255     DAG.getConstant(NumBits+NumBits-1, OpVT),
7256     DAG.getConstant(X86::COND_E, MVT::i8),
7257     Op.getValue(1)
7258   };
7259   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7260
7261   // Finally xor with NumBits-1.
7262   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7263
7264   if (VT == MVT::i8)
7265     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7266   return Op;
7267 }
7268
7269 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7270   EVT VT = Op.getValueType();
7271   EVT OpVT = VT;
7272   unsigned NumBits = VT.getSizeInBits();
7273   DebugLoc dl = Op.getDebugLoc();
7274
7275   Op = Op.getOperand(0);
7276   if (VT == MVT::i8) {
7277     OpVT = MVT::i32;
7278     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7279   }
7280
7281   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7282   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7283   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7284
7285   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7286   SDValue Ops[] = {
7287     Op,
7288     DAG.getConstant(NumBits, OpVT),
7289     DAG.getConstant(X86::COND_E, MVT::i8),
7290     Op.getValue(1)
7291   };
7292   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7293
7294   if (VT == MVT::i8)
7295     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7296   return Op;
7297 }
7298
7299 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7300   EVT VT = Op.getValueType();
7301   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7302   DebugLoc dl = Op.getDebugLoc();
7303
7304   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7305   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7306   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7307   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7308   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7309   //
7310   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7311   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7312   //  return AloBlo + AloBhi + AhiBlo;
7313
7314   SDValue A = Op.getOperand(0);
7315   SDValue B = Op.getOperand(1);
7316
7317   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7318                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7319                        A, DAG.getConstant(32, MVT::i32));
7320   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7321                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7322                        B, DAG.getConstant(32, MVT::i32));
7323   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7324                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7325                        A, B);
7326   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7327                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7328                        A, Bhi);
7329   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7330                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7331                        Ahi, B);
7332   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7333                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7334                        AloBhi, DAG.getConstant(32, MVT::i32));
7335   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7336                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7337                        AhiBlo, DAG.getConstant(32, MVT::i32));
7338   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7339   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7340   return Res;
7341 }
7342
7343
7344 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7345   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7346   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7347   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7348   // has only one use.
7349   SDNode *N = Op.getNode();
7350   SDValue LHS = N->getOperand(0);
7351   SDValue RHS = N->getOperand(1);
7352   unsigned BaseOp = 0;
7353   unsigned Cond = 0;
7354   DebugLoc dl = Op.getDebugLoc();
7355
7356   switch (Op.getOpcode()) {
7357   default: llvm_unreachable("Unknown ovf instruction!");
7358   case ISD::SADDO:
7359     // A subtract of one will be selected as a INC. Note that INC doesn't
7360     // set CF, so we can't do this for UADDO.
7361     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7362       if (C->getAPIntValue() == 1) {
7363         BaseOp = X86ISD::INC;
7364         Cond = X86::COND_O;
7365         break;
7366       }
7367     BaseOp = X86ISD::ADD;
7368     Cond = X86::COND_O;
7369     break;
7370   case ISD::UADDO:
7371     BaseOp = X86ISD::ADD;
7372     Cond = X86::COND_B;
7373     break;
7374   case ISD::SSUBO:
7375     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7376     // set CF, so we can't do this for USUBO.
7377     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7378       if (C->getAPIntValue() == 1) {
7379         BaseOp = X86ISD::DEC;
7380         Cond = X86::COND_O;
7381         break;
7382       }
7383     BaseOp = X86ISD::SUB;
7384     Cond = X86::COND_O;
7385     break;
7386   case ISD::USUBO:
7387     BaseOp = X86ISD::SUB;
7388     Cond = X86::COND_B;
7389     break;
7390   case ISD::SMULO:
7391     BaseOp = X86ISD::SMUL;
7392     Cond = X86::COND_O;
7393     break;
7394   case ISD::UMULO:
7395     BaseOp = X86ISD::UMUL;
7396     Cond = X86::COND_B;
7397     break;
7398   }
7399
7400   // Also sets EFLAGS.
7401   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7402   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7403
7404   SDValue SetCC =
7405     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7406                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7407
7408   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7409   return Sum;
7410 }
7411
7412 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7413   EVT T = Op.getValueType();
7414   DebugLoc dl = Op.getDebugLoc();
7415   unsigned Reg = 0;
7416   unsigned size = 0;
7417   switch(T.getSimpleVT().SimpleTy) {
7418   default:
7419     assert(false && "Invalid value type!");
7420   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7421   case MVT::i16: Reg = X86::AX;  size = 2; break;
7422   case MVT::i32: Reg = X86::EAX; size = 4; break;
7423   case MVT::i64:
7424     assert(Subtarget->is64Bit() && "Node not type legal!");
7425     Reg = X86::RAX; size = 8;
7426     break;
7427   }
7428   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7429                                     Op.getOperand(2), SDValue());
7430   SDValue Ops[] = { cpIn.getValue(0),
7431                     Op.getOperand(1),
7432                     Op.getOperand(3),
7433                     DAG.getTargetConstant(size, MVT::i8),
7434                     cpIn.getValue(1) };
7435   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7436   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7437   SDValue cpOut =
7438     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7439   return cpOut;
7440 }
7441
7442 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7443                                                  SelectionDAG &DAG) const {
7444   assert(Subtarget->is64Bit() && "Result not type legalized?");
7445   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7446   SDValue TheChain = Op.getOperand(0);
7447   DebugLoc dl = Op.getDebugLoc();
7448   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7449   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7450   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7451                                    rax.getValue(2));
7452   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7453                             DAG.getConstant(32, MVT::i8));
7454   SDValue Ops[] = {
7455     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7456     rdx.getValue(1)
7457   };
7458   return DAG.getMergeValues(Ops, 2, dl);
7459 }
7460
7461 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7462   SDNode *Node = Op.getNode();
7463   DebugLoc dl = Node->getDebugLoc();
7464   EVT T = Node->getValueType(0);
7465   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7466                               DAG.getConstant(0, T), Node->getOperand(2));
7467   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7468                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7469                        Node->getOperand(0),
7470                        Node->getOperand(1), negOp,
7471                        cast<AtomicSDNode>(Node)->getSrcValue(),
7472                        cast<AtomicSDNode>(Node)->getAlignment());
7473 }
7474
7475 /// LowerOperation - Provide custom lowering hooks for some operations.
7476 ///
7477 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7478   switch (Op.getOpcode()) {
7479   default: llvm_unreachable("Should not custom lower this!");
7480   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7481   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7482   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7483   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7484   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7485   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7486   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7487   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7488   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7489   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7490   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7491   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7492   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7493   case ISD::SHL_PARTS:
7494   case ISD::SRA_PARTS:
7495   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7496   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7497   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7498   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7499   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7500   case ISD::FABS:               return LowerFABS(Op, DAG);
7501   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7502   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7503   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7504   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7505   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7506   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7507   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7508   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7509   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7510   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7511   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7512   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7513   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7514   case ISD::FRAME_TO_ARGS_OFFSET:
7515                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7516   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7517   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7518   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7519   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7520   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7521   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7522   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7523   case ISD::SADDO:
7524   case ISD::UADDO:
7525   case ISD::SSUBO:
7526   case ISD::USUBO:
7527   case ISD::SMULO:
7528   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7529   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7530   }
7531 }
7532
7533 void X86TargetLowering::
7534 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7535                         SelectionDAG &DAG, unsigned NewOp) const {
7536   EVT T = Node->getValueType(0);
7537   DebugLoc dl = Node->getDebugLoc();
7538   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7539
7540   SDValue Chain = Node->getOperand(0);
7541   SDValue In1 = Node->getOperand(1);
7542   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7543                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7544   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7545                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7546   SDValue Ops[] = { Chain, In1, In2L, In2H };
7547   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7548   SDValue Result =
7549     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7550                             cast<MemSDNode>(Node)->getMemOperand());
7551   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7552   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7553   Results.push_back(Result.getValue(2));
7554 }
7555
7556 /// ReplaceNodeResults - Replace a node with an illegal result type
7557 /// with a new node built out of custom code.
7558 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7559                                            SmallVectorImpl<SDValue>&Results,
7560                                            SelectionDAG &DAG) const {
7561   DebugLoc dl = N->getDebugLoc();
7562   switch (N->getOpcode()) {
7563   default:
7564     assert(false && "Do not know how to custom type legalize this operation!");
7565     return;
7566   case ISD::FP_TO_SINT: {
7567     std::pair<SDValue,SDValue> Vals =
7568         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7569     SDValue FIST = Vals.first, StackSlot = Vals.second;
7570     if (FIST.getNode() != 0) {
7571       EVT VT = N->getValueType(0);
7572       // Return a load from the stack slot.
7573       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7574                                     false, false, 0));
7575     }
7576     return;
7577   }
7578   case ISD::READCYCLECOUNTER: {
7579     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7580     SDValue TheChain = N->getOperand(0);
7581     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7582     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7583                                      rd.getValue(1));
7584     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7585                                      eax.getValue(2));
7586     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7587     SDValue Ops[] = { eax, edx };
7588     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7589     Results.push_back(edx.getValue(1));
7590     return;
7591   }
7592   case ISD::ATOMIC_CMP_SWAP: {
7593     EVT T = N->getValueType(0);
7594     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7595     SDValue cpInL, cpInH;
7596     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7597                         DAG.getConstant(0, MVT::i32));
7598     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7599                         DAG.getConstant(1, MVT::i32));
7600     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7601     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7602                              cpInL.getValue(1));
7603     SDValue swapInL, swapInH;
7604     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7605                           DAG.getConstant(0, MVT::i32));
7606     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7607                           DAG.getConstant(1, MVT::i32));
7608     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7609                                cpInH.getValue(1));
7610     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7611                                swapInL.getValue(1));
7612     SDValue Ops[] = { swapInH.getValue(0),
7613                       N->getOperand(1),
7614                       swapInH.getValue(1) };
7615     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7616     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7617     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7618                                         MVT::i32, Result.getValue(1));
7619     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7620                                         MVT::i32, cpOutL.getValue(2));
7621     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7622     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7623     Results.push_back(cpOutH.getValue(1));
7624     return;
7625   }
7626   case ISD::ATOMIC_LOAD_ADD:
7627     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7628     return;
7629   case ISD::ATOMIC_LOAD_AND:
7630     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7631     return;
7632   case ISD::ATOMIC_LOAD_NAND:
7633     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7634     return;
7635   case ISD::ATOMIC_LOAD_OR:
7636     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7637     return;
7638   case ISD::ATOMIC_LOAD_SUB:
7639     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7640     return;
7641   case ISD::ATOMIC_LOAD_XOR:
7642     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7643     return;
7644   case ISD::ATOMIC_SWAP:
7645     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7646     return;
7647   }
7648 }
7649
7650 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7651   switch (Opcode) {
7652   default: return NULL;
7653   case X86ISD::BSF:                return "X86ISD::BSF";
7654   case X86ISD::BSR:                return "X86ISD::BSR";
7655   case X86ISD::SHLD:               return "X86ISD::SHLD";
7656   case X86ISD::SHRD:               return "X86ISD::SHRD";
7657   case X86ISD::FAND:               return "X86ISD::FAND";
7658   case X86ISD::FOR:                return "X86ISD::FOR";
7659   case X86ISD::FXOR:               return "X86ISD::FXOR";
7660   case X86ISD::FSRL:               return "X86ISD::FSRL";
7661   case X86ISD::FILD:               return "X86ISD::FILD";
7662   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7663   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7664   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7665   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7666   case X86ISD::FLD:                return "X86ISD::FLD";
7667   case X86ISD::FST:                return "X86ISD::FST";
7668   case X86ISD::CALL:               return "X86ISD::CALL";
7669   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7670   case X86ISD::BT:                 return "X86ISD::BT";
7671   case X86ISD::CMP:                return "X86ISD::CMP";
7672   case X86ISD::COMI:               return "X86ISD::COMI";
7673   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7674   case X86ISD::SETCC:              return "X86ISD::SETCC";
7675   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7676   case X86ISD::CMOV:               return "X86ISD::CMOV";
7677   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7678   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7679   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7680   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7681   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7682   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7683   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7684   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7685   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7686   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7687   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7688   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7689   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7690   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7691   case X86ISD::FMAX:               return "X86ISD::FMAX";
7692   case X86ISD::FMIN:               return "X86ISD::FMIN";
7693   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7694   case X86ISD::FRCP:               return "X86ISD::FRCP";
7695   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7696   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7697   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7698   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7699   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7700   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7701   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7702   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7703   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7704   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7705   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7706   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7707   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7708   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7709   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7710   case X86ISD::VSHL:               return "X86ISD::VSHL";
7711   case X86ISD::VSRL:               return "X86ISD::VSRL";
7712   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7713   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7714   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7715   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7716   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7717   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7718   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7719   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7720   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7721   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7722   case X86ISD::ADD:                return "X86ISD::ADD";
7723   case X86ISD::SUB:                return "X86ISD::SUB";
7724   case X86ISD::SMUL:               return "X86ISD::SMUL";
7725   case X86ISD::UMUL:               return "X86ISD::UMUL";
7726   case X86ISD::INC:                return "X86ISD::INC";
7727   case X86ISD::DEC:                return "X86ISD::DEC";
7728   case X86ISD::OR:                 return "X86ISD::OR";
7729   case X86ISD::XOR:                return "X86ISD::XOR";
7730   case X86ISD::AND:                return "X86ISD::AND";
7731   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7732   case X86ISD::PTEST:              return "X86ISD::PTEST";
7733   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7734   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7735   }
7736 }
7737
7738 // isLegalAddressingMode - Return true if the addressing mode represented
7739 // by AM is legal for this target, for a load/store of the specified type.
7740 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7741                                               const Type *Ty) const {
7742   // X86 supports extremely general addressing modes.
7743   CodeModel::Model M = getTargetMachine().getCodeModel();
7744
7745   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7746   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7747     return false;
7748
7749   if (AM.BaseGV) {
7750     unsigned GVFlags =
7751       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7752
7753     // If a reference to this global requires an extra load, we can't fold it.
7754     if (isGlobalStubReference(GVFlags))
7755       return false;
7756
7757     // If BaseGV requires a register for the PIC base, we cannot also have a
7758     // BaseReg specified.
7759     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7760       return false;
7761
7762     // If lower 4G is not available, then we must use rip-relative addressing.
7763     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7764       return false;
7765   }
7766
7767   switch (AM.Scale) {
7768   case 0:
7769   case 1:
7770   case 2:
7771   case 4:
7772   case 8:
7773     // These scales always work.
7774     break;
7775   case 3:
7776   case 5:
7777   case 9:
7778     // These scales are formed with basereg+scalereg.  Only accept if there is
7779     // no basereg yet.
7780     if (AM.HasBaseReg)
7781       return false;
7782     break;
7783   default:  // Other stuff never works.
7784     return false;
7785   }
7786
7787   return true;
7788 }
7789
7790
7791 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7792   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7793     return false;
7794   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7795   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7796   if (NumBits1 <= NumBits2)
7797     return false;
7798   return true;
7799 }
7800
7801 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7802   if (!VT1.isInteger() || !VT2.isInteger())
7803     return false;
7804   unsigned NumBits1 = VT1.getSizeInBits();
7805   unsigned NumBits2 = VT2.getSizeInBits();
7806   if (NumBits1 <= NumBits2)
7807     return false;
7808   return true;
7809 }
7810
7811 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7812   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7813   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7814 }
7815
7816 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7817   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7818   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7819 }
7820
7821 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7822   // i16 instructions are longer (0x66 prefix) and potentially slower.
7823   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7824 }
7825
7826 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7827 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7828 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7829 /// are assumed to be legal.
7830 bool
7831 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7832                                       EVT VT) const {
7833   // Very little shuffling can be done for 64-bit vectors right now.
7834   if (VT.getSizeInBits() == 64)
7835     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7836
7837   // FIXME: pshufb, blends, shifts.
7838   return (VT.getVectorNumElements() == 2 ||
7839           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7840           isMOVLMask(M, VT) ||
7841           isSHUFPMask(M, VT) ||
7842           isPSHUFDMask(M, VT) ||
7843           isPSHUFHWMask(M, VT) ||
7844           isPSHUFLWMask(M, VT) ||
7845           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7846           isUNPCKLMask(M, VT) ||
7847           isUNPCKHMask(M, VT) ||
7848           isUNPCKL_v_undef_Mask(M, VT) ||
7849           isUNPCKH_v_undef_Mask(M, VT));
7850 }
7851
7852 bool
7853 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7854                                           EVT VT) const {
7855   unsigned NumElts = VT.getVectorNumElements();
7856   // FIXME: This collection of masks seems suspect.
7857   if (NumElts == 2)
7858     return true;
7859   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7860     return (isMOVLMask(Mask, VT)  ||
7861             isCommutedMOVLMask(Mask, VT, true) ||
7862             isSHUFPMask(Mask, VT) ||
7863             isCommutedSHUFPMask(Mask, VT));
7864   }
7865   return false;
7866 }
7867
7868 //===----------------------------------------------------------------------===//
7869 //                           X86 Scheduler Hooks
7870 //===----------------------------------------------------------------------===//
7871
7872 // private utility function
7873 MachineBasicBlock *
7874 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7875                                                        MachineBasicBlock *MBB,
7876                                                        unsigned regOpc,
7877                                                        unsigned immOpc,
7878                                                        unsigned LoadOpc,
7879                                                        unsigned CXchgOpc,
7880                                                        unsigned copyOpc,
7881                                                        unsigned notOpc,
7882                                                        unsigned EAXreg,
7883                                                        TargetRegisterClass *RC,
7884                                                        bool invSrc) const {
7885   // For the atomic bitwise operator, we generate
7886   //   thisMBB:
7887   //   newMBB:
7888   //     ld  t1 = [bitinstr.addr]
7889   //     op  t2 = t1, [bitinstr.val]
7890   //     mov EAX = t1
7891   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7892   //     bz  newMBB
7893   //     fallthrough -->nextMBB
7894   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7895   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7896   MachineFunction::iterator MBBIter = MBB;
7897   ++MBBIter;
7898
7899   /// First build the CFG
7900   MachineFunction *F = MBB->getParent();
7901   MachineBasicBlock *thisMBB = MBB;
7902   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7903   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7904   F->insert(MBBIter, newMBB);
7905   F->insert(MBBIter, nextMBB);
7906
7907   // Move all successors to thisMBB to nextMBB
7908   nextMBB->transferSuccessors(thisMBB);
7909
7910   // Update thisMBB to fall through to newMBB
7911   thisMBB->addSuccessor(newMBB);
7912
7913   // newMBB jumps to itself and fall through to nextMBB
7914   newMBB->addSuccessor(nextMBB);
7915   newMBB->addSuccessor(newMBB);
7916
7917   // Insert instructions into newMBB based on incoming instruction
7918   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7919          "unexpected number of operands");
7920   DebugLoc dl = bInstr->getDebugLoc();
7921   MachineOperand& destOper = bInstr->getOperand(0);
7922   MachineOperand* argOpers[2 + X86AddrNumOperands];
7923   int numArgs = bInstr->getNumOperands() - 1;
7924   for (int i=0; i < numArgs; ++i)
7925     argOpers[i] = &bInstr->getOperand(i+1);
7926
7927   // x86 address has 4 operands: base, index, scale, and displacement
7928   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7929   int valArgIndx = lastAddrIndx + 1;
7930
7931   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7932   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7933   for (int i=0; i <= lastAddrIndx; ++i)
7934     (*MIB).addOperand(*argOpers[i]);
7935
7936   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7937   if (invSrc) {
7938     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7939   }
7940   else
7941     tt = t1;
7942
7943   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7944   assert((argOpers[valArgIndx]->isReg() ||
7945           argOpers[valArgIndx]->isImm()) &&
7946          "invalid operand");
7947   if (argOpers[valArgIndx]->isReg())
7948     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7949   else
7950     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7951   MIB.addReg(tt);
7952   (*MIB).addOperand(*argOpers[valArgIndx]);
7953
7954   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7955   MIB.addReg(t1);
7956
7957   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7958   for (int i=0; i <= lastAddrIndx; ++i)
7959     (*MIB).addOperand(*argOpers[i]);
7960   MIB.addReg(t2);
7961   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7962   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7963                     bInstr->memoperands_end());
7964
7965   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7966   MIB.addReg(EAXreg);
7967
7968   // insert branch
7969   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
7970
7971   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7972   return nextMBB;
7973 }
7974
7975 // private utility function:  64 bit atomics on 32 bit host.
7976 MachineBasicBlock *
7977 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7978                                                        MachineBasicBlock *MBB,
7979                                                        unsigned regOpcL,
7980                                                        unsigned regOpcH,
7981                                                        unsigned immOpcL,
7982                                                        unsigned immOpcH,
7983                                                        bool invSrc) const {
7984   // For the atomic bitwise operator, we generate
7985   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7986   //     ld t1,t2 = [bitinstr.addr]
7987   //   newMBB:
7988   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7989   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7990   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7991   //     mov ECX, EBX <- t5, t6
7992   //     mov EAX, EDX <- t1, t2
7993   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7994   //     mov t3, t4 <- EAX, EDX
7995   //     bz  newMBB
7996   //     result in out1, out2
7997   //     fallthrough -->nextMBB
7998
7999   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8000   const unsigned LoadOpc = X86::MOV32rm;
8001   const unsigned copyOpc = X86::MOV32rr;
8002   const unsigned NotOpc = X86::NOT32r;
8003   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8004   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8005   MachineFunction::iterator MBBIter = MBB;
8006   ++MBBIter;
8007
8008   /// First build the CFG
8009   MachineFunction *F = MBB->getParent();
8010   MachineBasicBlock *thisMBB = MBB;
8011   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8012   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8013   F->insert(MBBIter, newMBB);
8014   F->insert(MBBIter, nextMBB);
8015
8016   // Move all successors to thisMBB to nextMBB
8017   nextMBB->transferSuccessors(thisMBB);
8018
8019   // Update thisMBB to fall through to newMBB
8020   thisMBB->addSuccessor(newMBB);
8021
8022   // newMBB jumps to itself and fall through to nextMBB
8023   newMBB->addSuccessor(nextMBB);
8024   newMBB->addSuccessor(newMBB);
8025
8026   DebugLoc dl = bInstr->getDebugLoc();
8027   // Insert instructions into newMBB based on incoming instruction
8028   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8029   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8030          "unexpected number of operands");
8031   MachineOperand& dest1Oper = bInstr->getOperand(0);
8032   MachineOperand& dest2Oper = bInstr->getOperand(1);
8033   MachineOperand* argOpers[2 + X86AddrNumOperands];
8034   for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8035     argOpers[i] = &bInstr->getOperand(i+2);
8036
8037     // We use some of the operands multiple times, so conservatively just
8038     // clear any kill flags that might be present.
8039     if (argOpers[i]->isReg() && argOpers[i]->isUse())
8040       argOpers[i]->setIsKill(false);
8041   }
8042
8043   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8044   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8045
8046   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8047   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8048   for (int i=0; i <= lastAddrIndx; ++i)
8049     (*MIB).addOperand(*argOpers[i]);
8050   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8051   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8052   // add 4 to displacement.
8053   for (int i=0; i <= lastAddrIndx-2; ++i)
8054     (*MIB).addOperand(*argOpers[i]);
8055   MachineOperand newOp3 = *(argOpers[3]);
8056   if (newOp3.isImm())
8057     newOp3.setImm(newOp3.getImm()+4);
8058   else
8059     newOp3.setOffset(newOp3.getOffset()+4);
8060   (*MIB).addOperand(newOp3);
8061   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8062
8063   // t3/4 are defined later, at the bottom of the loop
8064   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8065   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8066   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8067     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8068   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8069     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8070
8071   // The subsequent operations should be using the destination registers of
8072   //the PHI instructions.
8073   if (invSrc) {
8074     t1 = F->getRegInfo().createVirtualRegister(RC);
8075     t2 = F->getRegInfo().createVirtualRegister(RC);
8076     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8077     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8078   } else {
8079     t1 = dest1Oper.getReg();
8080     t2 = dest2Oper.getReg();
8081   }
8082
8083   int valArgIndx = lastAddrIndx + 1;
8084   assert((argOpers[valArgIndx]->isReg() ||
8085           argOpers[valArgIndx]->isImm()) &&
8086          "invalid operand");
8087   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8088   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8089   if (argOpers[valArgIndx]->isReg())
8090     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8091   else
8092     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8093   if (regOpcL != X86::MOV32rr)
8094     MIB.addReg(t1);
8095   (*MIB).addOperand(*argOpers[valArgIndx]);
8096   assert(argOpers[valArgIndx + 1]->isReg() ==
8097          argOpers[valArgIndx]->isReg());
8098   assert(argOpers[valArgIndx + 1]->isImm() ==
8099          argOpers[valArgIndx]->isImm());
8100   if (argOpers[valArgIndx + 1]->isReg())
8101     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8102   else
8103     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8104   if (regOpcH != X86::MOV32rr)
8105     MIB.addReg(t2);
8106   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8107
8108   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8109   MIB.addReg(t1);
8110   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8111   MIB.addReg(t2);
8112
8113   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8114   MIB.addReg(t5);
8115   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8116   MIB.addReg(t6);
8117
8118   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8119   for (int i=0; i <= lastAddrIndx; ++i)
8120     (*MIB).addOperand(*argOpers[i]);
8121
8122   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8123   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8124                     bInstr->memoperands_end());
8125
8126   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8127   MIB.addReg(X86::EAX);
8128   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8129   MIB.addReg(X86::EDX);
8130
8131   // insert branch
8132   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8133
8134   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8135   return nextMBB;
8136 }
8137
8138 // private utility function
8139 MachineBasicBlock *
8140 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8141                                                       MachineBasicBlock *MBB,
8142                                                       unsigned cmovOpc) const {
8143   // For the atomic min/max operator, we generate
8144   //   thisMBB:
8145   //   newMBB:
8146   //     ld t1 = [min/max.addr]
8147   //     mov t2 = [min/max.val]
8148   //     cmp  t1, t2
8149   //     cmov[cond] t2 = t1
8150   //     mov EAX = t1
8151   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8152   //     bz   newMBB
8153   //     fallthrough -->nextMBB
8154   //
8155   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8156   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8157   MachineFunction::iterator MBBIter = MBB;
8158   ++MBBIter;
8159
8160   /// First build the CFG
8161   MachineFunction *F = MBB->getParent();
8162   MachineBasicBlock *thisMBB = MBB;
8163   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8164   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8165   F->insert(MBBIter, newMBB);
8166   F->insert(MBBIter, nextMBB);
8167
8168   // Move all successors of thisMBB to nextMBB
8169   nextMBB->transferSuccessors(thisMBB);
8170
8171   // Update thisMBB to fall through to newMBB
8172   thisMBB->addSuccessor(newMBB);
8173
8174   // newMBB jumps to newMBB and fall through to nextMBB
8175   newMBB->addSuccessor(nextMBB);
8176   newMBB->addSuccessor(newMBB);
8177
8178   DebugLoc dl = mInstr->getDebugLoc();
8179   // Insert instructions into newMBB based on incoming instruction
8180   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8181          "unexpected number of operands");
8182   MachineOperand& destOper = mInstr->getOperand(0);
8183   MachineOperand* argOpers[2 + X86AddrNumOperands];
8184   int numArgs = mInstr->getNumOperands() - 1;
8185   for (int i=0; i < numArgs; ++i)
8186     argOpers[i] = &mInstr->getOperand(i+1);
8187
8188   // x86 address has 4 operands: base, index, scale, and displacement
8189   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8190   int valArgIndx = lastAddrIndx + 1;
8191
8192   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8193   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8194   for (int i=0; i <= lastAddrIndx; ++i)
8195     (*MIB).addOperand(*argOpers[i]);
8196
8197   // We only support register and immediate values
8198   assert((argOpers[valArgIndx]->isReg() ||
8199           argOpers[valArgIndx]->isImm()) &&
8200          "invalid operand");
8201
8202   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8203   if (argOpers[valArgIndx]->isReg())
8204     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8205   else
8206     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8207   (*MIB).addOperand(*argOpers[valArgIndx]);
8208
8209   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8210   MIB.addReg(t1);
8211
8212   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8213   MIB.addReg(t1);
8214   MIB.addReg(t2);
8215
8216   // Generate movc
8217   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8218   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8219   MIB.addReg(t2);
8220   MIB.addReg(t1);
8221
8222   // Cmp and exchange if none has modified the memory location
8223   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8224   for (int i=0; i <= lastAddrIndx; ++i)
8225     (*MIB).addOperand(*argOpers[i]);
8226   MIB.addReg(t3);
8227   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8228   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8229                     mInstr->memoperands_end());
8230
8231   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8232   MIB.addReg(X86::EAX);
8233
8234   // insert branch
8235   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8236
8237   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8238   return nextMBB;
8239 }
8240
8241 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8242 // all of this code can be replaced with that in the .td file.
8243 MachineBasicBlock *
8244 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8245                             unsigned numArgs, bool memArg) const {
8246
8247   MachineFunction *F = BB->getParent();
8248   DebugLoc dl = MI->getDebugLoc();
8249   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8250
8251   unsigned Opc;
8252   if (memArg)
8253     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8254   else
8255     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8256
8257   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8258
8259   for (unsigned i = 0; i < numArgs; ++i) {
8260     MachineOperand &Op = MI->getOperand(i+1);
8261
8262     if (!(Op.isReg() && Op.isImplicit()))
8263       MIB.addOperand(Op);
8264   }
8265
8266   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8267     .addReg(X86::XMM0);
8268
8269   F->DeleteMachineInstr(MI);
8270
8271   return BB;
8272 }
8273
8274 MachineBasicBlock *
8275 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8276                                                  MachineInstr *MI,
8277                                                  MachineBasicBlock *MBB) const {
8278   // Emit code to save XMM registers to the stack. The ABI says that the
8279   // number of registers to save is given in %al, so it's theoretically
8280   // possible to do an indirect jump trick to avoid saving all of them,
8281   // however this code takes a simpler approach and just executes all
8282   // of the stores if %al is non-zero. It's less code, and it's probably
8283   // easier on the hardware branch predictor, and stores aren't all that
8284   // expensive anyway.
8285
8286   // Create the new basic blocks. One block contains all the XMM stores,
8287   // and one block is the final destination regardless of whether any
8288   // stores were performed.
8289   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8290   MachineFunction *F = MBB->getParent();
8291   MachineFunction::iterator MBBIter = MBB;
8292   ++MBBIter;
8293   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8294   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8295   F->insert(MBBIter, XMMSaveMBB);
8296   F->insert(MBBIter, EndMBB);
8297
8298   // Set up the CFG.
8299   // Move any original successors of MBB to the end block.
8300   EndMBB->transferSuccessors(MBB);
8301   // The original block will now fall through to the XMM save block.
8302   MBB->addSuccessor(XMMSaveMBB);
8303   // The XMMSaveMBB will fall through to the end block.
8304   XMMSaveMBB->addSuccessor(EndMBB);
8305
8306   // Now add the instructions.
8307   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8308   DebugLoc DL = MI->getDebugLoc();
8309
8310   unsigned CountReg = MI->getOperand(0).getReg();
8311   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8312   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8313
8314   if (!Subtarget->isTargetWin64()) {
8315     // If %al is 0, branch around the XMM save block.
8316     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8317     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8318     MBB->addSuccessor(EndMBB);
8319   }
8320
8321   // In the XMM save block, save all the XMM argument registers.
8322   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8323     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8324     MachineMemOperand *MMO =
8325       F->getMachineMemOperand(
8326         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8327         MachineMemOperand::MOStore, Offset,
8328         /*Size=*/16, /*Align=*/16);
8329     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8330       .addFrameIndex(RegSaveFrameIndex)
8331       .addImm(/*Scale=*/1)
8332       .addReg(/*IndexReg=*/0)
8333       .addImm(/*Disp=*/Offset)
8334       .addReg(/*Segment=*/0)
8335       .addReg(MI->getOperand(i).getReg())
8336       .addMemOperand(MMO);
8337   }
8338
8339   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8340
8341   return EndMBB;
8342 }
8343
8344 MachineBasicBlock *
8345 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8346                                      MachineBasicBlock *BB) const {
8347   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8348   DebugLoc DL = MI->getDebugLoc();
8349
8350   // To "insert" a SELECT_CC instruction, we actually have to insert the
8351   // diamond control-flow pattern.  The incoming instruction knows the
8352   // destination vreg to set, the condition code register to branch on, the
8353   // true/false values to select between, and a branch opcode to use.
8354   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8355   MachineFunction::iterator It = BB;
8356   ++It;
8357
8358   //  thisMBB:
8359   //  ...
8360   //   TrueVal = ...
8361   //   cmpTY ccX, r1, r2
8362   //   bCC copy1MBB
8363   //   fallthrough --> copy0MBB
8364   MachineBasicBlock *thisMBB = BB;
8365   MachineFunction *F = BB->getParent();
8366   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8367   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8368   unsigned Opc =
8369     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8370   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8371   F->insert(It, copy0MBB);
8372   F->insert(It, sinkMBB);
8373   // Update machine-CFG edges by first adding all successors of the current
8374   // block to the new block which will contain the Phi node for the select.
8375   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8376          E = BB->succ_end(); I != E; ++I)
8377     sinkMBB->addSuccessor(*I);
8378   // Next, remove all successors of the current block, and add the true
8379   // and fallthrough blocks as its successors.
8380   while (!BB->succ_empty())
8381     BB->removeSuccessor(BB->succ_begin());
8382   // Add the true and fallthrough blocks as its successors.
8383   BB->addSuccessor(copy0MBB);
8384   BB->addSuccessor(sinkMBB);
8385
8386   //  copy0MBB:
8387   //   %FalseValue = ...
8388   //   # fallthrough to sinkMBB
8389   copy0MBB->addSuccessor(sinkMBB);
8390
8391   //  sinkMBB:
8392   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8393   //  ...
8394   BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8395     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8396     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8397
8398   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8399   return sinkMBB;
8400 }
8401
8402 MachineBasicBlock *
8403 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8404                                           MachineBasicBlock *BB) const {
8405   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8406   DebugLoc DL = MI->getDebugLoc();
8407   MachineFunction *F = BB->getParent();
8408
8409   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8410   // non-trivial part is impdef of ESP.
8411   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8412   // mingw-w64.
8413
8414   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8415     .addExternalSymbol("_alloca")
8416     .addReg(X86::EAX, RegState::Implicit)
8417     .addReg(X86::ESP, RegState::Implicit)
8418     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8419     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8420
8421   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8422   return BB;
8423 }
8424
8425 MachineBasicBlock *
8426 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8427                                                MachineBasicBlock *BB) const {
8428   switch (MI->getOpcode()) {
8429   default: assert(false && "Unexpected instr type to insert");
8430   case X86::MINGW_ALLOCA:
8431     return EmitLoweredMingwAlloca(MI, BB);
8432   case X86::CMOV_GR8:
8433   case X86::CMOV_V1I64:
8434   case X86::CMOV_FR32:
8435   case X86::CMOV_FR64:
8436   case X86::CMOV_V4F32:
8437   case X86::CMOV_V2F64:
8438   case X86::CMOV_V2I64:
8439   case X86::CMOV_GR16:
8440   case X86::CMOV_GR32:
8441   case X86::CMOV_RFP32:
8442   case X86::CMOV_RFP64:
8443   case X86::CMOV_RFP80:
8444     return EmitLoweredSelect(MI, BB);
8445
8446   case X86::FP32_TO_INT16_IN_MEM:
8447   case X86::FP32_TO_INT32_IN_MEM:
8448   case X86::FP32_TO_INT64_IN_MEM:
8449   case X86::FP64_TO_INT16_IN_MEM:
8450   case X86::FP64_TO_INT32_IN_MEM:
8451   case X86::FP64_TO_INT64_IN_MEM:
8452   case X86::FP80_TO_INT16_IN_MEM:
8453   case X86::FP80_TO_INT32_IN_MEM:
8454   case X86::FP80_TO_INT64_IN_MEM: {
8455     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8456     DebugLoc DL = MI->getDebugLoc();
8457
8458     // Change the floating point control register to use "round towards zero"
8459     // mode when truncating to an integer value.
8460     MachineFunction *F = BB->getParent();
8461     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8462     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8463
8464     // Load the old value of the high byte of the control word...
8465     unsigned OldCW =
8466       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8467     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8468                       CWFrameIdx);
8469
8470     // Set the high part to be round to zero...
8471     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8472       .addImm(0xC7F);
8473
8474     // Reload the modified control word now...
8475     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8476
8477     // Restore the memory image of control word to original value
8478     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8479       .addReg(OldCW);
8480
8481     // Get the X86 opcode to use.
8482     unsigned Opc;
8483     switch (MI->getOpcode()) {
8484     default: llvm_unreachable("illegal opcode!");
8485     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8486     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8487     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8488     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8489     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8490     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8491     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8492     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8493     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8494     }
8495
8496     X86AddressMode AM;
8497     MachineOperand &Op = MI->getOperand(0);
8498     if (Op.isReg()) {
8499       AM.BaseType = X86AddressMode::RegBase;
8500       AM.Base.Reg = Op.getReg();
8501     } else {
8502       AM.BaseType = X86AddressMode::FrameIndexBase;
8503       AM.Base.FrameIndex = Op.getIndex();
8504     }
8505     Op = MI->getOperand(1);
8506     if (Op.isImm())
8507       AM.Scale = Op.getImm();
8508     Op = MI->getOperand(2);
8509     if (Op.isImm())
8510       AM.IndexReg = Op.getImm();
8511     Op = MI->getOperand(3);
8512     if (Op.isGlobal()) {
8513       AM.GV = Op.getGlobal();
8514     } else {
8515       AM.Disp = Op.getImm();
8516     }
8517     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8518                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8519
8520     // Reload the original control word now.
8521     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8522
8523     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8524     return BB;
8525   }
8526     // String/text processing lowering.
8527   case X86::PCMPISTRM128REG:
8528     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8529   case X86::PCMPISTRM128MEM:
8530     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8531   case X86::PCMPESTRM128REG:
8532     return EmitPCMP(MI, BB, 5, false /* in mem */);
8533   case X86::PCMPESTRM128MEM:
8534     return EmitPCMP(MI, BB, 5, true /* in mem */);
8535
8536     // Atomic Lowering.
8537   case X86::ATOMAND32:
8538     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8539                                                X86::AND32ri, X86::MOV32rm,
8540                                                X86::LCMPXCHG32, X86::MOV32rr,
8541                                                X86::NOT32r, X86::EAX,
8542                                                X86::GR32RegisterClass);
8543   case X86::ATOMOR32:
8544     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8545                                                X86::OR32ri, X86::MOV32rm,
8546                                                X86::LCMPXCHG32, X86::MOV32rr,
8547                                                X86::NOT32r, X86::EAX,
8548                                                X86::GR32RegisterClass);
8549   case X86::ATOMXOR32:
8550     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8551                                                X86::XOR32ri, X86::MOV32rm,
8552                                                X86::LCMPXCHG32, X86::MOV32rr,
8553                                                X86::NOT32r, X86::EAX,
8554                                                X86::GR32RegisterClass);
8555   case X86::ATOMNAND32:
8556     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8557                                                X86::AND32ri, X86::MOV32rm,
8558                                                X86::LCMPXCHG32, X86::MOV32rr,
8559                                                X86::NOT32r, X86::EAX,
8560                                                X86::GR32RegisterClass, true);
8561   case X86::ATOMMIN32:
8562     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8563   case X86::ATOMMAX32:
8564     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8565   case X86::ATOMUMIN32:
8566     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8567   case X86::ATOMUMAX32:
8568     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8569
8570   case X86::ATOMAND16:
8571     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8572                                                X86::AND16ri, X86::MOV16rm,
8573                                                X86::LCMPXCHG16, X86::MOV16rr,
8574                                                X86::NOT16r, X86::AX,
8575                                                X86::GR16RegisterClass);
8576   case X86::ATOMOR16:
8577     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8578                                                X86::OR16ri, X86::MOV16rm,
8579                                                X86::LCMPXCHG16, X86::MOV16rr,
8580                                                X86::NOT16r, X86::AX,
8581                                                X86::GR16RegisterClass);
8582   case X86::ATOMXOR16:
8583     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8584                                                X86::XOR16ri, X86::MOV16rm,
8585                                                X86::LCMPXCHG16, X86::MOV16rr,
8586                                                X86::NOT16r, X86::AX,
8587                                                X86::GR16RegisterClass);
8588   case X86::ATOMNAND16:
8589     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8590                                                X86::AND16ri, X86::MOV16rm,
8591                                                X86::LCMPXCHG16, X86::MOV16rr,
8592                                                X86::NOT16r, X86::AX,
8593                                                X86::GR16RegisterClass, true);
8594   case X86::ATOMMIN16:
8595     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8596   case X86::ATOMMAX16:
8597     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8598   case X86::ATOMUMIN16:
8599     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8600   case X86::ATOMUMAX16:
8601     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8602
8603   case X86::ATOMAND8:
8604     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8605                                                X86::AND8ri, X86::MOV8rm,
8606                                                X86::LCMPXCHG8, X86::MOV8rr,
8607                                                X86::NOT8r, X86::AL,
8608                                                X86::GR8RegisterClass);
8609   case X86::ATOMOR8:
8610     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8611                                                X86::OR8ri, X86::MOV8rm,
8612                                                X86::LCMPXCHG8, X86::MOV8rr,
8613                                                X86::NOT8r, X86::AL,
8614                                                X86::GR8RegisterClass);
8615   case X86::ATOMXOR8:
8616     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8617                                                X86::XOR8ri, X86::MOV8rm,
8618                                                X86::LCMPXCHG8, X86::MOV8rr,
8619                                                X86::NOT8r, X86::AL,
8620                                                X86::GR8RegisterClass);
8621   case X86::ATOMNAND8:
8622     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8623                                                X86::AND8ri, X86::MOV8rm,
8624                                                X86::LCMPXCHG8, X86::MOV8rr,
8625                                                X86::NOT8r, X86::AL,
8626                                                X86::GR8RegisterClass, true);
8627   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8628   // This group is for 64-bit host.
8629   case X86::ATOMAND64:
8630     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8631                                                X86::AND64ri32, X86::MOV64rm,
8632                                                X86::LCMPXCHG64, X86::MOV64rr,
8633                                                X86::NOT64r, X86::RAX,
8634                                                X86::GR64RegisterClass);
8635   case X86::ATOMOR64:
8636     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8637                                                X86::OR64ri32, X86::MOV64rm,
8638                                                X86::LCMPXCHG64, X86::MOV64rr,
8639                                                X86::NOT64r, X86::RAX,
8640                                                X86::GR64RegisterClass);
8641   case X86::ATOMXOR64:
8642     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8643                                                X86::XOR64ri32, X86::MOV64rm,
8644                                                X86::LCMPXCHG64, X86::MOV64rr,
8645                                                X86::NOT64r, X86::RAX,
8646                                                X86::GR64RegisterClass);
8647   case X86::ATOMNAND64:
8648     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8649                                                X86::AND64ri32, X86::MOV64rm,
8650                                                X86::LCMPXCHG64, X86::MOV64rr,
8651                                                X86::NOT64r, X86::RAX,
8652                                                X86::GR64RegisterClass, true);
8653   case X86::ATOMMIN64:
8654     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8655   case X86::ATOMMAX64:
8656     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8657   case X86::ATOMUMIN64:
8658     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8659   case X86::ATOMUMAX64:
8660     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8661
8662   // This group does 64-bit operations on a 32-bit host.
8663   case X86::ATOMAND6432:
8664     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8665                                                X86::AND32rr, X86::AND32rr,
8666                                                X86::AND32ri, X86::AND32ri,
8667                                                false);
8668   case X86::ATOMOR6432:
8669     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8670                                                X86::OR32rr, X86::OR32rr,
8671                                                X86::OR32ri, X86::OR32ri,
8672                                                false);
8673   case X86::ATOMXOR6432:
8674     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8675                                                X86::XOR32rr, X86::XOR32rr,
8676                                                X86::XOR32ri, X86::XOR32ri,
8677                                                false);
8678   case X86::ATOMNAND6432:
8679     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8680                                                X86::AND32rr, X86::AND32rr,
8681                                                X86::AND32ri, X86::AND32ri,
8682                                                true);
8683   case X86::ATOMADD6432:
8684     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8685                                                X86::ADD32rr, X86::ADC32rr,
8686                                                X86::ADD32ri, X86::ADC32ri,
8687                                                false);
8688   case X86::ATOMSUB6432:
8689     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8690                                                X86::SUB32rr, X86::SBB32rr,
8691                                                X86::SUB32ri, X86::SBB32ri,
8692                                                false);
8693   case X86::ATOMSWAP6432:
8694     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8695                                                X86::MOV32rr, X86::MOV32rr,
8696                                                X86::MOV32ri, X86::MOV32ri,
8697                                                false);
8698   case X86::VASTART_SAVE_XMM_REGS:
8699     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8700   }
8701 }
8702
8703 //===----------------------------------------------------------------------===//
8704 //                           X86 Optimization Hooks
8705 //===----------------------------------------------------------------------===//
8706
8707 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8708                                                        const APInt &Mask,
8709                                                        APInt &KnownZero,
8710                                                        APInt &KnownOne,
8711                                                        const SelectionDAG &DAG,
8712                                                        unsigned Depth) const {
8713   unsigned Opc = Op.getOpcode();
8714   assert((Opc >= ISD::BUILTIN_OP_END ||
8715           Opc == ISD::INTRINSIC_WO_CHAIN ||
8716           Opc == ISD::INTRINSIC_W_CHAIN ||
8717           Opc == ISD::INTRINSIC_VOID) &&
8718          "Should use MaskedValueIsZero if you don't know whether Op"
8719          " is a target node!");
8720
8721   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8722   switch (Opc) {
8723   default: break;
8724   case X86ISD::ADD:
8725   case X86ISD::SUB:
8726   case X86ISD::SMUL:
8727   case X86ISD::UMUL:
8728   case X86ISD::INC:
8729   case X86ISD::DEC:
8730   case X86ISD::OR:
8731   case X86ISD::XOR:
8732   case X86ISD::AND:
8733     // These nodes' second result is a boolean.
8734     if (Op.getResNo() == 0)
8735       break;
8736     // Fallthrough
8737   case X86ISD::SETCC:
8738     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8739                                        Mask.getBitWidth() - 1);
8740     break;
8741   }
8742 }
8743
8744 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8745 /// node is a GlobalAddress + offset.
8746 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8747                                        const GlobalValue* &GA,
8748                                        int64_t &Offset) const {
8749   if (N->getOpcode() == X86ISD::Wrapper) {
8750     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8751       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8752       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8753       return true;
8754     }
8755   }
8756   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8757 }
8758
8759 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8760 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8761 /// if the load addresses are consecutive, non-overlapping, and in the right
8762 /// order.
8763 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8764                                      const TargetLowering &TLI) {
8765   DebugLoc dl = N->getDebugLoc();
8766   EVT VT = N->getValueType(0);
8767   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8768
8769   if (VT.getSizeInBits() != 128)
8770     return SDValue();
8771
8772   SmallVector<SDValue, 16> Elts;
8773   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8774     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8775   
8776   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8777 }
8778
8779 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8780 /// and convert it from being a bunch of shuffles and extracts to a simple
8781 /// store and scalar loads to extract the elements.
8782 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8783                                                 const TargetLowering &TLI) {
8784   SDValue InputVector = N->getOperand(0);
8785
8786   // Only operate on vectors of 4 elements, where the alternative shuffling
8787   // gets to be more expensive.
8788   if (InputVector.getValueType() != MVT::v4i32)
8789     return SDValue();
8790
8791   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8792   // single use which is a sign-extend or zero-extend, and all elements are
8793   // used.
8794   SmallVector<SDNode *, 4> Uses;
8795   unsigned ExtractedElements = 0;
8796   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8797        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8798     if (UI.getUse().getResNo() != InputVector.getResNo())
8799       return SDValue();
8800
8801     SDNode *Extract = *UI;
8802     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8803       return SDValue();
8804
8805     if (Extract->getValueType(0) != MVT::i32)
8806       return SDValue();
8807     if (!Extract->hasOneUse())
8808       return SDValue();
8809     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8810         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8811       return SDValue();
8812     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8813       return SDValue();
8814
8815     // Record which element was extracted.
8816     ExtractedElements |=
8817       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8818
8819     Uses.push_back(Extract);
8820   }
8821
8822   // If not all the elements were used, this may not be worthwhile.
8823   if (ExtractedElements != 15)
8824     return SDValue();
8825
8826   // Ok, we've now decided to do the transformation.
8827   DebugLoc dl = InputVector.getDebugLoc();
8828
8829   // Store the value to a temporary stack slot.
8830   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8831   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8832                             false, false, 0);
8833
8834   // Replace each use (extract) with a load of the appropriate element.
8835   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8836        UE = Uses.end(); UI != UE; ++UI) {
8837     SDNode *Extract = *UI;
8838
8839     // Compute the element's address.
8840     SDValue Idx = Extract->getOperand(1);
8841     unsigned EltSize =
8842         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8843     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8844     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8845
8846     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8847
8848     // Load the scalar.
8849     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8850                           NULL, 0, false, false, 0);
8851
8852     // Replace the exact with the load.
8853     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8854   }
8855
8856   // The replacement was made in place; don't return anything.
8857   return SDValue();
8858 }
8859
8860 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8861 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8862                                     const X86Subtarget *Subtarget) {
8863   DebugLoc DL = N->getDebugLoc();
8864   SDValue Cond = N->getOperand(0);
8865   // Get the LHS/RHS of the select.
8866   SDValue LHS = N->getOperand(1);
8867   SDValue RHS = N->getOperand(2);
8868
8869   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8870   // instructions match the semantics of the common C idiom x<y?x:y but not
8871   // x<=y?x:y, because of how they handle negative zero (which can be
8872   // ignored in unsafe-math mode).
8873   if (Subtarget->hasSSE2() &&
8874       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8875       Cond.getOpcode() == ISD::SETCC) {
8876     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8877
8878     unsigned Opcode = 0;
8879     // Check for x CC y ? x : y.
8880     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8881         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8882       switch (CC) {
8883       default: break;
8884       case ISD::SETULT:
8885         // Converting this to a min would handle NaNs incorrectly, and swapping
8886         // the operands would cause it to handle comparisons between positive
8887         // and negative zero incorrectly.
8888         if (!FiniteOnlyFPMath() &&
8889             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8890           if (!UnsafeFPMath &&
8891               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8892             break;
8893           std::swap(LHS, RHS);
8894         }
8895         Opcode = X86ISD::FMIN;
8896         break;
8897       case ISD::SETOLE:
8898         // Converting this to a min would handle comparisons between positive
8899         // and negative zero incorrectly.
8900         if (!UnsafeFPMath &&
8901             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8902           break;
8903         Opcode = X86ISD::FMIN;
8904         break;
8905       case ISD::SETULE:
8906         // Converting this to a min would handle both negative zeros and NaNs
8907         // incorrectly, but we can swap the operands to fix both.
8908         std::swap(LHS, RHS);
8909       case ISD::SETOLT:
8910       case ISD::SETLT:
8911       case ISD::SETLE:
8912         Opcode = X86ISD::FMIN;
8913         break;
8914
8915       case ISD::SETOGE:
8916         // Converting this to a max would handle comparisons between positive
8917         // and negative zero incorrectly.
8918         if (!UnsafeFPMath &&
8919             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8920           break;
8921         Opcode = X86ISD::FMAX;
8922         break;
8923       case ISD::SETUGT:
8924         // Converting this to a max would handle NaNs incorrectly, and swapping
8925         // the operands would cause it to handle comparisons between positive
8926         // and negative zero incorrectly.
8927         if (!FiniteOnlyFPMath() &&
8928             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8929           if (!UnsafeFPMath &&
8930               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8931             break;
8932           std::swap(LHS, RHS);
8933         }
8934         Opcode = X86ISD::FMAX;
8935         break;
8936       case ISD::SETUGE:
8937         // Converting this to a max would handle both negative zeros and NaNs
8938         // incorrectly, but we can swap the operands to fix both.
8939         std::swap(LHS, RHS);
8940       case ISD::SETOGT:
8941       case ISD::SETGT:
8942       case ISD::SETGE:
8943         Opcode = X86ISD::FMAX;
8944         break;
8945       }
8946     // Check for x CC y ? y : x -- a min/max with reversed arms.
8947     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8948                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8949       switch (CC) {
8950       default: break;
8951       case ISD::SETOGE:
8952         // Converting this to a min would handle comparisons between positive
8953         // and negative zero incorrectly, and swapping the operands would
8954         // cause it to handle NaNs incorrectly.
8955         if (!UnsafeFPMath &&
8956             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8957           if (!FiniteOnlyFPMath() &&
8958               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8959             break;
8960           std::swap(LHS, RHS);
8961         }
8962         Opcode = X86ISD::FMIN;
8963         break;
8964       case ISD::SETUGT:
8965         // Converting this to a min would handle NaNs incorrectly.
8966         if (!UnsafeFPMath &&
8967             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8968           break;
8969         Opcode = X86ISD::FMIN;
8970         break;
8971       case ISD::SETUGE:
8972         // Converting this to a min would handle both negative zeros and NaNs
8973         // incorrectly, but we can swap the operands to fix both.
8974         std::swap(LHS, RHS);
8975       case ISD::SETOGT:
8976       case ISD::SETGT:
8977       case ISD::SETGE:
8978         Opcode = X86ISD::FMIN;
8979         break;
8980
8981       case ISD::SETULT:
8982         // Converting this to a max would handle NaNs incorrectly.
8983         if (!FiniteOnlyFPMath() &&
8984             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8985           break;
8986         Opcode = X86ISD::FMAX;
8987         break;
8988       case ISD::SETOLE:
8989         // Converting this to a max would handle comparisons between positive
8990         // and negative zero incorrectly, and swapping the operands would
8991         // cause it to handle NaNs incorrectly.
8992         if (!UnsafeFPMath &&
8993             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
8994           if (!FiniteOnlyFPMath() &&
8995               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8996             break;
8997           std::swap(LHS, RHS);
8998         }
8999         Opcode = X86ISD::FMAX;
9000         break;
9001       case ISD::SETULE:
9002         // Converting this to a max would handle both negative zeros and NaNs
9003         // incorrectly, but we can swap the operands to fix both.
9004         std::swap(LHS, RHS);
9005       case ISD::SETOLT:
9006       case ISD::SETLT:
9007       case ISD::SETLE:
9008         Opcode = X86ISD::FMAX;
9009         break;
9010       }
9011     }
9012
9013     if (Opcode)
9014       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9015   }
9016
9017   // If this is a select between two integer constants, try to do some
9018   // optimizations.
9019   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9020     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9021       // Don't do this for crazy integer types.
9022       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9023         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9024         // so that TrueC (the true value) is larger than FalseC.
9025         bool NeedsCondInvert = false;
9026
9027         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9028             // Efficiently invertible.
9029             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9030              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9031               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9032           NeedsCondInvert = true;
9033           std::swap(TrueC, FalseC);
9034         }
9035
9036         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9037         if (FalseC->getAPIntValue() == 0 &&
9038             TrueC->getAPIntValue().isPowerOf2()) {
9039           if (NeedsCondInvert) // Invert the condition if needed.
9040             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9041                                DAG.getConstant(1, Cond.getValueType()));
9042
9043           // Zero extend the condition if needed.
9044           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9045
9046           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9047           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9048                              DAG.getConstant(ShAmt, MVT::i8));
9049         }
9050
9051         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9052         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9053           if (NeedsCondInvert) // Invert the condition if needed.
9054             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9055                                DAG.getConstant(1, Cond.getValueType()));
9056
9057           // Zero extend the condition if needed.
9058           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9059                              FalseC->getValueType(0), Cond);
9060           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9061                              SDValue(FalseC, 0));
9062         }
9063
9064         // Optimize cases that will turn into an LEA instruction.  This requires
9065         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9066         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9067           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9068           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9069
9070           bool isFastMultiplier = false;
9071           if (Diff < 10) {
9072             switch ((unsigned char)Diff) {
9073               default: break;
9074               case 1:  // result = add base, cond
9075               case 2:  // result = lea base(    , cond*2)
9076               case 3:  // result = lea base(cond, cond*2)
9077               case 4:  // result = lea base(    , cond*4)
9078               case 5:  // result = lea base(cond, cond*4)
9079               case 8:  // result = lea base(    , cond*8)
9080               case 9:  // result = lea base(cond, cond*8)
9081                 isFastMultiplier = true;
9082                 break;
9083             }
9084           }
9085
9086           if (isFastMultiplier) {
9087             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9088             if (NeedsCondInvert) // Invert the condition if needed.
9089               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9090                                  DAG.getConstant(1, Cond.getValueType()));
9091
9092             // Zero extend the condition if needed.
9093             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9094                                Cond);
9095             // Scale the condition by the difference.
9096             if (Diff != 1)
9097               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9098                                  DAG.getConstant(Diff, Cond.getValueType()));
9099
9100             // Add the base if non-zero.
9101             if (FalseC->getAPIntValue() != 0)
9102               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9103                                  SDValue(FalseC, 0));
9104             return Cond;
9105           }
9106         }
9107       }
9108   }
9109
9110   return SDValue();
9111 }
9112
9113 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9114 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9115                                   TargetLowering::DAGCombinerInfo &DCI) {
9116   DebugLoc DL = N->getDebugLoc();
9117
9118   // If the flag operand isn't dead, don't touch this CMOV.
9119   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9120     return SDValue();
9121
9122   // If this is a select between two integer constants, try to do some
9123   // optimizations.  Note that the operands are ordered the opposite of SELECT
9124   // operands.
9125   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9126     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9127       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9128       // larger than FalseC (the false value).
9129       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9130
9131       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9132         CC = X86::GetOppositeBranchCondition(CC);
9133         std::swap(TrueC, FalseC);
9134       }
9135
9136       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9137       // This is efficient for any integer data type (including i8/i16) and
9138       // shift amount.
9139       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9140         SDValue Cond = N->getOperand(3);
9141         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9142                            DAG.getConstant(CC, MVT::i8), Cond);
9143
9144         // Zero extend the condition if needed.
9145         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9146
9147         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9148         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9149                            DAG.getConstant(ShAmt, MVT::i8));
9150         if (N->getNumValues() == 2)  // Dead flag value?
9151           return DCI.CombineTo(N, Cond, SDValue());
9152         return Cond;
9153       }
9154
9155       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9156       // for any integer data type, including i8/i16.
9157       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9158         SDValue Cond = N->getOperand(3);
9159         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9160                            DAG.getConstant(CC, MVT::i8), Cond);
9161
9162         // Zero extend the condition if needed.
9163         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9164                            FalseC->getValueType(0), Cond);
9165         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9166                            SDValue(FalseC, 0));
9167
9168         if (N->getNumValues() == 2)  // Dead flag value?
9169           return DCI.CombineTo(N, Cond, SDValue());
9170         return Cond;
9171       }
9172
9173       // Optimize cases that will turn into an LEA instruction.  This requires
9174       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9175       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9176         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9177         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9178
9179         bool isFastMultiplier = false;
9180         if (Diff < 10) {
9181           switch ((unsigned char)Diff) {
9182           default: break;
9183           case 1:  // result = add base, cond
9184           case 2:  // result = lea base(    , cond*2)
9185           case 3:  // result = lea base(cond, cond*2)
9186           case 4:  // result = lea base(    , cond*4)
9187           case 5:  // result = lea base(cond, cond*4)
9188           case 8:  // result = lea base(    , cond*8)
9189           case 9:  // result = lea base(cond, cond*8)
9190             isFastMultiplier = true;
9191             break;
9192           }
9193         }
9194
9195         if (isFastMultiplier) {
9196           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9197           SDValue Cond = N->getOperand(3);
9198           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9199                              DAG.getConstant(CC, MVT::i8), Cond);
9200           // Zero extend the condition if needed.
9201           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9202                              Cond);
9203           // Scale the condition by the difference.
9204           if (Diff != 1)
9205             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9206                                DAG.getConstant(Diff, Cond.getValueType()));
9207
9208           // Add the base if non-zero.
9209           if (FalseC->getAPIntValue() != 0)
9210             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9211                                SDValue(FalseC, 0));
9212           if (N->getNumValues() == 2)  // Dead flag value?
9213             return DCI.CombineTo(N, Cond, SDValue());
9214           return Cond;
9215         }
9216       }
9217     }
9218   }
9219   return SDValue();
9220 }
9221
9222
9223 /// PerformMulCombine - Optimize a single multiply with constant into two
9224 /// in order to implement it with two cheaper instructions, e.g.
9225 /// LEA + SHL, LEA + LEA.
9226 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9227                                  TargetLowering::DAGCombinerInfo &DCI) {
9228   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9229     return SDValue();
9230
9231   EVT VT = N->getValueType(0);
9232   if (VT != MVT::i64)
9233     return SDValue();
9234
9235   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9236   if (!C)
9237     return SDValue();
9238   uint64_t MulAmt = C->getZExtValue();
9239   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9240     return SDValue();
9241
9242   uint64_t MulAmt1 = 0;
9243   uint64_t MulAmt2 = 0;
9244   if ((MulAmt % 9) == 0) {
9245     MulAmt1 = 9;
9246     MulAmt2 = MulAmt / 9;
9247   } else if ((MulAmt % 5) == 0) {
9248     MulAmt1 = 5;
9249     MulAmt2 = MulAmt / 5;
9250   } else if ((MulAmt % 3) == 0) {
9251     MulAmt1 = 3;
9252     MulAmt2 = MulAmt / 3;
9253   }
9254   if (MulAmt2 &&
9255       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9256     DebugLoc DL = N->getDebugLoc();
9257
9258     if (isPowerOf2_64(MulAmt2) &&
9259         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9260       // If second multiplifer is pow2, issue it first. We want the multiply by
9261       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9262       // is an add.
9263       std::swap(MulAmt1, MulAmt2);
9264
9265     SDValue NewMul;
9266     if (isPowerOf2_64(MulAmt1))
9267       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9268                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9269     else
9270       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9271                            DAG.getConstant(MulAmt1, VT));
9272
9273     if (isPowerOf2_64(MulAmt2))
9274       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9275                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9276     else
9277       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9278                            DAG.getConstant(MulAmt2, VT));
9279
9280     // Do not add new nodes to DAG combiner worklist.
9281     DCI.CombineTo(N, NewMul, false);
9282   }
9283   return SDValue();
9284 }
9285
9286 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9287   SDValue N0 = N->getOperand(0);
9288   SDValue N1 = N->getOperand(1);
9289   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9290   EVT VT = N0.getValueType();
9291
9292   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9293   // since the result of setcc_c is all zero's or all ones.
9294   if (N1C && N0.getOpcode() == ISD::AND &&
9295       N0.getOperand(1).getOpcode() == ISD::Constant) {
9296     SDValue N00 = N0.getOperand(0);
9297     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9298         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9299           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9300          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9301       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9302       APInt ShAmt = N1C->getAPIntValue();
9303       Mask = Mask.shl(ShAmt);
9304       if (Mask != 0)
9305         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9306                            N00, DAG.getConstant(Mask, VT));
9307     }
9308   }
9309
9310   return SDValue();
9311 }
9312
9313 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9314 ///                       when possible.
9315 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9316                                    const X86Subtarget *Subtarget) {
9317   EVT VT = N->getValueType(0);
9318   if (!VT.isVector() && VT.isInteger() &&
9319       N->getOpcode() == ISD::SHL)
9320     return PerformSHLCombine(N, DAG);
9321
9322   // On X86 with SSE2 support, we can transform this to a vector shift if
9323   // all elements are shifted by the same amount.  We can't do this in legalize
9324   // because the a constant vector is typically transformed to a constant pool
9325   // so we have no knowledge of the shift amount.
9326   if (!Subtarget->hasSSE2())
9327     return SDValue();
9328
9329   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9330     return SDValue();
9331
9332   SDValue ShAmtOp = N->getOperand(1);
9333   EVT EltVT = VT.getVectorElementType();
9334   DebugLoc DL = N->getDebugLoc();
9335   SDValue BaseShAmt = SDValue();
9336   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9337     unsigned NumElts = VT.getVectorNumElements();
9338     unsigned i = 0;
9339     for (; i != NumElts; ++i) {
9340       SDValue Arg = ShAmtOp.getOperand(i);
9341       if (Arg.getOpcode() == ISD::UNDEF) continue;
9342       BaseShAmt = Arg;
9343       break;
9344     }
9345     for (; i != NumElts; ++i) {
9346       SDValue Arg = ShAmtOp.getOperand(i);
9347       if (Arg.getOpcode() == ISD::UNDEF) continue;
9348       if (Arg != BaseShAmt) {
9349         return SDValue();
9350       }
9351     }
9352   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9353              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9354     SDValue InVec = ShAmtOp.getOperand(0);
9355     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9356       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9357       unsigned i = 0;
9358       for (; i != NumElts; ++i) {
9359         SDValue Arg = InVec.getOperand(i);
9360         if (Arg.getOpcode() == ISD::UNDEF) continue;
9361         BaseShAmt = Arg;
9362         break;
9363       }
9364     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9365        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9366          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9367          if (C->getZExtValue() == SplatIdx)
9368            BaseShAmt = InVec.getOperand(1);
9369        }
9370     }
9371     if (BaseShAmt.getNode() == 0)
9372       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9373                               DAG.getIntPtrConstant(0));
9374   } else
9375     return SDValue();
9376
9377   // The shift amount is an i32.
9378   if (EltVT.bitsGT(MVT::i32))
9379     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9380   else if (EltVT.bitsLT(MVT::i32))
9381     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9382
9383   // The shift amount is identical so we can do a vector shift.
9384   SDValue  ValOp = N->getOperand(0);
9385   switch (N->getOpcode()) {
9386   default:
9387     llvm_unreachable("Unknown shift opcode!");
9388     break;
9389   case ISD::SHL:
9390     if (VT == MVT::v2i64)
9391       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9392                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9393                          ValOp, BaseShAmt);
9394     if (VT == MVT::v4i32)
9395       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9396                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9397                          ValOp, BaseShAmt);
9398     if (VT == MVT::v8i16)
9399       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9400                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9401                          ValOp, BaseShAmt);
9402     break;
9403   case ISD::SRA:
9404     if (VT == MVT::v4i32)
9405       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9406                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9407                          ValOp, BaseShAmt);
9408     if (VT == MVT::v8i16)
9409       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9410                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9411                          ValOp, BaseShAmt);
9412     break;
9413   case ISD::SRL:
9414     if (VT == MVT::v2i64)
9415       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9416                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9417                          ValOp, BaseShAmt);
9418     if (VT == MVT::v4i32)
9419       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9420                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9421                          ValOp, BaseShAmt);
9422     if (VT ==  MVT::v8i16)
9423       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9424                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9425                          ValOp, BaseShAmt);
9426     break;
9427   }
9428   return SDValue();
9429 }
9430
9431 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9432                                 TargetLowering::DAGCombinerInfo &DCI,
9433                                 const X86Subtarget *Subtarget) {
9434   if (DCI.isBeforeLegalizeOps())
9435     return SDValue();
9436
9437   EVT VT = N->getValueType(0);
9438   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9439     return SDValue();
9440
9441   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9442   SDValue N0 = N->getOperand(0);
9443   SDValue N1 = N->getOperand(1);
9444   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9445     std::swap(N0, N1);
9446   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9447     return SDValue();
9448   if (!N0.hasOneUse() || !N1.hasOneUse())
9449     return SDValue();
9450
9451   SDValue ShAmt0 = N0.getOperand(1);
9452   if (ShAmt0.getValueType() != MVT::i8)
9453     return SDValue();
9454   SDValue ShAmt1 = N1.getOperand(1);
9455   if (ShAmt1.getValueType() != MVT::i8)
9456     return SDValue();
9457   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9458     ShAmt0 = ShAmt0.getOperand(0);
9459   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9460     ShAmt1 = ShAmt1.getOperand(0);
9461
9462   DebugLoc DL = N->getDebugLoc();
9463   unsigned Opc = X86ISD::SHLD;
9464   SDValue Op0 = N0.getOperand(0);
9465   SDValue Op1 = N1.getOperand(0);
9466   if (ShAmt0.getOpcode() == ISD::SUB) {
9467     Opc = X86ISD::SHRD;
9468     std::swap(Op0, Op1);
9469     std::swap(ShAmt0, ShAmt1);
9470   }
9471
9472   unsigned Bits = VT.getSizeInBits();
9473   if (ShAmt1.getOpcode() == ISD::SUB) {
9474     SDValue Sum = ShAmt1.getOperand(0);
9475     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9476       if (SumC->getSExtValue() == Bits &&
9477           ShAmt1.getOperand(1) == ShAmt0)
9478         return DAG.getNode(Opc, DL, VT,
9479                            Op0, Op1,
9480                            DAG.getNode(ISD::TRUNCATE, DL,
9481                                        MVT::i8, ShAmt0));
9482     }
9483   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9484     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9485     if (ShAmt0C &&
9486         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9487       return DAG.getNode(Opc, DL, VT,
9488                          N0.getOperand(0), N1.getOperand(0),
9489                          DAG.getNode(ISD::TRUNCATE, DL,
9490                                        MVT::i8, ShAmt0));
9491   }
9492
9493   return SDValue();
9494 }
9495
9496 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9497 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9498                                    const X86Subtarget *Subtarget) {
9499   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9500   // the FP state in cases where an emms may be missing.
9501   // A preferable solution to the general problem is to figure out the right
9502   // places to insert EMMS.  This qualifies as a quick hack.
9503
9504   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9505   StoreSDNode *St = cast<StoreSDNode>(N);
9506   EVT VT = St->getValue().getValueType();
9507   if (VT.getSizeInBits() != 64)
9508     return SDValue();
9509
9510   const Function *F = DAG.getMachineFunction().getFunction();
9511   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9512   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9513     && Subtarget->hasSSE2();
9514   if ((VT.isVector() ||
9515        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9516       isa<LoadSDNode>(St->getValue()) &&
9517       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9518       St->getChain().hasOneUse() && !St->isVolatile()) {
9519     SDNode* LdVal = St->getValue().getNode();
9520     LoadSDNode *Ld = 0;
9521     int TokenFactorIndex = -1;
9522     SmallVector<SDValue, 8> Ops;
9523     SDNode* ChainVal = St->getChain().getNode();
9524     // Must be a store of a load.  We currently handle two cases:  the load
9525     // is a direct child, and it's under an intervening TokenFactor.  It is
9526     // possible to dig deeper under nested TokenFactors.
9527     if (ChainVal == LdVal)
9528       Ld = cast<LoadSDNode>(St->getChain());
9529     else if (St->getValue().hasOneUse() &&
9530              ChainVal->getOpcode() == ISD::TokenFactor) {
9531       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9532         if (ChainVal->getOperand(i).getNode() == LdVal) {
9533           TokenFactorIndex = i;
9534           Ld = cast<LoadSDNode>(St->getValue());
9535         } else
9536           Ops.push_back(ChainVal->getOperand(i));
9537       }
9538     }
9539
9540     if (!Ld || !ISD::isNormalLoad(Ld))
9541       return SDValue();
9542
9543     // If this is not the MMX case, i.e. we are just turning i64 load/store
9544     // into f64 load/store, avoid the transformation if there are multiple
9545     // uses of the loaded value.
9546     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9547       return SDValue();
9548
9549     DebugLoc LdDL = Ld->getDebugLoc();
9550     DebugLoc StDL = N->getDebugLoc();
9551     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9552     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9553     // pair instead.
9554     if (Subtarget->is64Bit() || F64IsLegal) {
9555       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9556       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9557                                   Ld->getBasePtr(), Ld->getSrcValue(),
9558                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9559                                   Ld->isNonTemporal(), Ld->getAlignment());
9560       SDValue NewChain = NewLd.getValue(1);
9561       if (TokenFactorIndex != -1) {
9562         Ops.push_back(NewChain);
9563         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9564                                Ops.size());
9565       }
9566       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9567                           St->getSrcValue(), St->getSrcValueOffset(),
9568                           St->isVolatile(), St->isNonTemporal(),
9569                           St->getAlignment());
9570     }
9571
9572     // Otherwise, lower to two pairs of 32-bit loads / stores.
9573     SDValue LoAddr = Ld->getBasePtr();
9574     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9575                                  DAG.getConstant(4, MVT::i32));
9576
9577     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9578                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9579                                Ld->isVolatile(), Ld->isNonTemporal(),
9580                                Ld->getAlignment());
9581     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9582                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9583                                Ld->isVolatile(), Ld->isNonTemporal(),
9584                                MinAlign(Ld->getAlignment(), 4));
9585
9586     SDValue NewChain = LoLd.getValue(1);
9587     if (TokenFactorIndex != -1) {
9588       Ops.push_back(LoLd);
9589       Ops.push_back(HiLd);
9590       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9591                              Ops.size());
9592     }
9593
9594     LoAddr = St->getBasePtr();
9595     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9596                          DAG.getConstant(4, MVT::i32));
9597
9598     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9599                                 St->getSrcValue(), St->getSrcValueOffset(),
9600                                 St->isVolatile(), St->isNonTemporal(),
9601                                 St->getAlignment());
9602     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9603                                 St->getSrcValue(),
9604                                 St->getSrcValueOffset() + 4,
9605                                 St->isVolatile(),
9606                                 St->isNonTemporal(),
9607                                 MinAlign(St->getAlignment(), 4));
9608     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9609   }
9610   return SDValue();
9611 }
9612
9613 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9614 /// X86ISD::FXOR nodes.
9615 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9616   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9617   // F[X]OR(0.0, x) -> x
9618   // F[X]OR(x, 0.0) -> x
9619   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9620     if (C->getValueAPF().isPosZero())
9621       return N->getOperand(1);
9622   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9623     if (C->getValueAPF().isPosZero())
9624       return N->getOperand(0);
9625   return SDValue();
9626 }
9627
9628 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9629 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9630   // FAND(0.0, x) -> 0.0
9631   // FAND(x, 0.0) -> 0.0
9632   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9633     if (C->getValueAPF().isPosZero())
9634       return N->getOperand(0);
9635   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9636     if (C->getValueAPF().isPosZero())
9637       return N->getOperand(1);
9638   return SDValue();
9639 }
9640
9641 static SDValue PerformBTCombine(SDNode *N,
9642                                 SelectionDAG &DAG,
9643                                 TargetLowering::DAGCombinerInfo &DCI) {
9644   // BT ignores high bits in the bit index operand.
9645   SDValue Op1 = N->getOperand(1);
9646   if (Op1.hasOneUse()) {
9647     unsigned BitWidth = Op1.getValueSizeInBits();
9648     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9649     APInt KnownZero, KnownOne;
9650     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9651                                           !DCI.isBeforeLegalizeOps());
9652     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9653     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9654         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9655       DCI.CommitTargetLoweringOpt(TLO);
9656   }
9657   return SDValue();
9658 }
9659
9660 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9661   SDValue Op = N->getOperand(0);
9662   if (Op.getOpcode() == ISD::BIT_CONVERT)
9663     Op = Op.getOperand(0);
9664   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9665   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9666       VT.getVectorElementType().getSizeInBits() ==
9667       OpVT.getVectorElementType().getSizeInBits()) {
9668     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9669   }
9670   return SDValue();
9671 }
9672
9673 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9674 // Locked instructions, in turn, have implicit fence semantics (all memory
9675 // operations are flushed before issuing the locked instruction, and the
9676 // are not buffered), so we can fold away the common pattern of
9677 // fence-atomic-fence.
9678 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9679   SDValue atomic = N->getOperand(0);
9680   switch (atomic.getOpcode()) {
9681     case ISD::ATOMIC_CMP_SWAP:
9682     case ISD::ATOMIC_SWAP:
9683     case ISD::ATOMIC_LOAD_ADD:
9684     case ISD::ATOMIC_LOAD_SUB:
9685     case ISD::ATOMIC_LOAD_AND:
9686     case ISD::ATOMIC_LOAD_OR:
9687     case ISD::ATOMIC_LOAD_XOR:
9688     case ISD::ATOMIC_LOAD_NAND:
9689     case ISD::ATOMIC_LOAD_MIN:
9690     case ISD::ATOMIC_LOAD_MAX:
9691     case ISD::ATOMIC_LOAD_UMIN:
9692     case ISD::ATOMIC_LOAD_UMAX:
9693       break;
9694     default:
9695       return SDValue();
9696   }
9697
9698   SDValue fence = atomic.getOperand(0);
9699   if (fence.getOpcode() != ISD::MEMBARRIER)
9700     return SDValue();
9701
9702   switch (atomic.getOpcode()) {
9703     case ISD::ATOMIC_CMP_SWAP:
9704       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9705                                     atomic.getOperand(1), atomic.getOperand(2),
9706                                     atomic.getOperand(3));
9707     case ISD::ATOMIC_SWAP:
9708     case ISD::ATOMIC_LOAD_ADD:
9709     case ISD::ATOMIC_LOAD_SUB:
9710     case ISD::ATOMIC_LOAD_AND:
9711     case ISD::ATOMIC_LOAD_OR:
9712     case ISD::ATOMIC_LOAD_XOR:
9713     case ISD::ATOMIC_LOAD_NAND:
9714     case ISD::ATOMIC_LOAD_MIN:
9715     case ISD::ATOMIC_LOAD_MAX:
9716     case ISD::ATOMIC_LOAD_UMIN:
9717     case ISD::ATOMIC_LOAD_UMAX:
9718       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9719                                     atomic.getOperand(1), atomic.getOperand(2));
9720     default:
9721       return SDValue();
9722   }
9723 }
9724
9725 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9726   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9727   //           (and (i32 x86isd::setcc_carry), 1)
9728   // This eliminates the zext. This transformation is necessary because
9729   // ISD::SETCC is always legalized to i8.
9730   DebugLoc dl = N->getDebugLoc();
9731   SDValue N0 = N->getOperand(0);
9732   EVT VT = N->getValueType(0);
9733   if (N0.getOpcode() == ISD::AND &&
9734       N0.hasOneUse() &&
9735       N0.getOperand(0).hasOneUse()) {
9736     SDValue N00 = N0.getOperand(0);
9737     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9738       return SDValue();
9739     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9740     if (!C || C->getZExtValue() != 1)
9741       return SDValue();
9742     return DAG.getNode(ISD::AND, dl, VT,
9743                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9744                                    N00.getOperand(0), N00.getOperand(1)),
9745                        DAG.getConstant(1, VT));
9746   }
9747
9748   return SDValue();
9749 }
9750
9751 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9752                                              DAGCombinerInfo &DCI) const {
9753   SelectionDAG &DAG = DCI.DAG;
9754   switch (N->getOpcode()) {
9755   default: break;
9756   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9757   case ISD::EXTRACT_VECTOR_ELT:
9758                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9759   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9760   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9761   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9762   case ISD::SHL:
9763   case ISD::SRA:
9764   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9765   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
9766   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9767   case X86ISD::FXOR:
9768   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9769   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9770   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9771   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9772   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9773   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9774   }
9775
9776   return SDValue();
9777 }
9778
9779 /// isTypeDesirableForOp - Return true if the target has native support for
9780 /// the specified value type and it is 'desirable' to use the type for the
9781 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9782 /// instruction encodings are longer and some i16 instructions are slow.
9783 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9784   if (!isTypeLegal(VT))
9785     return false;
9786   if (VT != MVT::i16)
9787     return true;
9788
9789   switch (Opc) {
9790   default:
9791     return true;
9792   case ISD::LOAD:
9793   case ISD::SIGN_EXTEND:
9794   case ISD::ZERO_EXTEND:
9795   case ISD::ANY_EXTEND:
9796   case ISD::SHL:
9797   case ISD::SRL:
9798   case ISD::SUB:
9799   case ISD::ADD:
9800   case ISD::MUL:
9801   case ISD::AND:
9802   case ISD::OR:
9803   case ISD::XOR:
9804     return false;
9805   }
9806 }
9807
9808 static bool MayFoldLoad(SDValue Op) {
9809   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9810 }
9811
9812 static bool MayFoldIntoStore(SDValue Op) {
9813   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9814 }
9815
9816 /// IsDesirableToPromoteOp - This method query the target whether it is
9817 /// beneficial for dag combiner to promote the specified node. If true, it
9818 /// should return the desired promotion type by reference.
9819 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9820   EVT VT = Op.getValueType();
9821   if (VT != MVT::i16)
9822     return false;
9823
9824   bool Promote = false;
9825   bool Commute = false;
9826   switch (Op.getOpcode()) {
9827   default: break;
9828   case ISD::LOAD: {
9829     LoadSDNode *LD = cast<LoadSDNode>(Op);
9830     // If the non-extending load has a single use and it's not live out, then it
9831     // might be folded.
9832     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9833                                                      Op.hasOneUse()*/) {
9834       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9835              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9836         // The only case where we'd want to promote LOAD (rather then it being
9837         // promoted as an operand is when it's only use is liveout.
9838         if (UI->getOpcode() != ISD::CopyToReg)
9839           return false;
9840       }
9841     }
9842     Promote = true;
9843     break;
9844   }
9845   case ISD::SIGN_EXTEND:
9846   case ISD::ZERO_EXTEND:
9847   case ISD::ANY_EXTEND:
9848     Promote = true;
9849     break;
9850   case ISD::SHL:
9851   case ISD::SRL: {
9852     SDValue N0 = Op.getOperand(0);
9853     // Look out for (store (shl (load), x)).
9854     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9855       return false;
9856     Promote = true;
9857     break;
9858   }
9859   case ISD::ADD:
9860   case ISD::MUL:
9861   case ISD::AND:
9862   case ISD::OR:
9863   case ISD::XOR:
9864     Commute = true;
9865     // fallthrough
9866   case ISD::SUB: {
9867     SDValue N0 = Op.getOperand(0);
9868     SDValue N1 = Op.getOperand(1);
9869     if (!Commute && MayFoldLoad(N1))
9870       return false;
9871     // Avoid disabling potential load folding opportunities.
9872     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9873       return false;
9874     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9875       return false;
9876     Promote = true;
9877   }
9878   }
9879
9880   PVT = MVT::i32;
9881   return Promote;
9882 }
9883
9884 //===----------------------------------------------------------------------===//
9885 //                           X86 Inline Assembly Support
9886 //===----------------------------------------------------------------------===//
9887
9888 static bool LowerToBSwap(CallInst *CI) {
9889   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9890   // we will turn this bswap into something that will be lowered to logical ops
9891   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9892   // so don't worry about this.
9893
9894   // Verify this is a simple bswap.
9895   if (CI->getNumOperands() != 2 ||
9896       CI->getType() != CI->getOperand(1)->getType() ||
9897       !CI->getType()->isIntegerTy())
9898     return false;
9899
9900   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9901   if (!Ty || Ty->getBitWidth() % 16 != 0)
9902     return false;
9903
9904   // Okay, we can do this xform, do so now.
9905   const Type *Tys[] = { Ty };
9906   Module *M = CI->getParent()->getParent()->getParent();
9907   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9908
9909   Value *Op = CI->getOperand(1);
9910   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9911
9912   CI->replaceAllUsesWith(Op);
9913   CI->eraseFromParent();
9914   return true;
9915 }
9916
9917 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9918   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9919   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9920
9921   std::string AsmStr = IA->getAsmString();
9922
9923   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9924   SmallVector<StringRef, 4> AsmPieces;
9925   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9926
9927   switch (AsmPieces.size()) {
9928   default: return false;
9929   case 1:
9930     AsmStr = AsmPieces[0];
9931     AsmPieces.clear();
9932     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9933
9934     // bswap $0
9935     if (AsmPieces.size() == 2 &&
9936         (AsmPieces[0] == "bswap" ||
9937          AsmPieces[0] == "bswapq" ||
9938          AsmPieces[0] == "bswapl") &&
9939         (AsmPieces[1] == "$0" ||
9940          AsmPieces[1] == "${0:q}")) {
9941       // No need to check constraints, nothing other than the equivalent of
9942       // "=r,0" would be valid here.
9943       return LowerToBSwap(CI);
9944     }
9945     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9946     if (CI->getType()->isIntegerTy(16) &&
9947         AsmPieces.size() == 3 &&
9948         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9949         AsmPieces[1] == "$$8," &&
9950         AsmPieces[2] == "${0:w}" &&
9951         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9952       AsmPieces.clear();
9953       const std::string &Constraints = IA->getConstraintString();
9954       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9955       std::sort(AsmPieces.begin(), AsmPieces.end());
9956       if (AsmPieces.size() == 4 &&
9957           AsmPieces[0] == "~{cc}" &&
9958           AsmPieces[1] == "~{dirflag}" &&
9959           AsmPieces[2] == "~{flags}" &&
9960           AsmPieces[3] == "~{fpsr}") {
9961         return LowerToBSwap(CI);
9962       }
9963     }
9964     break;
9965   case 3:
9966     if (CI->getType()->isIntegerTy(64) &&
9967         Constraints.size() >= 2 &&
9968         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9969         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9970       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9971       SmallVector<StringRef, 4> Words;
9972       SplitString(AsmPieces[0], Words, " \t");
9973       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9974         Words.clear();
9975         SplitString(AsmPieces[1], Words, " \t");
9976         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9977           Words.clear();
9978           SplitString(AsmPieces[2], Words, " \t,");
9979           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9980               Words[2] == "%edx") {
9981             return LowerToBSwap(CI);
9982           }
9983         }
9984       }
9985     }
9986     break;
9987   }
9988   return false;
9989 }
9990
9991
9992
9993 /// getConstraintType - Given a constraint letter, return the type of
9994 /// constraint it is for this target.
9995 X86TargetLowering::ConstraintType
9996 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9997   if (Constraint.size() == 1) {
9998     switch (Constraint[0]) {
9999     case 'A':
10000       return C_Register;
10001     case 'f':
10002     case 'r':
10003     case 'R':
10004     case 'l':
10005     case 'q':
10006     case 'Q':
10007     case 'x':
10008     case 'y':
10009     case 'Y':
10010       return C_RegisterClass;
10011     case 'e':
10012     case 'Z':
10013       return C_Other;
10014     default:
10015       break;
10016     }
10017   }
10018   return TargetLowering::getConstraintType(Constraint);
10019 }
10020
10021 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10022 /// with another that has more specific requirements based on the type of the
10023 /// corresponding operand.
10024 const char *X86TargetLowering::
10025 LowerXConstraint(EVT ConstraintVT) const {
10026   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10027   // 'f' like normal targets.
10028   if (ConstraintVT.isFloatingPoint()) {
10029     if (Subtarget->hasSSE2())
10030       return "Y";
10031     if (Subtarget->hasSSE1())
10032       return "x";
10033   }
10034
10035   return TargetLowering::LowerXConstraint(ConstraintVT);
10036 }
10037
10038 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10039 /// vector.  If it is invalid, don't add anything to Ops.
10040 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10041                                                      char Constraint,
10042                                                      bool hasMemory,
10043                                                      std::vector<SDValue>&Ops,
10044                                                      SelectionDAG &DAG) const {
10045   SDValue Result(0, 0);
10046
10047   switch (Constraint) {
10048   default: break;
10049   case 'I':
10050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10051       if (C->getZExtValue() <= 31) {
10052         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10053         break;
10054       }
10055     }
10056     return;
10057   case 'J':
10058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10059       if (C->getZExtValue() <= 63) {
10060         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10061         break;
10062       }
10063     }
10064     return;
10065   case 'K':
10066     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10067       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10068         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10069         break;
10070       }
10071     }
10072     return;
10073   case 'N':
10074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10075       if (C->getZExtValue() <= 255) {
10076         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10077         break;
10078       }
10079     }
10080     return;
10081   case 'e': {
10082     // 32-bit signed value
10083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10084       const ConstantInt *CI = C->getConstantIntValue();
10085       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10086                                   C->getSExtValue())) {
10087         // Widen to 64 bits here to get it sign extended.
10088         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10089         break;
10090       }
10091     // FIXME gcc accepts some relocatable values here too, but only in certain
10092     // memory models; it's complicated.
10093     }
10094     return;
10095   }
10096   case 'Z': {
10097     // 32-bit unsigned value
10098     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10099       const ConstantInt *CI = C->getConstantIntValue();
10100       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10101                                   C->getZExtValue())) {
10102         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10103         break;
10104       }
10105     }
10106     // FIXME gcc accepts some relocatable values here too, but only in certain
10107     // memory models; it's complicated.
10108     return;
10109   }
10110   case 'i': {
10111     // Literal immediates are always ok.
10112     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10113       // Widen to 64 bits here to get it sign extended.
10114       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10115       break;
10116     }
10117
10118     // If we are in non-pic codegen mode, we allow the address of a global (with
10119     // an optional displacement) to be used with 'i'.
10120     GlobalAddressSDNode *GA = 0;
10121     int64_t Offset = 0;
10122
10123     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10124     while (1) {
10125       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10126         Offset += GA->getOffset();
10127         break;
10128       } else if (Op.getOpcode() == ISD::ADD) {
10129         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10130           Offset += C->getZExtValue();
10131           Op = Op.getOperand(0);
10132           continue;
10133         }
10134       } else if (Op.getOpcode() == ISD::SUB) {
10135         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10136           Offset += -C->getZExtValue();
10137           Op = Op.getOperand(0);
10138           continue;
10139         }
10140       }
10141
10142       // Otherwise, this isn't something we can handle, reject it.
10143       return;
10144     }
10145
10146     const GlobalValue *GV = GA->getGlobal();
10147     // If we require an extra load to get this address, as in PIC mode, we
10148     // can't accept it.
10149     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10150                                                         getTargetMachine())))
10151       return;
10152
10153     if (hasMemory)
10154       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10155     else
10156       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10157     Result = Op;
10158     break;
10159   }
10160   }
10161
10162   if (Result.getNode()) {
10163     Ops.push_back(Result);
10164     return;
10165   }
10166   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10167                                                       Ops, DAG);
10168 }
10169
10170 std::vector<unsigned> X86TargetLowering::
10171 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10172                                   EVT VT) const {
10173   if (Constraint.size() == 1) {
10174     // FIXME: not handling fp-stack yet!
10175     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10176     default: break;  // Unknown constraint letter
10177     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10178       if (Subtarget->is64Bit()) {
10179         if (VT == MVT::i32)
10180           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10181                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10182                                        X86::R10D,X86::R11D,X86::R12D,
10183                                        X86::R13D,X86::R14D,X86::R15D,
10184                                        X86::EBP, X86::ESP, 0);
10185         else if (VT == MVT::i16)
10186           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10187                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10188                                        X86::R10W,X86::R11W,X86::R12W,
10189                                        X86::R13W,X86::R14W,X86::R15W,
10190                                        X86::BP,  X86::SP, 0);
10191         else if (VT == MVT::i8)
10192           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10193                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10194                                        X86::R10B,X86::R11B,X86::R12B,
10195                                        X86::R13B,X86::R14B,X86::R15B,
10196                                        X86::BPL, X86::SPL, 0);
10197
10198         else if (VT == MVT::i64)
10199           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10200                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10201                                        X86::R10, X86::R11, X86::R12,
10202                                        X86::R13, X86::R14, X86::R15,
10203                                        X86::RBP, X86::RSP, 0);
10204
10205         break;
10206       }
10207       // 32-bit fallthrough
10208     case 'Q':   // Q_REGS
10209       if (VT == MVT::i32)
10210         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10211       else if (VT == MVT::i16)
10212         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10213       else if (VT == MVT::i8)
10214         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10215       else if (VT == MVT::i64)
10216         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10217       break;
10218     }
10219   }
10220
10221   return std::vector<unsigned>();
10222 }
10223
10224 std::pair<unsigned, const TargetRegisterClass*>
10225 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10226                                                 EVT VT) const {
10227   // First, see if this is a constraint that directly corresponds to an LLVM
10228   // register class.
10229   if (Constraint.size() == 1) {
10230     // GCC Constraint Letters
10231     switch (Constraint[0]) {
10232     default: break;
10233     case 'r':   // GENERAL_REGS
10234     case 'l':   // INDEX_REGS
10235       if (VT == MVT::i8)
10236         return std::make_pair(0U, X86::GR8RegisterClass);
10237       if (VT == MVT::i16)
10238         return std::make_pair(0U, X86::GR16RegisterClass);
10239       if (VT == MVT::i32 || !Subtarget->is64Bit())
10240         return std::make_pair(0U, X86::GR32RegisterClass);
10241       return std::make_pair(0U, X86::GR64RegisterClass);
10242     case 'R':   // LEGACY_REGS
10243       if (VT == MVT::i8)
10244         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10245       if (VT == MVT::i16)
10246         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10247       if (VT == MVT::i32 || !Subtarget->is64Bit())
10248         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10249       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10250     case 'f':  // FP Stack registers.
10251       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10252       // value to the correct fpstack register class.
10253       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10254         return std::make_pair(0U, X86::RFP32RegisterClass);
10255       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10256         return std::make_pair(0U, X86::RFP64RegisterClass);
10257       return std::make_pair(0U, X86::RFP80RegisterClass);
10258     case 'y':   // MMX_REGS if MMX allowed.
10259       if (!Subtarget->hasMMX()) break;
10260       return std::make_pair(0U, X86::VR64RegisterClass);
10261     case 'Y':   // SSE_REGS if SSE2 allowed
10262       if (!Subtarget->hasSSE2()) break;
10263       // FALL THROUGH.
10264     case 'x':   // SSE_REGS if SSE1 allowed
10265       if (!Subtarget->hasSSE1()) break;
10266
10267       switch (VT.getSimpleVT().SimpleTy) {
10268       default: break;
10269       // Scalar SSE types.
10270       case MVT::f32:
10271       case MVT::i32:
10272         return std::make_pair(0U, X86::FR32RegisterClass);
10273       case MVT::f64:
10274       case MVT::i64:
10275         return std::make_pair(0U, X86::FR64RegisterClass);
10276       // Vector types.
10277       case MVT::v16i8:
10278       case MVT::v8i16:
10279       case MVT::v4i32:
10280       case MVT::v2i64:
10281       case MVT::v4f32:
10282       case MVT::v2f64:
10283         return std::make_pair(0U, X86::VR128RegisterClass);
10284       }
10285       break;
10286     }
10287   }
10288
10289   // Use the default implementation in TargetLowering to convert the register
10290   // constraint into a member of a register class.
10291   std::pair<unsigned, const TargetRegisterClass*> Res;
10292   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10293
10294   // Not found as a standard register?
10295   if (Res.second == 0) {
10296     // Map st(0) -> st(7) -> ST0
10297     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10298         tolower(Constraint[1]) == 's' &&
10299         tolower(Constraint[2]) == 't' &&
10300         Constraint[3] == '(' &&
10301         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10302         Constraint[5] == ')' &&
10303         Constraint[6] == '}') {
10304
10305       Res.first = X86::ST0+Constraint[4]-'0';
10306       Res.second = X86::RFP80RegisterClass;
10307       return Res;
10308     }
10309
10310     // GCC allows "st(0)" to be called just plain "st".
10311     if (StringRef("{st}").equals_lower(Constraint)) {
10312       Res.first = X86::ST0;
10313       Res.second = X86::RFP80RegisterClass;
10314       return Res;
10315     }
10316
10317     // flags -> EFLAGS
10318     if (StringRef("{flags}").equals_lower(Constraint)) {
10319       Res.first = X86::EFLAGS;
10320       Res.second = X86::CCRRegisterClass;
10321       return Res;
10322     }
10323
10324     // 'A' means EAX + EDX.
10325     if (Constraint == "A") {
10326       Res.first = X86::EAX;
10327       Res.second = X86::GR32_ADRegisterClass;
10328       return Res;
10329     }
10330     return Res;
10331   }
10332
10333   // Otherwise, check to see if this is a register class of the wrong value
10334   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10335   // turn into {ax},{dx}.
10336   if (Res.second->hasType(VT))
10337     return Res;   // Correct type already, nothing to do.
10338
10339   // All of the single-register GCC register classes map their values onto
10340   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10341   // really want an 8-bit or 32-bit register, map to the appropriate register
10342   // class and return the appropriate register.
10343   if (Res.second == X86::GR16RegisterClass) {
10344     if (VT == MVT::i8) {
10345       unsigned DestReg = 0;
10346       switch (Res.first) {
10347       default: break;
10348       case X86::AX: DestReg = X86::AL; break;
10349       case X86::DX: DestReg = X86::DL; break;
10350       case X86::CX: DestReg = X86::CL; break;
10351       case X86::BX: DestReg = X86::BL; break;
10352       }
10353       if (DestReg) {
10354         Res.first = DestReg;
10355         Res.second = X86::GR8RegisterClass;
10356       }
10357     } else if (VT == MVT::i32) {
10358       unsigned DestReg = 0;
10359       switch (Res.first) {
10360       default: break;
10361       case X86::AX: DestReg = X86::EAX; break;
10362       case X86::DX: DestReg = X86::EDX; break;
10363       case X86::CX: DestReg = X86::ECX; break;
10364       case X86::BX: DestReg = X86::EBX; break;
10365       case X86::SI: DestReg = X86::ESI; break;
10366       case X86::DI: DestReg = X86::EDI; break;
10367       case X86::BP: DestReg = X86::EBP; break;
10368       case X86::SP: DestReg = X86::ESP; break;
10369       }
10370       if (DestReg) {
10371         Res.first = DestReg;
10372         Res.second = X86::GR32RegisterClass;
10373       }
10374     } else if (VT == MVT::i64) {
10375       unsigned DestReg = 0;
10376       switch (Res.first) {
10377       default: break;
10378       case X86::AX: DestReg = X86::RAX; break;
10379       case X86::DX: DestReg = X86::RDX; break;
10380       case X86::CX: DestReg = X86::RCX; break;
10381       case X86::BX: DestReg = X86::RBX; break;
10382       case X86::SI: DestReg = X86::RSI; break;
10383       case X86::DI: DestReg = X86::RDI; break;
10384       case X86::BP: DestReg = X86::RBP; break;
10385       case X86::SP: DestReg = X86::RSP; break;
10386       }
10387       if (DestReg) {
10388         Res.first = DestReg;
10389         Res.second = X86::GR64RegisterClass;
10390       }
10391     }
10392   } else if (Res.second == X86::FR32RegisterClass ||
10393              Res.second == X86::FR64RegisterClass ||
10394              Res.second == X86::VR128RegisterClass) {
10395     // Handle references to XMM physical registers that got mapped into the
10396     // wrong class.  This can happen with constraints like {xmm0} where the
10397     // target independent register mapper will just pick the first match it can
10398     // find, ignoring the required type.
10399     if (VT == MVT::f32)
10400       Res.second = X86::FR32RegisterClass;
10401     else if (VT == MVT::f64)
10402       Res.second = X86::FR64RegisterClass;
10403     else if (X86::VR128RegisterClass->hasType(VT))
10404       Res.second = X86::VR128RegisterClass;
10405   }
10406
10407   return Res;
10408 }