Enable sibling call optimization of libcalls which are expanded during
[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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 static cl::opt<bool>
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60
61 // Forward declarations.
62 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63                        SDValue V2);
64
65 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
66
67   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
68
69   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
70     if (is64Bit) return new X8664_MachoTargetObjectFile();
71     return new TargetLoweringObjectFileMachO();
72   } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73     if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
76     return new TargetLoweringObjectFileCOFF();
77   }
78   llvm_unreachable("unknown subtarget type");
79 }
80
81 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
82   : TargetLowering(TM, createTLOF(TM)) {
83   Subtarget = &TM.getSubtarget<X86Subtarget>();
84   X86ScalarSSEf64 = Subtarget->hasSSE2();
85   X86ScalarSSEf32 = Subtarget->hasSSE1();
86   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
87
88   RegInfo = TM.getRegisterInfo();
89   TD = getTargetData();
90
91   // Set up the TargetLowering object.
92
93   // X86 is weird, it always uses i8 for shift amounts and setcc results.
94   setShiftAmountType(MVT::i8);
95   setBooleanContents(ZeroOrOneBooleanContent);
96   setSchedulingPreference(Sched::RegPressure);
97   setStackPointerRegisterToSaveRestore(X86StackPtr);
98
99   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
100     // Setup Windows compiler runtime calls.
101     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
102     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
103     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
104     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
105     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
106     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
107     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
108     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
109   }
110
111   if (Subtarget->isTargetDarwin()) {
112     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
113     setUseUnderscoreSetJmp(false);
114     setUseUnderscoreLongJmp(false);
115   } else if (Subtarget->isTargetMingw()) {
116     // MS runtime is weird: it exports _setjmp, but longjmp!
117     setUseUnderscoreSetJmp(true);
118     setUseUnderscoreLongJmp(false);
119   } else {
120     setUseUnderscoreSetJmp(true);
121     setUseUnderscoreLongJmp(true);
122   }
123
124   // Set up the register classes.
125   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
126   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
127   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
128   if (Subtarget->is64Bit())
129     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
130
131   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
132
133   // We don't accept any truncstore of integer registers.
134   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
135   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
136   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
137   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
140
141   // SETOEQ and SETUNE require checking two conditions.
142   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
148
149   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
150   // operation.
151   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
152   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
153   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
154
155   if (Subtarget->is64Bit()) {
156     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
157     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
158   } else if (!UseSoftFloat) {
159     // We have an algorithm for SSE2->double, and we turn this into a
160     // 64-bit FILD followed by conditional FADD for other targets.
161     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
162     // We have an algorithm for SSE2, and we turn this into a 64-bit
163     // FILD for other targets.
164     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
165   }
166
167   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
168   // this operation.
169   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
170   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
171
172   if (!UseSoftFloat) {
173     // SSE has no i16 to fp conversion, only i32
174     if (X86ScalarSSEf32) {
175       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
176       // f32 and f64 cases are Legal, f80 case is not
177       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
178     } else {
179       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
180       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
181     }
182   } else {
183     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
184     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
185   }
186
187   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
188   // are Legal, f80 is custom lowered.
189   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
190   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
191
192   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
193   // this operation.
194   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
195   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
196
197   if (X86ScalarSSEf32) {
198     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
199     // f32 and f64 cases are Legal, f80 case is not
200     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
201   } else {
202     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
203     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
204   }
205
206   // Handle FP_TO_UINT by promoting the destination to a larger signed
207   // conversion.
208   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
209   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
210   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
211
212   if (Subtarget->is64Bit()) {
213     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
214     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
215   } else if (!UseSoftFloat) {
216     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
217       // Expand FP_TO_UINT into a select.
218       // FIXME: We would like to use a Custom expander here eventually to do
219       // the optimal thing for SSE vs. the default expansion in the legalizer.
220       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
221     else
222       // With SSE3 we can use fisttpll to convert to a signed i64; without
223       // SSE, we're stuck with a fistpll.
224       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
225   }
226
227   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
228   if (!X86ScalarSSEf64) {
229     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
230     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
231     if (Subtarget->is64Bit()) {
232       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
233       // Without SSE, i64->f64 goes through memory.
234       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
235     }
236   }
237
238   // Scalar integer divide and remainder are lowered to use operations that
239   // produce two results, to match the available instructions. This exposes
240   // the two-result form to trivial CSE, which is able to combine x/y and x%y
241   // into a single instruction.
242   //
243   // Scalar integer multiply-high is also lowered to use two-result
244   // operations, to match the available instructions. However, plain multiply
245   // (low) operations are left as Legal, as there are single-result
246   // instructions for this in x86. Using the two-result multiply instructions
247   // when both high and low results are needed must be arranged by dagcombine.
248   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
249   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
250   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
251   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
252   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
253   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
254   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
255   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
256   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
257   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
258   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
259   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
260   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
261   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
262   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
263   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
264   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
265   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
266   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
267   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
268   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
269   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
270   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
271   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
272
273   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
274   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
275   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
276   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
277   if (Subtarget->is64Bit())
278     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
279   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
280   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
281   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
282   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
283   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
284   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
285   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
286   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
287
288   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
289   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
290   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
291   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
292   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
293   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
294   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
295   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
296   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
297   if (Subtarget->is64Bit()) {
298     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
299     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
300     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
301   }
302
303   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
304   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
305
306   // These should be promoted to a larger select which is supported.
307   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
308   // X86 wants to expand cmov itself.
309   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
310   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
311   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
312   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
313   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
314   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
315   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
316   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
317   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
318   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
320   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
323     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
324   }
325   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
326
327   // Darwin ABI issue.
328   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
329   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
330   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
331   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
332   if (Subtarget->is64Bit())
333     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
335   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
338     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
339     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
340     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
341     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
342   }
343   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
345   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
346   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
349     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
350     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasSSE1())
354     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
355
356   // We may not have a libcall for MEMBARRIER so we should lower this.
357   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
358
359   // On X86 and X86-64, atomic operations are lowered to locked instructions.
360   // Locked instructions, in turn, have implicit fence semantics (all memory
361   // operations are flushed before issuing the locked instruction, and they
362   // are not buffered), so we can fold away the common pattern of
363   // fence-atomic-fence.
364   setShouldFoldAtomicFences(true);
365
366   // Expand certain atomics
367   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
371
372   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
376
377   if (!Subtarget->is64Bit()) {
378     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
385   }
386
387   // FIXME - use subtarget debug flags
388   if (!Subtarget->isTargetDarwin() &&
389       !Subtarget->isTargetELF() &&
390       !Subtarget->isTargetCygMing()) {
391     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
392   }
393
394   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
396   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
398   if (Subtarget->is64Bit()) {
399     setExceptionPointerRegister(X86::RAX);
400     setExceptionSelectorRegister(X86::RDX);
401   } else {
402     setExceptionPointerRegister(X86::EAX);
403     setExceptionSelectorRegister(X86::EDX);
404   }
405   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
407
408   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
409
410   setOperationAction(ISD::TRAP, MVT::Other, Legal);
411
412   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
414   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
417     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
418   } else {
419     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
420     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
421   }
422
423   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
424   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
425   if (Subtarget->is64Bit())
426     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
428     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
429   else
430     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
431
432   if (!UseSoftFloat && X86ScalarSSEf64) {
433     // f32 and f64 use SSE.
434     // Set up the FP register classes.
435     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
437
438     // Use ANDPD to simulate FABS.
439     setOperationAction(ISD::FABS , MVT::f64, Custom);
440     setOperationAction(ISD::FABS , MVT::f32, Custom);
441
442     // Use XORP to simulate FNEG.
443     setOperationAction(ISD::FNEG , MVT::f64, Custom);
444     setOperationAction(ISD::FNEG , MVT::f32, Custom);
445
446     // Use ANDPD and ORPD to simulate FCOPYSIGN.
447     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
449
450     // We don't support sin/cos/fmod
451     setOperationAction(ISD::FSIN , MVT::f64, Expand);
452     setOperationAction(ISD::FCOS , MVT::f64, Expand);
453     setOperationAction(ISD::FSIN , MVT::f32, Expand);
454     setOperationAction(ISD::FCOS , MVT::f32, Expand);
455
456     // Expand FP immediates into loads from the stack, except for the special
457     // cases we handle.
458     addLegalFPImmediate(APFloat(+0.0)); // xorpd
459     addLegalFPImmediate(APFloat(+0.0f)); // xorps
460   } else if (!UseSoftFloat && X86ScalarSSEf32) {
461     // Use SSE for f32, x87 for f64.
462     // Set up the FP register classes.
463     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465
466     // Use ANDPS to simulate FABS.
467     setOperationAction(ISD::FABS , MVT::f32, Custom);
468
469     // Use XORP to simulate FNEG.
470     setOperationAction(ISD::FNEG , MVT::f32, Custom);
471
472     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
473
474     // Use ANDPS and ORPS to simulate FCOPYSIGN.
475     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
477
478     // We don't support sin/cos/fmod
479     setOperationAction(ISD::FSIN , MVT::f32, Expand);
480     setOperationAction(ISD::FCOS , MVT::f32, Expand);
481
482     // Special cases we handle for FP constants.
483     addLegalFPImmediate(APFloat(+0.0f)); // xorps
484     addLegalFPImmediate(APFloat(+0.0)); // FLD0
485     addLegalFPImmediate(APFloat(+1.0)); // FLD1
486     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
488
489     if (!UnsafeFPMath) {
490       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
491       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
492     }
493   } else if (!UseSoftFloat) {
494     // f32 and f64 in x87.
495     // Set up the FP register classes.
496     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
498
499     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
500     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
501     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
503
504     if (!UnsafeFPMath) {
505       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
506       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
507     }
508     addLegalFPImmediate(APFloat(+0.0)); // FLD0
509     addLegalFPImmediate(APFloat(+1.0)); // FLD1
510     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
516   }
517
518   // Long double always uses X87.
519   if (!UseSoftFloat) {
520     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
522     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
523     {
524       bool ignored;
525       APFloat TmpFlt(+0.0);
526       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527                      &ignored);
528       addLegalFPImmediate(TmpFlt);  // FLD0
529       TmpFlt.changeSign();
530       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
531       APFloat TmpFlt2(+1.0);
532       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
533                       &ignored);
534       addLegalFPImmediate(TmpFlt2);  // FLD1
535       TmpFlt2.changeSign();
536       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
537     }
538
539     if (!UnsafeFPMath) {
540       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
541       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
542     }
543   }
544
545   // Always use a library call for pow.
546   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
547   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
548   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
549
550   setOperationAction(ISD::FLOG, MVT::f80, Expand);
551   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553   setOperationAction(ISD::FEXP, MVT::f80, Expand);
554   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
555
556   // First set operation action for all vector types to either promote
557   // (for widening) or expand (for scalarization). Then we will selectively
558   // turn on ones that can be effectively codegen'd.
559   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
614     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616       setTruncStoreAction((MVT::SimpleValueType)VT,
617                           (MVT::SimpleValueType)InnerVT, Expand);
618     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
621   }
622
623   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624   // with -msoft-float, disable use of MMX as well.
625   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
627     // No operations on x86mmx supported, everything uses intrinsics.
628   }
629
630   // MMX-sized vectors (other than x86mmx) are expected to be expanded
631   // into smaller operations.
632   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
633   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
634   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
635   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
636   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
637   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
638   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
639   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
640   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
641   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
642   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
643   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
644   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
645   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
646   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
647   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
648   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
649   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
650   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
651   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
652   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
653   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
654   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
655   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
656   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
657   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
658   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
659   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
660   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
661
662   if (!UseSoftFloat && Subtarget->hasSSE1()) {
663     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
664
665     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
666     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
667     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
668     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
669     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
670     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
671     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
674     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
675     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
676     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
677   }
678
679   if (!UseSoftFloat && Subtarget->hasSSE2()) {
680     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
681
682     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
683     // registers cannot be used even for integer operations.
684     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
685     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
686     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
687     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
688
689     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
690     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
691     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
692     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
693     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
694     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
695     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
696     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
697     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
698     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
699     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
700     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
701     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
702     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
703     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
704     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
705
706     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
707     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
708     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
709     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
710
711     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
712     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
713     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
714     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
715     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
716
717     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
718     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
719     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
720     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
721     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
722
723     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
724     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
725       EVT VT = (MVT::SimpleValueType)i;
726       // Do not attempt to custom lower non-power-of-2 vectors
727       if (!isPowerOf2_32(VT.getVectorNumElements()))
728         continue;
729       // Do not attempt to custom lower non-128-bit vectors
730       if (!VT.is128BitVector())
731         continue;
732       setOperationAction(ISD::BUILD_VECTOR,
733                          VT.getSimpleVT().SimpleTy, Custom);
734       setOperationAction(ISD::VECTOR_SHUFFLE,
735                          VT.getSimpleVT().SimpleTy, Custom);
736       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
737                          VT.getSimpleVT().SimpleTy, Custom);
738     }
739
740     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
741     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
742     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
743     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
744     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
746
747     if (Subtarget->is64Bit()) {
748       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
749       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
750     }
751
752     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
753     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
754       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
755       EVT VT = SVT;
756
757       // Do not attempt to promote non-128-bit vectors
758       if (!VT.is128BitVector())
759         continue;
760
761       setOperationAction(ISD::AND,    SVT, Promote);
762       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
763       setOperationAction(ISD::OR,     SVT, Promote);
764       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
765       setOperationAction(ISD::XOR,    SVT, Promote);
766       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
767       setOperationAction(ISD::LOAD,   SVT, Promote);
768       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
769       setOperationAction(ISD::SELECT, SVT, Promote);
770       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
771     }
772
773     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
774
775     // Custom lower v2i64 and v2f64 selects.
776     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
777     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
778     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
779     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
780
781     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
782     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
783   }
784
785   if (Subtarget->hasSSE41()) {
786     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
787     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
788     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
789     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
790     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
791     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
792     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
793     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
794     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
795     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
796
797     // FIXME: Do we need to handle scalar-to-vector here?
798     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
799
800     // Can turn SHL into an integer multiply.
801     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
802     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
803
804     // i8 and i16 vectors are custom , because the source register and source
805     // source memory operand types are not the same width.  f32 vectors are
806     // custom since the immediate controlling the insert encodes additional
807     // information.
808     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
809     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
810     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
811     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
812
813     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
814     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
815     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
816     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
817
818     if (Subtarget->is64Bit()) {
819       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
820       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
821     }
822   }
823
824   if (Subtarget->hasSSE42()) {
825     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
826   }
827
828   if (!UseSoftFloat && Subtarget->hasAVX()) {
829     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
830     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
831     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
832     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
833     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
834
835     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
836     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
837     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
838     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
839     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
840     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
841     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
842     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
843     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
844     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
845     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
846     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
847     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
848     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
849     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
850
851     // Operations to consider commented out -v16i16 v32i8
852     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
853     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
854     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
855     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
856     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
857     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
858     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
859     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
860     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
861     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
862     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
863     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
864     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
865     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
866
867     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
868     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
869     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
870     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
871
872     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
873     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
874     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
877
878     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
879     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
880     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
881     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
883     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
884
885 #if 0
886     // Not sure we want to do this since there are no 256-bit integer
887     // operations in AVX
888
889     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
890     // This includes 256-bit vectors
891     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
892       EVT VT = (MVT::SimpleValueType)i;
893
894       // Do not attempt to custom lower non-power-of-2 vectors
895       if (!isPowerOf2_32(VT.getVectorNumElements()))
896         continue;
897
898       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
899       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
900       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
901     }
902
903     if (Subtarget->is64Bit()) {
904       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
906     }
907 #endif
908
909 #if 0
910     // Not sure we want to do this since there are no 256-bit integer
911     // operations in AVX
912
913     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
914     // Including 256-bit vectors
915     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
916       EVT VT = (MVT::SimpleValueType)i;
917
918       if (!VT.is256BitVector()) {
919         continue;
920       }
921       setOperationAction(ISD::AND,    VT, Promote);
922       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
923       setOperationAction(ISD::OR,     VT, Promote);
924       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
925       setOperationAction(ISD::XOR,    VT, Promote);
926       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
927       setOperationAction(ISD::LOAD,   VT, Promote);
928       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
929       setOperationAction(ISD::SELECT, VT, Promote);
930       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
931     }
932
933     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
934 #endif
935   }
936
937   // We want to custom lower some of our intrinsics.
938   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
939
940   // Add/Sub/Mul with overflow operations are custom lowered.
941   setOperationAction(ISD::SADDO, MVT::i32, Custom);
942   setOperationAction(ISD::UADDO, MVT::i32, Custom);
943   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
944   setOperationAction(ISD::USUBO, MVT::i32, Custom);
945   setOperationAction(ISD::SMULO, MVT::i32, Custom);
946
947   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
948   // handle type legalization for these operations here.
949   //
950   // FIXME: We really should do custom legalization for addition and
951   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
952   // than generic legalization for 64-bit multiplication-with-overflow, though.
953   if (Subtarget->is64Bit()) {
954     setOperationAction(ISD::SADDO, MVT::i64, Custom);
955     setOperationAction(ISD::UADDO, MVT::i64, Custom);
956     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
957     setOperationAction(ISD::USUBO, MVT::i64, Custom);
958     setOperationAction(ISD::SMULO, MVT::i64, Custom);
959   }
960
961   if (!Subtarget->is64Bit()) {
962     // These libcalls are not available in 32-bit.
963     setLibcallName(RTLIB::SHL_I128, 0);
964     setLibcallName(RTLIB::SRL_I128, 0);
965     setLibcallName(RTLIB::SRA_I128, 0);
966   }
967
968   // We have target-specific dag combine patterns for the following nodes:
969   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
970   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
971   setTargetDAGCombine(ISD::BUILD_VECTOR);
972   setTargetDAGCombine(ISD::SELECT);
973   setTargetDAGCombine(ISD::SHL);
974   setTargetDAGCombine(ISD::SRA);
975   setTargetDAGCombine(ISD::SRL);
976   setTargetDAGCombine(ISD::OR);
977   setTargetDAGCombine(ISD::STORE);
978   setTargetDAGCombine(ISD::ZERO_EXTEND);
979   if (Subtarget->is64Bit())
980     setTargetDAGCombine(ISD::MUL);
981
982   computeRegisterProperties();
983
984   // FIXME: These should be based on subtarget info. Plus, the values should
985   // be smaller when we are in optimizing for size mode.
986   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
987   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
988   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
989   setPrefLoopAlignment(16);
990   benefitFromCodePlacementOpt = true;
991 }
992
993
994 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
995   return MVT::i8;
996 }
997
998
999 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1000 /// the desired ByVal argument alignment.
1001 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1002   if (MaxAlign == 16)
1003     return;
1004   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1005     if (VTy->getBitWidth() == 128)
1006       MaxAlign = 16;
1007   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1008     unsigned EltAlign = 0;
1009     getMaxByValAlign(ATy->getElementType(), EltAlign);
1010     if (EltAlign > MaxAlign)
1011       MaxAlign = EltAlign;
1012   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1013     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1014       unsigned EltAlign = 0;
1015       getMaxByValAlign(STy->getElementType(i), EltAlign);
1016       if (EltAlign > MaxAlign)
1017         MaxAlign = EltAlign;
1018       if (MaxAlign == 16)
1019         break;
1020     }
1021   }
1022   return;
1023 }
1024
1025 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1026 /// function arguments in the caller parameter area. For X86, aggregates
1027 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1028 /// are at 4-byte boundaries.
1029 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1030   if (Subtarget->is64Bit()) {
1031     // Max of 8 and alignment of type.
1032     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1033     if (TyAlign > 8)
1034       return TyAlign;
1035     return 8;
1036   }
1037
1038   unsigned Align = 4;
1039   if (Subtarget->hasSSE1())
1040     getMaxByValAlign(Ty, Align);
1041   return Align;
1042 }
1043
1044 /// getOptimalMemOpType - Returns the target specific optimal type for load
1045 /// and store operations as a result of memset, memcpy, and memmove
1046 /// lowering. If DstAlign is zero that means it's safe to destination
1047 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1048 /// means there isn't a need to check it against alignment requirement,
1049 /// probably because the source does not need to be loaded. If
1050 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1051 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1052 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1053 /// constant so it does not need to be loaded.
1054 /// It returns EVT::Other if the type should be determined using generic
1055 /// target-independent logic.
1056 EVT
1057 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1058                                        unsigned DstAlign, unsigned SrcAlign,
1059                                        bool NonScalarIntSafe,
1060                                        bool MemcpyStrSrc,
1061                                        MachineFunction &MF) const {
1062   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1063   // linux.  This is because the stack realignment code can't handle certain
1064   // cases like PR2962.  This should be removed when PR2962 is fixed.
1065   const Function *F = MF.getFunction();
1066   if (NonScalarIntSafe &&
1067       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1068     if (Size >= 16 &&
1069         (Subtarget->isUnalignedMemAccessFast() ||
1070          ((DstAlign == 0 || DstAlign >= 16) &&
1071           (SrcAlign == 0 || SrcAlign >= 16))) &&
1072         Subtarget->getStackAlignment() >= 16) {
1073       if (Subtarget->hasSSE2())
1074         return MVT::v4i32;
1075       if (Subtarget->hasSSE1())
1076         return MVT::v4f32;
1077     } else if (!MemcpyStrSrc && Size >= 8 &&
1078                !Subtarget->is64Bit() &&
1079                Subtarget->getStackAlignment() >= 8 &&
1080                Subtarget->hasSSE2()) {
1081       // Do not use f64 to lower memcpy if source is string constant. It's
1082       // better to use i32 to avoid the loads.
1083       return MVT::f64;
1084     }
1085   }
1086   if (Subtarget->is64Bit() && Size >= 8)
1087     return MVT::i64;
1088   return MVT::i32;
1089 }
1090
1091 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1092 /// current function.  The returned value is a member of the
1093 /// MachineJumpTableInfo::JTEntryKind enum.
1094 unsigned X86TargetLowering::getJumpTableEncoding() const {
1095   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1096   // symbol.
1097   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1098       Subtarget->isPICStyleGOT())
1099     return MachineJumpTableInfo::EK_Custom32;
1100
1101   // Otherwise, use the normal jump table encoding heuristics.
1102   return TargetLowering::getJumpTableEncoding();
1103 }
1104
1105 const MCExpr *
1106 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1107                                              const MachineBasicBlock *MBB,
1108                                              unsigned uid,MCContext &Ctx) const{
1109   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1110          Subtarget->isPICStyleGOT());
1111   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1112   // entries.
1113   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1114                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1115 }
1116
1117 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1118 /// jumptable.
1119 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1120                                                     SelectionDAG &DAG) const {
1121   if (!Subtarget->is64Bit())
1122     // This doesn't have DebugLoc associated with it, but is not really the
1123     // same as a Register.
1124     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1125   return Table;
1126 }
1127
1128 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1129 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1130 /// MCExpr.
1131 const MCExpr *X86TargetLowering::
1132 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1133                              MCContext &Ctx) const {
1134   // X86-64 uses RIP relative addressing based on the jump table label.
1135   if (Subtarget->isPICStyleRIPRel())
1136     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1137
1138   // Otherwise, the reference is relative to the PIC base.
1139   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1140 }
1141
1142 /// getFunctionAlignment - Return the Log2 alignment of this function.
1143 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1144   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1145 }
1146
1147 std::pair<const TargetRegisterClass*, uint8_t>
1148 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1149   const TargetRegisterClass *RRC = 0;
1150   uint8_t Cost = 1;
1151   switch (VT.getSimpleVT().SimpleTy) {
1152   default:
1153     return TargetLowering::findRepresentativeClass(VT);
1154   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1155     RRC = (Subtarget->is64Bit()
1156            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1157     break;
1158   case MVT::x86mmx:
1159     RRC = X86::VR64RegisterClass;
1160     break;
1161   case MVT::f32: case MVT::f64:
1162   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1163   case MVT::v4f32: case MVT::v2f64:
1164   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1165   case MVT::v4f64:
1166     RRC = X86::VR128RegisterClass;
1167     break;
1168   }
1169   return std::make_pair(RRC, Cost);
1170 }
1171
1172 unsigned
1173 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1174                                        MachineFunction &MF) const {
1175   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1176
1177   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1178   switch (RC->getID()) {
1179   default:
1180     return 0;
1181   case X86::GR32RegClassID:
1182     return 4 - FPDiff;
1183   case X86::GR64RegClassID:
1184     return 8 - FPDiff;
1185   case X86::VR128RegClassID:
1186     return Subtarget->is64Bit() ? 10 : 4;
1187   case X86::VR64RegClassID:
1188     return 4;
1189   }
1190 }
1191
1192 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1193                                                unsigned &Offset) const {
1194   if (!Subtarget->isTargetLinux())
1195     return false;
1196
1197   if (Subtarget->is64Bit()) {
1198     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1199     Offset = 0x28;
1200     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1201       AddressSpace = 256;
1202     else
1203       AddressSpace = 257;
1204   } else {
1205     // %gs:0x14 on i386
1206     Offset = 0x14;
1207     AddressSpace = 256;
1208   }
1209   return true;
1210 }
1211
1212
1213 //===----------------------------------------------------------------------===//
1214 //               Return Value Calling Convention Implementation
1215 //===----------------------------------------------------------------------===//
1216
1217 #include "X86GenCallingConv.inc"
1218
1219 bool
1220 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1221                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1222                         LLVMContext &Context) const {
1223   SmallVector<CCValAssign, 16> RVLocs;
1224   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1225                  RVLocs, Context);
1226   return CCInfo.CheckReturn(Outs, RetCC_X86);
1227 }
1228
1229 SDValue
1230 X86TargetLowering::LowerReturn(SDValue Chain,
1231                                CallingConv::ID CallConv, bool isVarArg,
1232                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1233                                const SmallVectorImpl<SDValue> &OutVals,
1234                                DebugLoc dl, SelectionDAG &DAG) const {
1235   MachineFunction &MF = DAG.getMachineFunction();
1236   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1237
1238   SmallVector<CCValAssign, 16> RVLocs;
1239   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1240                  RVLocs, *DAG.getContext());
1241   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1242
1243   // Add the regs to the liveout set for the function.
1244   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1245   for (unsigned i = 0; i != RVLocs.size(); ++i)
1246     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1247       MRI.addLiveOut(RVLocs[i].getLocReg());
1248
1249   SDValue Flag;
1250
1251   SmallVector<SDValue, 6> RetOps;
1252   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1253   // Operand #1 = Bytes To Pop
1254   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1255                    MVT::i16));
1256
1257   // Copy the result values into the output registers.
1258   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1259     CCValAssign &VA = RVLocs[i];
1260     assert(VA.isRegLoc() && "Can only return in registers!");
1261     SDValue ValToCopy = OutVals[i];
1262     EVT ValVT = ValToCopy.getValueType();
1263
1264     // If this is x86-64, and we disabled SSE, we can't return FP values,
1265     // or SSE or MMX vectors.
1266     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1267          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1268           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1269       report_fatal_error("SSE register return with SSE disabled");
1270     }
1271     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1272     // llvm-gcc has never done it right and no one has noticed, so this
1273     // should be OK for now.
1274     if (ValVT == MVT::f64 &&
1275         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1276       report_fatal_error("SSE2 register return with SSE2 disabled");
1277
1278     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1279     // the RET instruction and handled by the FP Stackifier.
1280     if (VA.getLocReg() == X86::ST0 ||
1281         VA.getLocReg() == X86::ST1) {
1282       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1283       // change the value to the FP stack register class.
1284       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1285         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1286       RetOps.push_back(ValToCopy);
1287       // Don't emit a copytoreg.
1288       continue;
1289     }
1290
1291     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1292     // which is returned in RAX / RDX.
1293     if (Subtarget->is64Bit()) {
1294       if (ValVT == MVT::x86mmx) {
1295         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1296           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1297           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1298                                   ValToCopy);
1299           // If we don't have SSE2 available, convert to v4f32 so the generated
1300           // register is legal.
1301           if (!Subtarget->hasSSE2())
1302             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1303         }
1304       }
1305     }
1306
1307     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1308     Flag = Chain.getValue(1);
1309   }
1310
1311   // The x86-64 ABI for returning structs by value requires that we copy
1312   // the sret argument into %rax for the return. We saved the argument into
1313   // a virtual register in the entry block, so now we copy the value out
1314   // and into %rax.
1315   if (Subtarget->is64Bit() &&
1316       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1317     MachineFunction &MF = DAG.getMachineFunction();
1318     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1319     unsigned Reg = FuncInfo->getSRetReturnReg();
1320     assert(Reg &&
1321            "SRetReturnReg should have been set in LowerFormalArguments().");
1322     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1323
1324     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1325     Flag = Chain.getValue(1);
1326
1327     // RAX now acts like a return value.
1328     MRI.addLiveOut(X86::RAX);
1329   }
1330
1331   RetOps[0] = Chain;  // Update chain.
1332
1333   // Add the flag if we have it.
1334   if (Flag.getNode())
1335     RetOps.push_back(Flag);
1336
1337   return DAG.getNode(X86ISD::RET_FLAG, dl,
1338                      MVT::Other, &RetOps[0], RetOps.size());
1339 }
1340
1341 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1342   if (N->getNumValues() != 1)
1343     return false;
1344   if (!N->hasNUsesOfValue(1, 0))
1345     return false;
1346
1347   SDNode *Copy = *N->use_begin();
1348   if (Copy->getOpcode() != ISD::CopyToReg)
1349     return false;
1350   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1351        UI != UE; ++UI)
1352     if (UI->getOpcode() != X86ISD::RET_FLAG)
1353       return false;
1354
1355   return true;
1356 }
1357
1358 /// LowerCallResult - Lower the result values of a call into the
1359 /// appropriate copies out of appropriate physical registers.
1360 ///
1361 SDValue
1362 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1363                                    CallingConv::ID CallConv, bool isVarArg,
1364                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1365                                    DebugLoc dl, SelectionDAG &DAG,
1366                                    SmallVectorImpl<SDValue> &InVals) const {
1367
1368   // Assign locations to each value returned by this call.
1369   SmallVector<CCValAssign, 16> RVLocs;
1370   bool Is64Bit = Subtarget->is64Bit();
1371   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1372                  RVLocs, *DAG.getContext());
1373   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1374
1375   // Copy all of the result registers out of their specified physreg.
1376   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1377     CCValAssign &VA = RVLocs[i];
1378     EVT CopyVT = VA.getValVT();
1379
1380     // If this is x86-64, and we disabled SSE, we can't return FP values
1381     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1382         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1383       report_fatal_error("SSE register return with SSE disabled");
1384     }
1385
1386     SDValue Val;
1387
1388     // If this is a call to a function that returns an fp value on the floating
1389     // point stack, we must guarantee the the value is popped from the stack, so
1390     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1391     // if the return value is not used. We use the FpGET_ST0 instructions
1392     // instead.
1393     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1394       // If we prefer to use the value in xmm registers, copy it out as f80 and
1395       // use a truncate to move it from fp stack reg to xmm reg.
1396       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1397       bool isST0 = VA.getLocReg() == X86::ST0;
1398       unsigned Opc = 0;
1399       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1400       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1401       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1402       SDValue Ops[] = { Chain, InFlag };
1403       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1404                                          Ops, 2), 1);
1405       Val = Chain.getValue(0);
1406
1407       // Round the f80 to the right size, which also moves it to the appropriate
1408       // xmm register.
1409       if (CopyVT != VA.getValVT())
1410         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1411                           // This truncation won't change the value.
1412                           DAG.getIntPtrConstant(1));
1413     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1414       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1415       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1416         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1417                                    MVT::v2i64, InFlag).getValue(1);
1418         Val = Chain.getValue(0);
1419         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1420                           Val, DAG.getConstant(0, MVT::i64));
1421       } else {
1422         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1423                                    MVT::i64, InFlag).getValue(1);
1424         Val = Chain.getValue(0);
1425       }
1426       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1427     } else {
1428       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1429                                  CopyVT, InFlag).getValue(1);
1430       Val = Chain.getValue(0);
1431     }
1432     InFlag = Chain.getValue(2);
1433     InVals.push_back(Val);
1434   }
1435
1436   return Chain;
1437 }
1438
1439
1440 //===----------------------------------------------------------------------===//
1441 //                C & StdCall & Fast Calling Convention implementation
1442 //===----------------------------------------------------------------------===//
1443 //  StdCall calling convention seems to be standard for many Windows' API
1444 //  routines and around. It differs from C calling convention just a little:
1445 //  callee should clean up the stack, not caller. Symbols should be also
1446 //  decorated in some fancy way :) It doesn't support any vector arguments.
1447 //  For info on fast calling convention see Fast Calling Convention (tail call)
1448 //  implementation LowerX86_32FastCCCallTo.
1449
1450 /// CallIsStructReturn - Determines whether a call uses struct return
1451 /// semantics.
1452 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1453   if (Outs.empty())
1454     return false;
1455
1456   return Outs[0].Flags.isSRet();
1457 }
1458
1459 /// ArgsAreStructReturn - Determines whether a function uses struct
1460 /// return semantics.
1461 static bool
1462 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1463   if (Ins.empty())
1464     return false;
1465
1466   return Ins[0].Flags.isSRet();
1467 }
1468
1469 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1470 /// by "Src" to address "Dst" with size and alignment information specified by
1471 /// the specific parameter attribute. The copy will be passed as a byval
1472 /// function parameter.
1473 static SDValue
1474 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1475                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1476                           DebugLoc dl) {
1477   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1478
1479   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1480                        /*isVolatile*/false, /*AlwaysInline=*/true,
1481                        MachinePointerInfo(), MachinePointerInfo());
1482 }
1483
1484 /// IsTailCallConvention - Return true if the calling convention is one that
1485 /// supports tail call optimization.
1486 static bool IsTailCallConvention(CallingConv::ID CC) {
1487   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1488 }
1489
1490 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1491 /// a tailcall target by changing its ABI.
1492 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1493   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1494 }
1495
1496 SDValue
1497 X86TargetLowering::LowerMemArgument(SDValue Chain,
1498                                     CallingConv::ID CallConv,
1499                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1500                                     DebugLoc dl, SelectionDAG &DAG,
1501                                     const CCValAssign &VA,
1502                                     MachineFrameInfo *MFI,
1503                                     unsigned i) const {
1504   // Create the nodes corresponding to a load from this parameter slot.
1505   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1506   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1507   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1508   EVT ValVT;
1509
1510   // If value is passed by pointer we have address passed instead of the value
1511   // itself.
1512   if (VA.getLocInfo() == CCValAssign::Indirect)
1513     ValVT = VA.getLocVT();
1514   else
1515     ValVT = VA.getValVT();
1516
1517   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1518   // changed with more analysis.
1519   // In case of tail call optimization mark all arguments mutable. Since they
1520   // could be overwritten by lowering of arguments in case of a tail call.
1521   if (Flags.isByVal()) {
1522     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1523                                     VA.getLocMemOffset(), isImmutable);
1524     return DAG.getFrameIndex(FI, getPointerTy());
1525   } else {
1526     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1527                                     VA.getLocMemOffset(), isImmutable);
1528     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1529     return DAG.getLoad(ValVT, dl, Chain, FIN,
1530                        MachinePointerInfo::getFixedStack(FI),
1531                        false, false, 0);
1532   }
1533 }
1534
1535 SDValue
1536 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1537                                         CallingConv::ID CallConv,
1538                                         bool isVarArg,
1539                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1540                                         DebugLoc dl,
1541                                         SelectionDAG &DAG,
1542                                         SmallVectorImpl<SDValue> &InVals)
1543                                           const {
1544   MachineFunction &MF = DAG.getMachineFunction();
1545   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1546
1547   const Function* Fn = MF.getFunction();
1548   if (Fn->hasExternalLinkage() &&
1549       Subtarget->isTargetCygMing() &&
1550       Fn->getName() == "main")
1551     FuncInfo->setForceFramePointer(true);
1552
1553   MachineFrameInfo *MFI = MF.getFrameInfo();
1554   bool Is64Bit = Subtarget->is64Bit();
1555   bool IsWin64 = Subtarget->isTargetWin64();
1556
1557   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1558          "Var args not supported with calling convention fastcc or ghc");
1559
1560   // Assign locations to all of the incoming arguments.
1561   SmallVector<CCValAssign, 16> ArgLocs;
1562   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1563                  ArgLocs, *DAG.getContext());
1564   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1565
1566   unsigned LastVal = ~0U;
1567   SDValue ArgValue;
1568   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1569     CCValAssign &VA = ArgLocs[i];
1570     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1571     // places.
1572     assert(VA.getValNo() != LastVal &&
1573            "Don't support value assigned to multiple locs yet");
1574     LastVal = VA.getValNo();
1575
1576     if (VA.isRegLoc()) {
1577       EVT RegVT = VA.getLocVT();
1578       TargetRegisterClass *RC = NULL;
1579       if (RegVT == MVT::i32)
1580         RC = X86::GR32RegisterClass;
1581       else if (Is64Bit && RegVT == MVT::i64)
1582         RC = X86::GR64RegisterClass;
1583       else if (RegVT == MVT::f32)
1584         RC = X86::FR32RegisterClass;
1585       else if (RegVT == MVT::f64)
1586         RC = X86::FR64RegisterClass;
1587       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1588         RC = X86::VR256RegisterClass;
1589       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1590         RC = X86::VR128RegisterClass;
1591       else if (RegVT == MVT::x86mmx)
1592         RC = X86::VR64RegisterClass;
1593       else
1594         llvm_unreachable("Unknown argument type!");
1595
1596       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1597       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1598
1599       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1600       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1601       // right size.
1602       if (VA.getLocInfo() == CCValAssign::SExt)
1603         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1604                                DAG.getValueType(VA.getValVT()));
1605       else if (VA.getLocInfo() == CCValAssign::ZExt)
1606         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1607                                DAG.getValueType(VA.getValVT()));
1608       else if (VA.getLocInfo() == CCValAssign::BCvt)
1609         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1610
1611       if (VA.isExtInLoc()) {
1612         // Handle MMX values passed in XMM regs.
1613         if (RegVT.isVector()) {
1614           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1615                                  ArgValue);
1616         } else
1617           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1618       }
1619     } else {
1620       assert(VA.isMemLoc());
1621       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1622     }
1623
1624     // If value is passed via pointer - do a load.
1625     if (VA.getLocInfo() == CCValAssign::Indirect)
1626       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1627                              MachinePointerInfo(), false, false, 0);
1628
1629     InVals.push_back(ArgValue);
1630   }
1631
1632   // The x86-64 ABI for returning structs by value requires that we copy
1633   // the sret argument into %rax for the return. Save the argument into
1634   // a virtual register so that we can access it from the return points.
1635   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1636     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1637     unsigned Reg = FuncInfo->getSRetReturnReg();
1638     if (!Reg) {
1639       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1640       FuncInfo->setSRetReturnReg(Reg);
1641     }
1642     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1643     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1644   }
1645
1646   unsigned StackSize = CCInfo.getNextStackOffset();
1647   // Align stack specially for tail calls.
1648   if (FuncIsMadeTailCallSafe(CallConv))
1649     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1650
1651   // If the function takes variable number of arguments, make a frame index for
1652   // the start of the first vararg value... for expansion of llvm.va_start.
1653   if (isVarArg) {
1654     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1655                     CallConv != CallingConv::X86_ThisCall))) {
1656       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1657     }
1658     if (Is64Bit) {
1659       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1660
1661       // FIXME: We should really autogenerate these arrays
1662       static const unsigned GPR64ArgRegsWin64[] = {
1663         X86::RCX, X86::RDX, X86::R8,  X86::R9
1664       };
1665       static const unsigned GPR64ArgRegs64Bit[] = {
1666         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1667       };
1668       static const unsigned XMMArgRegs64Bit[] = {
1669         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1670         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1671       };
1672       const unsigned *GPR64ArgRegs;
1673       unsigned NumXMMRegs = 0;
1674
1675       if (IsWin64) {
1676         // The XMM registers which might contain var arg parameters are shadowed
1677         // in their paired GPR.  So we only need to save the GPR to their home
1678         // slots.
1679         TotalNumIntRegs = 4;
1680         GPR64ArgRegs = GPR64ArgRegsWin64;
1681       } else {
1682         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1683         GPR64ArgRegs = GPR64ArgRegs64Bit;
1684
1685         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1686       }
1687       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1688                                                        TotalNumIntRegs);
1689
1690       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1691       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1692              "SSE register cannot be used when SSE is disabled!");
1693       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1694              "SSE register cannot be used when SSE is disabled!");
1695       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1696         // Kernel mode asks for SSE to be disabled, so don't push them
1697         // on the stack.
1698         TotalNumXMMRegs = 0;
1699
1700       if (IsWin64) {
1701         const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1702         // Get to the caller-allocated home save location.  Add 8 to account
1703         // for the return address.
1704         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1705         FuncInfo->setRegSaveFrameIndex(
1706           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1707         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1708       } else {
1709         // For X86-64, if there are vararg parameters that are passed via
1710         // registers, then we must store them to their spots on the stack so they
1711         // may be loaded by deferencing the result of va_next.
1712         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1713         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1714         FuncInfo->setRegSaveFrameIndex(
1715           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1716                                false));
1717       }
1718
1719       // Store the integer parameter registers.
1720       SmallVector<SDValue, 8> MemOps;
1721       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1722                                         getPointerTy());
1723       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1724       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1725         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1726                                   DAG.getIntPtrConstant(Offset));
1727         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1728                                      X86::GR64RegisterClass);
1729         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1730         SDValue Store =
1731           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1732                        MachinePointerInfo::getFixedStack(
1733                          FuncInfo->getRegSaveFrameIndex(), Offset),
1734                        false, false, 0);
1735         MemOps.push_back(Store);
1736         Offset += 8;
1737       }
1738
1739       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1740         // Now store the XMM (fp + vector) parameter registers.
1741         SmallVector<SDValue, 11> SaveXMMOps;
1742         SaveXMMOps.push_back(Chain);
1743
1744         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1745         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1746         SaveXMMOps.push_back(ALVal);
1747
1748         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1749                                FuncInfo->getRegSaveFrameIndex()));
1750         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1751                                FuncInfo->getVarArgsFPOffset()));
1752
1753         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1754           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1755                                        X86::VR128RegisterClass);
1756           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1757           SaveXMMOps.push_back(Val);
1758         }
1759         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1760                                      MVT::Other,
1761                                      &SaveXMMOps[0], SaveXMMOps.size()));
1762       }
1763
1764       if (!MemOps.empty())
1765         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1766                             &MemOps[0], MemOps.size());
1767     }
1768   }
1769
1770   // Some CCs need callee pop.
1771   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1772     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1773   } else {
1774     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1775     // If this is an sret function, the return should pop the hidden pointer.
1776     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1777       FuncInfo->setBytesToPopOnReturn(4);
1778   }
1779
1780   if (!Is64Bit) {
1781     // RegSaveFrameIndex is X86-64 only.
1782     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1783     if (CallConv == CallingConv::X86_FastCall ||
1784         CallConv == CallingConv::X86_ThisCall)
1785       // fastcc functions can't have varargs.
1786       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1787   }
1788
1789   return Chain;
1790 }
1791
1792 SDValue
1793 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1794                                     SDValue StackPtr, SDValue Arg,
1795                                     DebugLoc dl, SelectionDAG &DAG,
1796                                     const CCValAssign &VA,
1797                                     ISD::ArgFlagsTy Flags) const {
1798   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1799   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1800   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1801   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1802   if (Flags.isByVal())
1803     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1804
1805   return DAG.getStore(Chain, dl, Arg, PtrOff,
1806                       MachinePointerInfo::getStack(LocMemOffset),
1807                       false, false, 0);
1808 }
1809
1810 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1811 /// optimization is performed and it is required.
1812 SDValue
1813 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1814                                            SDValue &OutRetAddr, SDValue Chain,
1815                                            bool IsTailCall, bool Is64Bit,
1816                                            int FPDiff, DebugLoc dl) const {
1817   // Adjust the Return address stack slot.
1818   EVT VT = getPointerTy();
1819   OutRetAddr = getReturnAddressFrameIndex(DAG);
1820
1821   // Load the "old" Return address.
1822   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1823                            false, false, 0);
1824   return SDValue(OutRetAddr.getNode(), 1);
1825 }
1826
1827 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1828 /// optimization is performed and it is required (FPDiff!=0).
1829 static SDValue
1830 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1831                          SDValue Chain, SDValue RetAddrFrIdx,
1832                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1833   // Store the return address to the appropriate stack slot.
1834   if (!FPDiff) return Chain;
1835   // Calculate the new stack slot for the return address.
1836   int SlotSize = Is64Bit ? 8 : 4;
1837   int NewReturnAddrFI =
1838     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1839   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1840   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1841   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1842                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1843                        false, false, 0);
1844   return Chain;
1845 }
1846
1847 SDValue
1848 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1849                              CallingConv::ID CallConv, bool isVarArg,
1850                              bool &isTailCall,
1851                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1852                              const SmallVectorImpl<SDValue> &OutVals,
1853                              const SmallVectorImpl<ISD::InputArg> &Ins,
1854                              DebugLoc dl, SelectionDAG &DAG,
1855                              SmallVectorImpl<SDValue> &InVals) const {
1856   MachineFunction &MF = DAG.getMachineFunction();
1857   bool Is64Bit        = Subtarget->is64Bit();
1858   bool IsStructRet    = CallIsStructReturn(Outs);
1859   bool IsSibcall      = false;
1860
1861   if (isTailCall) {
1862     // Check if it's really possible to do a tail call.
1863     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1864                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1865                                                    Outs, OutVals, Ins, DAG);
1866
1867     // Sibcalls are automatically detected tailcalls which do not require
1868     // ABI changes.
1869     if (!GuaranteedTailCallOpt && isTailCall)
1870       IsSibcall = true;
1871
1872     if (isTailCall)
1873       ++NumTailCalls;
1874   }
1875
1876   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1877          "Var args not supported with calling convention fastcc or ghc");
1878
1879   // Analyze operands of the call, assigning locations to each operand.
1880   SmallVector<CCValAssign, 16> ArgLocs;
1881   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1882                  ArgLocs, *DAG.getContext());
1883   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1884
1885   // Get a count of how many bytes are to be pushed on the stack.
1886   unsigned NumBytes = CCInfo.getNextStackOffset();
1887   if (IsSibcall)
1888     // This is a sibcall. The memory operands are available in caller's
1889     // own caller's stack.
1890     NumBytes = 0;
1891   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1892     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1893
1894   int FPDiff = 0;
1895   if (isTailCall && !IsSibcall) {
1896     // Lower arguments at fp - stackoffset + fpdiff.
1897     unsigned NumBytesCallerPushed =
1898       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1899     FPDiff = NumBytesCallerPushed - NumBytes;
1900
1901     // Set the delta of movement of the returnaddr stackslot.
1902     // But only set if delta is greater than previous delta.
1903     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1904       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1905   }
1906
1907   if (!IsSibcall)
1908     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1909
1910   SDValue RetAddrFrIdx;
1911   // Load return adress for tail calls.
1912   if (isTailCall && FPDiff)
1913     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1914                                     Is64Bit, FPDiff, dl);
1915
1916   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1917   SmallVector<SDValue, 8> MemOpChains;
1918   SDValue StackPtr;
1919
1920   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1921   // of tail call optimization arguments are handle later.
1922   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1923     CCValAssign &VA = ArgLocs[i];
1924     EVT RegVT = VA.getLocVT();
1925     SDValue Arg = OutVals[i];
1926     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1927     bool isByVal = Flags.isByVal();
1928
1929     // Promote the value if needed.
1930     switch (VA.getLocInfo()) {
1931     default: llvm_unreachable("Unknown loc info!");
1932     case CCValAssign::Full: break;
1933     case CCValAssign::SExt:
1934       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1935       break;
1936     case CCValAssign::ZExt:
1937       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1938       break;
1939     case CCValAssign::AExt:
1940       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1941         // Special case: passing MMX values in XMM registers.
1942         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1943         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1944         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1945       } else
1946         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1947       break;
1948     case CCValAssign::BCvt:
1949       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1950       break;
1951     case CCValAssign::Indirect: {
1952       // Store the argument.
1953       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1954       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1955       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1956                            MachinePointerInfo::getFixedStack(FI),
1957                            false, false, 0);
1958       Arg = SpillSlot;
1959       break;
1960     }
1961     }
1962
1963     if (VA.isRegLoc()) {
1964       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1965       if (isVarArg && Subtarget->isTargetWin64()) {
1966         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1967         // shadow reg if callee is a varargs function.
1968         unsigned ShadowReg = 0;
1969         switch (VA.getLocReg()) {
1970         case X86::XMM0: ShadowReg = X86::RCX; break;
1971         case X86::XMM1: ShadowReg = X86::RDX; break;
1972         case X86::XMM2: ShadowReg = X86::R8; break;
1973         case X86::XMM3: ShadowReg = X86::R9; break;
1974         }
1975         if (ShadowReg)
1976           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1977       }
1978     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1979       assert(VA.isMemLoc());
1980       if (StackPtr.getNode() == 0)
1981         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1982       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1983                                              dl, DAG, VA, Flags));
1984     }
1985   }
1986
1987   if (!MemOpChains.empty())
1988     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1989                         &MemOpChains[0], MemOpChains.size());
1990
1991   // Build a sequence of copy-to-reg nodes chained together with token chain
1992   // and flag operands which copy the outgoing args into registers.
1993   SDValue InFlag;
1994   // Tail call byval lowering might overwrite argument registers so in case of
1995   // tail call optimization the copies to registers are lowered later.
1996   if (!isTailCall)
1997     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1998       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1999                                RegsToPass[i].second, InFlag);
2000       InFlag = Chain.getValue(1);
2001     }
2002
2003   if (Subtarget->isPICStyleGOT()) {
2004     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2005     // GOT pointer.
2006     if (!isTailCall) {
2007       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2008                                DAG.getNode(X86ISD::GlobalBaseReg,
2009                                            DebugLoc(), getPointerTy()),
2010                                InFlag);
2011       InFlag = Chain.getValue(1);
2012     } else {
2013       // If we are tail calling and generating PIC/GOT style code load the
2014       // address of the callee into ECX. The value in ecx is used as target of
2015       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2016       // for tail calls on PIC/GOT architectures. Normally we would just put the
2017       // address of GOT into ebx and then call target@PLT. But for tail calls
2018       // ebx would be restored (since ebx is callee saved) before jumping to the
2019       // target@PLT.
2020
2021       // Note: The actual moving to ECX is done further down.
2022       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2023       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2024           !G->getGlobal()->hasProtectedVisibility())
2025         Callee = LowerGlobalAddress(Callee, DAG);
2026       else if (isa<ExternalSymbolSDNode>(Callee))
2027         Callee = LowerExternalSymbol(Callee, DAG);
2028     }
2029   }
2030
2031   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2032     // From AMD64 ABI document:
2033     // For calls that may call functions that use varargs or stdargs
2034     // (prototype-less calls or calls to functions containing ellipsis (...) in
2035     // the declaration) %al is used as hidden argument to specify the number
2036     // of SSE registers used. The contents of %al do not need to match exactly
2037     // the number of registers, but must be an ubound on the number of SSE
2038     // registers used and is in the range 0 - 8 inclusive.
2039
2040     // Count the number of XMM registers allocated.
2041     static const unsigned XMMArgRegs[] = {
2042       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2044     };
2045     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2046     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2047            && "SSE registers cannot be used when SSE is disabled");
2048
2049     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2050                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2051     InFlag = Chain.getValue(1);
2052   }
2053
2054
2055   // For tail calls lower the arguments to the 'real' stack slot.
2056   if (isTailCall) {
2057     // Force all the incoming stack arguments to be loaded from the stack
2058     // before any new outgoing arguments are stored to the stack, because the
2059     // outgoing stack slots may alias the incoming argument stack slots, and
2060     // the alias isn't otherwise explicit. This is slightly more conservative
2061     // than necessary, because it means that each store effectively depends
2062     // on every argument instead of just those arguments it would clobber.
2063     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2064
2065     SmallVector<SDValue, 8> MemOpChains2;
2066     SDValue FIN;
2067     int FI = 0;
2068     // Do not flag preceeding copytoreg stuff together with the following stuff.
2069     InFlag = SDValue();
2070     if (GuaranteedTailCallOpt) {
2071       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2072         CCValAssign &VA = ArgLocs[i];
2073         if (VA.isRegLoc())
2074           continue;
2075         assert(VA.isMemLoc());
2076         SDValue Arg = OutVals[i];
2077         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2078         // Create frame index.
2079         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2080         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2081         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2082         FIN = DAG.getFrameIndex(FI, getPointerTy());
2083
2084         if (Flags.isByVal()) {
2085           // Copy relative to framepointer.
2086           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2087           if (StackPtr.getNode() == 0)
2088             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2089                                           getPointerTy());
2090           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2091
2092           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2093                                                            ArgChain,
2094                                                            Flags, DAG, dl));
2095         } else {
2096           // Store relative to framepointer.
2097           MemOpChains2.push_back(
2098             DAG.getStore(ArgChain, dl, Arg, FIN,
2099                          MachinePointerInfo::getFixedStack(FI),
2100                          false, false, 0));
2101         }
2102       }
2103     }
2104
2105     if (!MemOpChains2.empty())
2106       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2107                           &MemOpChains2[0], MemOpChains2.size());
2108
2109     // Copy arguments to their registers.
2110     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2111       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2112                                RegsToPass[i].second, InFlag);
2113       InFlag = Chain.getValue(1);
2114     }
2115     InFlag =SDValue();
2116
2117     // Store the return address to the appropriate stack slot.
2118     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2119                                      FPDiff, dl);
2120   }
2121
2122   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2123     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2124     // In the 64-bit large code model, we have to make all calls
2125     // through a register, since the call instruction's 32-bit
2126     // pc-relative offset may not be large enough to hold the whole
2127     // address.
2128   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2129     // If the callee is a GlobalAddress node (quite common, every direct call
2130     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2131     // it.
2132
2133     // We should use extra load for direct calls to dllimported functions in
2134     // non-JIT mode.
2135     const GlobalValue *GV = G->getGlobal();
2136     if (!GV->hasDLLImportLinkage()) {
2137       unsigned char OpFlags = 0;
2138
2139       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2140       // external symbols most go through the PLT in PIC mode.  If the symbol
2141       // has hidden or protected visibility, or if it is static or local, then
2142       // we don't need to use the PLT - we can directly call it.
2143       if (Subtarget->isTargetELF() &&
2144           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2145           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2146         OpFlags = X86II::MO_PLT;
2147       } else if (Subtarget->isPICStyleStubAny() &&
2148                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2149                  Subtarget->getDarwinVers() < 9) {
2150         // PC-relative references to external symbols should go through $stub,
2151         // unless we're building with the leopard linker or later, which
2152         // automatically synthesizes these stubs.
2153         OpFlags = X86II::MO_DARWIN_STUB;
2154       }
2155
2156       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2157                                           G->getOffset(), OpFlags);
2158     }
2159   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2160     unsigned char OpFlags = 0;
2161
2162     if (!isTailCall) {
2163       // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2164       // external symbols should go through the PLT.
2165       if (Subtarget->isTargetELF() &&
2166           getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2167         OpFlags = X86II::MO_PLT;
2168       } else if (Subtarget->isPICStyleStubAny() &&
2169                  Subtarget->getDarwinVers() < 9) {
2170         // PC-relative references to external symbols should go through $stub,
2171         // unless we're building with the leopard linker or later, which
2172         // automatically synthesizes these stubs.
2173         OpFlags = X86II::MO_DARWIN_STUB;
2174       }
2175     }
2176
2177     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2178                                          OpFlags);
2179   }
2180
2181   // Returns a chain & a flag for retval copy to use.
2182   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2183   SmallVector<SDValue, 8> Ops;
2184
2185   if (!IsSibcall && isTailCall) {
2186     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2187                            DAG.getIntPtrConstant(0, true), InFlag);
2188     InFlag = Chain.getValue(1);
2189   }
2190
2191   Ops.push_back(Chain);
2192   Ops.push_back(Callee);
2193
2194   if (isTailCall)
2195     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2196
2197   // Add argument registers to the end of the list so that they are known live
2198   // into the call.
2199   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2200     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2201                                   RegsToPass[i].second.getValueType()));
2202
2203   // Add an implicit use GOT pointer in EBX.
2204   if (!isTailCall && Subtarget->isPICStyleGOT())
2205     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2206
2207   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2208   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2209     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2210
2211   if (InFlag.getNode())
2212     Ops.push_back(InFlag);
2213
2214   if (isTailCall) {
2215     // We used to do:
2216     //// If this is the first return lowered for this function, add the regs
2217     //// to the liveout set for the function.
2218     // This isn't right, although it's probably harmless on x86; liveouts
2219     // should be computed from returns not tail calls.  Consider a void
2220     // function making a tail call to a function returning int.
2221     return DAG.getNode(X86ISD::TC_RETURN, dl,
2222                        NodeTys, &Ops[0], Ops.size());
2223   }
2224
2225   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2226   InFlag = Chain.getValue(1);
2227
2228   // Create the CALLSEQ_END node.
2229   unsigned NumBytesForCalleeToPush;
2230   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2231     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2232   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2233     // If this is a call to a struct-return function, the callee
2234     // pops the hidden struct pointer, so we have to push it back.
2235     // This is common for Darwin/X86, Linux & Mingw32 targets.
2236     NumBytesForCalleeToPush = 4;
2237   else
2238     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2239
2240   // Returns a flag for retval copy to use.
2241   if (!IsSibcall) {
2242     Chain = DAG.getCALLSEQ_END(Chain,
2243                                DAG.getIntPtrConstant(NumBytes, true),
2244                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2245                                                      true),
2246                                InFlag);
2247     InFlag = Chain.getValue(1);
2248   }
2249
2250   // Handle result values, copying them out of physregs into vregs that we
2251   // return.
2252   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2253                          Ins, dl, DAG, InVals);
2254 }
2255
2256
2257 //===----------------------------------------------------------------------===//
2258 //                Fast Calling Convention (tail call) implementation
2259 //===----------------------------------------------------------------------===//
2260
2261 //  Like std call, callee cleans arguments, convention except that ECX is
2262 //  reserved for storing the tail called function address. Only 2 registers are
2263 //  free for argument passing (inreg). Tail call optimization is performed
2264 //  provided:
2265 //                * tailcallopt is enabled
2266 //                * caller/callee are fastcc
2267 //  On X86_64 architecture with GOT-style position independent code only local
2268 //  (within module) calls are supported at the moment.
2269 //  To keep the stack aligned according to platform abi the function
2270 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2271 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2272 //  If a tail called function callee has more arguments than the caller the
2273 //  caller needs to make sure that there is room to move the RETADDR to. This is
2274 //  achieved by reserving an area the size of the argument delta right after the
2275 //  original REtADDR, but before the saved framepointer or the spilled registers
2276 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2277 //  stack layout:
2278 //    arg1
2279 //    arg2
2280 //    RETADDR
2281 //    [ new RETADDR
2282 //      move area ]
2283 //    (possible EBP)
2284 //    ESI
2285 //    EDI
2286 //    local1 ..
2287
2288 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2289 /// for a 16 byte align requirement.
2290 unsigned
2291 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2292                                                SelectionDAG& DAG) const {
2293   MachineFunction &MF = DAG.getMachineFunction();
2294   const TargetMachine &TM = MF.getTarget();
2295   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2296   unsigned StackAlignment = TFI.getStackAlignment();
2297   uint64_t AlignMask = StackAlignment - 1;
2298   int64_t Offset = StackSize;
2299   uint64_t SlotSize = TD->getPointerSize();
2300   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2301     // Number smaller than 12 so just add the difference.
2302     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2303   } else {
2304     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2305     Offset = ((~AlignMask) & Offset) + StackAlignment +
2306       (StackAlignment-SlotSize);
2307   }
2308   return Offset;
2309 }
2310
2311 /// MatchingStackOffset - Return true if the given stack call argument is
2312 /// already available in the same position (relatively) of the caller's
2313 /// incoming argument stack.
2314 static
2315 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2316                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2317                          const X86InstrInfo *TII) {
2318   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2319   int FI = INT_MAX;
2320   if (Arg.getOpcode() == ISD::CopyFromReg) {
2321     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2322     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2323       return false;
2324     MachineInstr *Def = MRI->getVRegDef(VR);
2325     if (!Def)
2326       return false;
2327     if (!Flags.isByVal()) {
2328       if (!TII->isLoadFromStackSlot(Def, FI))
2329         return false;
2330     } else {
2331       unsigned Opcode = Def->getOpcode();
2332       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2333           Def->getOperand(1).isFI()) {
2334         FI = Def->getOperand(1).getIndex();
2335         Bytes = Flags.getByValSize();
2336       } else
2337         return false;
2338     }
2339   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2340     if (Flags.isByVal())
2341       // ByVal argument is passed in as a pointer but it's now being
2342       // dereferenced. e.g.
2343       // define @foo(%struct.X* %A) {
2344       //   tail call @bar(%struct.X* byval %A)
2345       // }
2346       return false;
2347     SDValue Ptr = Ld->getBasePtr();
2348     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2349     if (!FINode)
2350       return false;
2351     FI = FINode->getIndex();
2352   } else
2353     return false;
2354
2355   assert(FI != INT_MAX);
2356   if (!MFI->isFixedObjectIndex(FI))
2357     return false;
2358   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2359 }
2360
2361 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2362 /// for tail call optimization. Targets which want to do tail call
2363 /// optimization should implement this function.
2364 bool
2365 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2366                                                      CallingConv::ID CalleeCC,
2367                                                      bool isVarArg,
2368                                                      bool isCalleeStructRet,
2369                                                      bool isCallerStructRet,
2370                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2371                                     const SmallVectorImpl<SDValue> &OutVals,
2372                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2373                                                      SelectionDAG& DAG) const {
2374   if (!IsTailCallConvention(CalleeCC) &&
2375       CalleeCC != CallingConv::C)
2376     return false;
2377
2378   // If -tailcallopt is specified, make fastcc functions tail-callable.
2379   const MachineFunction &MF = DAG.getMachineFunction();
2380   const Function *CallerF = DAG.getMachineFunction().getFunction();
2381   CallingConv::ID CallerCC = CallerF->getCallingConv();
2382   bool CCMatch = CallerCC == CalleeCC;
2383
2384   if (GuaranteedTailCallOpt) {
2385     if (IsTailCallConvention(CalleeCC) && CCMatch)
2386       return true;
2387     return false;
2388   }
2389
2390   // Look for obvious safe cases to perform tail call optimization that do not
2391   // require ABI changes. This is what gcc calls sibcall.
2392
2393   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2394   // emit a special epilogue.
2395   if (RegInfo->needsStackRealignment(MF))
2396     return false;
2397
2398   // Do not sibcall optimize vararg calls unless the call site is not passing
2399   // any arguments.
2400   if (isVarArg && !Outs.empty())
2401     return false;
2402
2403   // Also avoid sibcall optimization if either caller or callee uses struct
2404   // return semantics.
2405   if (isCalleeStructRet || isCallerStructRet)
2406     return false;
2407
2408   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2409   // Therefore if it's not used by the call it is not safe to optimize this into
2410   // a sibcall.
2411   bool Unused = false;
2412   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2413     if (!Ins[i].Used) {
2414       Unused = true;
2415       break;
2416     }
2417   }
2418   if (Unused) {
2419     SmallVector<CCValAssign, 16> RVLocs;
2420     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2421                    RVLocs, *DAG.getContext());
2422     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2423     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2424       CCValAssign &VA = RVLocs[i];
2425       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2426         return false;
2427     }
2428   }
2429
2430   // If the calling conventions do not match, then we'd better make sure the
2431   // results are returned in the same way as what the caller expects.
2432   if (!CCMatch) {
2433     SmallVector<CCValAssign, 16> RVLocs1;
2434     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2435                     RVLocs1, *DAG.getContext());
2436     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2437
2438     SmallVector<CCValAssign, 16> RVLocs2;
2439     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2440                     RVLocs2, *DAG.getContext());
2441     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2442
2443     if (RVLocs1.size() != RVLocs2.size())
2444       return false;
2445     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2446       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2447         return false;
2448       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2449         return false;
2450       if (RVLocs1[i].isRegLoc()) {
2451         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2452           return false;
2453       } else {
2454         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2455           return false;
2456       }
2457     }
2458   }
2459
2460   // If the callee takes no arguments then go on to check the results of the
2461   // call.
2462   if (!Outs.empty()) {
2463     // Check if stack adjustment is needed. For now, do not do this if any
2464     // argument is passed on the stack.
2465     SmallVector<CCValAssign, 16> ArgLocs;
2466     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2467                    ArgLocs, *DAG.getContext());
2468     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2469     if (CCInfo.getNextStackOffset()) {
2470       MachineFunction &MF = DAG.getMachineFunction();
2471       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2472         return false;
2473       if (Subtarget->isTargetWin64())
2474         // Win64 ABI has additional complications.
2475         return false;
2476
2477       // Check if the arguments are already laid out in the right way as
2478       // the caller's fixed stack objects.
2479       MachineFrameInfo *MFI = MF.getFrameInfo();
2480       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2481       const X86InstrInfo *TII =
2482         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2483       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2484         CCValAssign &VA = ArgLocs[i];
2485         SDValue Arg = OutVals[i];
2486         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2487         if (VA.getLocInfo() == CCValAssign::Indirect)
2488           return false;
2489         if (!VA.isRegLoc()) {
2490           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2491                                    MFI, MRI, TII))
2492             return false;
2493         }
2494       }
2495     }
2496
2497     // If the tailcall address may be in a register, then make sure it's
2498     // possible to register allocate for it. In 32-bit, the call address can
2499     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2500     // callee-saved registers are restored. These happen to be the same
2501     // registers used to pass 'inreg' arguments so watch out for those.
2502     if (!Subtarget->is64Bit() &&
2503         !isa<GlobalAddressSDNode>(Callee) &&
2504         !isa<ExternalSymbolSDNode>(Callee)) {
2505       unsigned NumInRegs = 0;
2506       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507         CCValAssign &VA = ArgLocs[i];
2508         if (!VA.isRegLoc())
2509           continue;
2510         unsigned Reg = VA.getLocReg();
2511         switch (Reg) {
2512         default: break;
2513         case X86::EAX: case X86::EDX: case X86::ECX:
2514           if (++NumInRegs == 3)
2515             return false;
2516           break;
2517         }
2518       }
2519     }
2520   }
2521
2522   // An stdcall caller is expected to clean up its arguments; the callee
2523   // isn't going to do that.
2524   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2525     return false;
2526
2527   return true;
2528 }
2529
2530 FastISel *
2531 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2532   return X86::createFastISel(funcInfo);
2533 }
2534
2535
2536 //===----------------------------------------------------------------------===//
2537 //                           Other Lowering Hooks
2538 //===----------------------------------------------------------------------===//
2539
2540 static bool MayFoldLoad(SDValue Op) {
2541   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2542 }
2543
2544 static bool MayFoldIntoStore(SDValue Op) {
2545   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2546 }
2547
2548 static bool isTargetShuffle(unsigned Opcode) {
2549   switch(Opcode) {
2550   default: return false;
2551   case X86ISD::PSHUFD:
2552   case X86ISD::PSHUFHW:
2553   case X86ISD::PSHUFLW:
2554   case X86ISD::SHUFPD:
2555   case X86ISD::PALIGN:
2556   case X86ISD::SHUFPS:
2557   case X86ISD::MOVLHPS:
2558   case X86ISD::MOVLHPD:
2559   case X86ISD::MOVHLPS:
2560   case X86ISD::MOVLPS:
2561   case X86ISD::MOVLPD:
2562   case X86ISD::MOVSHDUP:
2563   case X86ISD::MOVSLDUP:
2564   case X86ISD::MOVDDUP:
2565   case X86ISD::MOVSS:
2566   case X86ISD::MOVSD:
2567   case X86ISD::UNPCKLPS:
2568   case X86ISD::UNPCKLPD:
2569   case X86ISD::PUNPCKLWD:
2570   case X86ISD::PUNPCKLBW:
2571   case X86ISD::PUNPCKLDQ:
2572   case X86ISD::PUNPCKLQDQ:
2573   case X86ISD::UNPCKHPS:
2574   case X86ISD::UNPCKHPD:
2575   case X86ISD::PUNPCKHWD:
2576   case X86ISD::PUNPCKHBW:
2577   case X86ISD::PUNPCKHDQ:
2578   case X86ISD::PUNPCKHQDQ:
2579     return true;
2580   }
2581   return false;
2582 }
2583
2584 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2585                                                SDValue V1, SelectionDAG &DAG) {
2586   switch(Opc) {
2587   default: llvm_unreachable("Unknown x86 shuffle node");
2588   case X86ISD::MOVSHDUP:
2589   case X86ISD::MOVSLDUP:
2590   case X86ISD::MOVDDUP:
2591     return DAG.getNode(Opc, dl, VT, V1);
2592   }
2593
2594   return SDValue();
2595 }
2596
2597 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2598                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2599   switch(Opc) {
2600   default: llvm_unreachable("Unknown x86 shuffle node");
2601   case X86ISD::PSHUFD:
2602   case X86ISD::PSHUFHW:
2603   case X86ISD::PSHUFLW:
2604     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2605   }
2606
2607   return SDValue();
2608 }
2609
2610 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2611                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2612   switch(Opc) {
2613   default: llvm_unreachable("Unknown x86 shuffle node");
2614   case X86ISD::PALIGN:
2615   case X86ISD::SHUFPD:
2616   case X86ISD::SHUFPS:
2617     return DAG.getNode(Opc, dl, VT, V1, V2,
2618                        DAG.getConstant(TargetMask, MVT::i8));
2619   }
2620   return SDValue();
2621 }
2622
2623 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2624                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2625   switch(Opc) {
2626   default: llvm_unreachable("Unknown x86 shuffle node");
2627   case X86ISD::MOVLHPS:
2628   case X86ISD::MOVLHPD:
2629   case X86ISD::MOVHLPS:
2630   case X86ISD::MOVLPS:
2631   case X86ISD::MOVLPD:
2632   case X86ISD::MOVSS:
2633   case X86ISD::MOVSD:
2634   case X86ISD::UNPCKLPS:
2635   case X86ISD::UNPCKLPD:
2636   case X86ISD::PUNPCKLWD:
2637   case X86ISD::PUNPCKLBW:
2638   case X86ISD::PUNPCKLDQ:
2639   case X86ISD::PUNPCKLQDQ:
2640   case X86ISD::UNPCKHPS:
2641   case X86ISD::UNPCKHPD:
2642   case X86ISD::PUNPCKHWD:
2643   case X86ISD::PUNPCKHBW:
2644   case X86ISD::PUNPCKHDQ:
2645   case X86ISD::PUNPCKHQDQ:
2646     return DAG.getNode(Opc, dl, VT, V1, V2);
2647   }
2648   return SDValue();
2649 }
2650
2651 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2652   MachineFunction &MF = DAG.getMachineFunction();
2653   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2654   int ReturnAddrIndex = FuncInfo->getRAIndex();
2655
2656   if (ReturnAddrIndex == 0) {
2657     // Set up a frame object for the return address.
2658     uint64_t SlotSize = TD->getPointerSize();
2659     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2660                                                            false);
2661     FuncInfo->setRAIndex(ReturnAddrIndex);
2662   }
2663
2664   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2665 }
2666
2667
2668 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2669                                        bool hasSymbolicDisplacement) {
2670   // Offset should fit into 32 bit immediate field.
2671   if (!isInt<32>(Offset))
2672     return false;
2673
2674   // If we don't have a symbolic displacement - we don't have any extra
2675   // restrictions.
2676   if (!hasSymbolicDisplacement)
2677     return true;
2678
2679   // FIXME: Some tweaks might be needed for medium code model.
2680   if (M != CodeModel::Small && M != CodeModel::Kernel)
2681     return false;
2682
2683   // For small code model we assume that latest object is 16MB before end of 31
2684   // bits boundary. We may also accept pretty large negative constants knowing
2685   // that all objects are in the positive half of address space.
2686   if (M == CodeModel::Small && Offset < 16*1024*1024)
2687     return true;
2688
2689   // For kernel code model we know that all object resist in the negative half
2690   // of 32bits address space. We may not accept negative offsets, since they may
2691   // be just off and we may accept pretty large positive ones.
2692   if (M == CodeModel::Kernel && Offset > 0)
2693     return true;
2694
2695   return false;
2696 }
2697
2698 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2699 /// specific condition code, returning the condition code and the LHS/RHS of the
2700 /// comparison to make.
2701 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2702                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2703   if (!isFP) {
2704     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2705       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2706         // X > -1   -> X == 0, jump !sign.
2707         RHS = DAG.getConstant(0, RHS.getValueType());
2708         return X86::COND_NS;
2709       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2710         // X < 0   -> X == 0, jump on sign.
2711         return X86::COND_S;
2712       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2713         // X < 1   -> X <= 0
2714         RHS = DAG.getConstant(0, RHS.getValueType());
2715         return X86::COND_LE;
2716       }
2717     }
2718
2719     switch (SetCCOpcode) {
2720     default: llvm_unreachable("Invalid integer condition!");
2721     case ISD::SETEQ:  return X86::COND_E;
2722     case ISD::SETGT:  return X86::COND_G;
2723     case ISD::SETGE:  return X86::COND_GE;
2724     case ISD::SETLT:  return X86::COND_L;
2725     case ISD::SETLE:  return X86::COND_LE;
2726     case ISD::SETNE:  return X86::COND_NE;
2727     case ISD::SETULT: return X86::COND_B;
2728     case ISD::SETUGT: return X86::COND_A;
2729     case ISD::SETULE: return X86::COND_BE;
2730     case ISD::SETUGE: return X86::COND_AE;
2731     }
2732   }
2733
2734   // First determine if it is required or is profitable to flip the operands.
2735
2736   // If LHS is a foldable load, but RHS is not, flip the condition.
2737   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2738       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2739     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2740     std::swap(LHS, RHS);
2741   }
2742
2743   switch (SetCCOpcode) {
2744   default: break;
2745   case ISD::SETOLT:
2746   case ISD::SETOLE:
2747   case ISD::SETUGT:
2748   case ISD::SETUGE:
2749     std::swap(LHS, RHS);
2750     break;
2751   }
2752
2753   // On a floating point condition, the flags are set as follows:
2754   // ZF  PF  CF   op
2755   //  0 | 0 | 0 | X > Y
2756   //  0 | 0 | 1 | X < Y
2757   //  1 | 0 | 0 | X == Y
2758   //  1 | 1 | 1 | unordered
2759   switch (SetCCOpcode) {
2760   default: llvm_unreachable("Condcode should be pre-legalized away");
2761   case ISD::SETUEQ:
2762   case ISD::SETEQ:   return X86::COND_E;
2763   case ISD::SETOLT:              // flipped
2764   case ISD::SETOGT:
2765   case ISD::SETGT:   return X86::COND_A;
2766   case ISD::SETOLE:              // flipped
2767   case ISD::SETOGE:
2768   case ISD::SETGE:   return X86::COND_AE;
2769   case ISD::SETUGT:              // flipped
2770   case ISD::SETULT:
2771   case ISD::SETLT:   return X86::COND_B;
2772   case ISD::SETUGE:              // flipped
2773   case ISD::SETULE:
2774   case ISD::SETLE:   return X86::COND_BE;
2775   case ISD::SETONE:
2776   case ISD::SETNE:   return X86::COND_NE;
2777   case ISD::SETUO:   return X86::COND_P;
2778   case ISD::SETO:    return X86::COND_NP;
2779   case ISD::SETOEQ:
2780   case ISD::SETUNE:  return X86::COND_INVALID;
2781   }
2782 }
2783
2784 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2785 /// code. Current x86 isa includes the following FP cmov instructions:
2786 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2787 static bool hasFPCMov(unsigned X86CC) {
2788   switch (X86CC) {
2789   default:
2790     return false;
2791   case X86::COND_B:
2792   case X86::COND_BE:
2793   case X86::COND_E:
2794   case X86::COND_P:
2795   case X86::COND_A:
2796   case X86::COND_AE:
2797   case X86::COND_NE:
2798   case X86::COND_NP:
2799     return true;
2800   }
2801 }
2802
2803 /// isFPImmLegal - Returns true if the target can instruction select the
2804 /// specified FP immediate natively. If false, the legalizer will
2805 /// materialize the FP immediate as a load from a constant pool.
2806 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2807   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2808     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2809       return true;
2810   }
2811   return false;
2812 }
2813
2814 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2815 /// the specified range (L, H].
2816 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2817   return (Val < 0) || (Val >= Low && Val < Hi);
2818 }
2819
2820 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2821 /// specified value.
2822 static bool isUndefOrEqual(int Val, int CmpVal) {
2823   if (Val < 0 || Val == CmpVal)
2824     return true;
2825   return false;
2826 }
2827
2828 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2829 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2830 /// the second operand.
2831 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2832   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2833     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2834   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2835     return (Mask[0] < 2 && Mask[1] < 2);
2836   return false;
2837 }
2838
2839 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2840   SmallVector<int, 8> M;
2841   N->getMask(M);
2842   return ::isPSHUFDMask(M, N->getValueType(0));
2843 }
2844
2845 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2846 /// is suitable for input to PSHUFHW.
2847 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2848   if (VT != MVT::v8i16)
2849     return false;
2850
2851   // Lower quadword copied in order or undef.
2852   for (int i = 0; i != 4; ++i)
2853     if (Mask[i] >= 0 && Mask[i] != i)
2854       return false;
2855
2856   // Upper quadword shuffled.
2857   for (int i = 4; i != 8; ++i)
2858     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2859       return false;
2860
2861   return true;
2862 }
2863
2864 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2865   SmallVector<int, 8> M;
2866   N->getMask(M);
2867   return ::isPSHUFHWMask(M, N->getValueType(0));
2868 }
2869
2870 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2871 /// is suitable for input to PSHUFLW.
2872 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2873   if (VT != MVT::v8i16)
2874     return false;
2875
2876   // Upper quadword copied in order.
2877   for (int i = 4; i != 8; ++i)
2878     if (Mask[i] >= 0 && Mask[i] != i)
2879       return false;
2880
2881   // Lower quadword shuffled.
2882   for (int i = 0; i != 4; ++i)
2883     if (Mask[i] >= 4)
2884       return false;
2885
2886   return true;
2887 }
2888
2889 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2890   SmallVector<int, 8> M;
2891   N->getMask(M);
2892   return ::isPSHUFLWMask(M, N->getValueType(0));
2893 }
2894
2895 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2896 /// is suitable for input to PALIGNR.
2897 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2898                           bool hasSSSE3) {
2899   int i, e = VT.getVectorNumElements();
2900
2901   // Do not handle v2i64 / v2f64 shuffles with palignr.
2902   if (e < 4 || !hasSSSE3)
2903     return false;
2904
2905   for (i = 0; i != e; ++i)
2906     if (Mask[i] >= 0)
2907       break;
2908
2909   // All undef, not a palignr.
2910   if (i == e)
2911     return false;
2912
2913   // Determine if it's ok to perform a palignr with only the LHS, since we
2914   // don't have access to the actual shuffle elements to see if RHS is undef.
2915   bool Unary = Mask[i] < (int)e;
2916   bool NeedsUnary = false;
2917
2918   int s = Mask[i] - i;
2919
2920   // Check the rest of the elements to see if they are consecutive.
2921   for (++i; i != e; ++i) {
2922     int m = Mask[i];
2923     if (m < 0)
2924       continue;
2925
2926     Unary = Unary && (m < (int)e);
2927     NeedsUnary = NeedsUnary || (m < s);
2928
2929     if (NeedsUnary && !Unary)
2930       return false;
2931     if (Unary && m != ((s+i) & (e-1)))
2932       return false;
2933     if (!Unary && m != (s+i))
2934       return false;
2935   }
2936   return true;
2937 }
2938
2939 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2940   SmallVector<int, 8> M;
2941   N->getMask(M);
2942   return ::isPALIGNRMask(M, N->getValueType(0), true);
2943 }
2944
2945 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2946 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2947 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2948   int NumElems = VT.getVectorNumElements();
2949   if (NumElems != 2 && NumElems != 4)
2950     return false;
2951
2952   int Half = NumElems / 2;
2953   for (int i = 0; i < Half; ++i)
2954     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2955       return false;
2956   for (int i = Half; i < NumElems; ++i)
2957     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2958       return false;
2959
2960   return true;
2961 }
2962
2963 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2964   SmallVector<int, 8> M;
2965   N->getMask(M);
2966   return ::isSHUFPMask(M, N->getValueType(0));
2967 }
2968
2969 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2970 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2971 /// half elements to come from vector 1 (which would equal the dest.) and
2972 /// the upper half to come from vector 2.
2973 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2974   int NumElems = VT.getVectorNumElements();
2975
2976   if (NumElems != 2 && NumElems != 4)
2977     return false;
2978
2979   int Half = NumElems / 2;
2980   for (int i = 0; i < Half; ++i)
2981     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2982       return false;
2983   for (int i = Half; i < NumElems; ++i)
2984     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2985       return false;
2986   return true;
2987 }
2988
2989 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2990   SmallVector<int, 8> M;
2991   N->getMask(M);
2992   return isCommutedSHUFPMask(M, N->getValueType(0));
2993 }
2994
2995 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2996 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2997 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2998   if (N->getValueType(0).getVectorNumElements() != 4)
2999     return false;
3000
3001   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3002   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3003          isUndefOrEqual(N->getMaskElt(1), 7) &&
3004          isUndefOrEqual(N->getMaskElt(2), 2) &&
3005          isUndefOrEqual(N->getMaskElt(3), 3);
3006 }
3007
3008 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3009 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3010 /// <2, 3, 2, 3>
3011 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3012   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3013
3014   if (NumElems != 4)
3015     return false;
3016
3017   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3018   isUndefOrEqual(N->getMaskElt(1), 3) &&
3019   isUndefOrEqual(N->getMaskElt(2), 2) &&
3020   isUndefOrEqual(N->getMaskElt(3), 3);
3021 }
3022
3023 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3024 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3025 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3026   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3027
3028   if (NumElems != 2 && NumElems != 4)
3029     return false;
3030
3031   for (unsigned i = 0; i < NumElems/2; ++i)
3032     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3033       return false;
3034
3035   for (unsigned i = NumElems/2; i < NumElems; ++i)
3036     if (!isUndefOrEqual(N->getMaskElt(i), i))
3037       return false;
3038
3039   return true;
3040 }
3041
3042 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3043 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3044 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3045   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3046
3047   if (NumElems != 2 && NumElems != 4)
3048     return false;
3049
3050   for (unsigned i = 0; i < NumElems/2; ++i)
3051     if (!isUndefOrEqual(N->getMaskElt(i), i))
3052       return false;
3053
3054   for (unsigned i = 0; i < NumElems/2; ++i)
3055     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3056       return false;
3057
3058   return true;
3059 }
3060
3061 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3062 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3063 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3064                          bool V2IsSplat = false) {
3065   int NumElts = VT.getVectorNumElements();
3066   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3067     return false;
3068
3069   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3070     int BitI  = Mask[i];
3071     int BitI1 = Mask[i+1];
3072     if (!isUndefOrEqual(BitI, j))
3073       return false;
3074     if (V2IsSplat) {
3075       if (!isUndefOrEqual(BitI1, NumElts))
3076         return false;
3077     } else {
3078       if (!isUndefOrEqual(BitI1, j + NumElts))
3079         return false;
3080     }
3081   }
3082   return true;
3083 }
3084
3085 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3086   SmallVector<int, 8> M;
3087   N->getMask(M);
3088   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3089 }
3090
3091 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3092 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3093 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3094                          bool V2IsSplat = false) {
3095   int NumElts = VT.getVectorNumElements();
3096   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3097     return false;
3098
3099   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3100     int BitI  = Mask[i];
3101     int BitI1 = Mask[i+1];
3102     if (!isUndefOrEqual(BitI, j + NumElts/2))
3103       return false;
3104     if (V2IsSplat) {
3105       if (isUndefOrEqual(BitI1, NumElts))
3106         return false;
3107     } else {
3108       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3109         return false;
3110     }
3111   }
3112   return true;
3113 }
3114
3115 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3116   SmallVector<int, 8> M;
3117   N->getMask(M);
3118   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3119 }
3120
3121 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3122 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3123 /// <0, 0, 1, 1>
3124 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3125   int NumElems = VT.getVectorNumElements();
3126   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3127     return false;
3128
3129   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3130     int BitI  = Mask[i];
3131     int BitI1 = Mask[i+1];
3132     if (!isUndefOrEqual(BitI, j))
3133       return false;
3134     if (!isUndefOrEqual(BitI1, j))
3135       return false;
3136   }
3137   return true;
3138 }
3139
3140 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3141   SmallVector<int, 8> M;
3142   N->getMask(M);
3143   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3144 }
3145
3146 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3147 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3148 /// <2, 2, 3, 3>
3149 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3150   int NumElems = VT.getVectorNumElements();
3151   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3152     return false;
3153
3154   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3155     int BitI  = Mask[i];
3156     int BitI1 = Mask[i+1];
3157     if (!isUndefOrEqual(BitI, j))
3158       return false;
3159     if (!isUndefOrEqual(BitI1, j))
3160       return false;
3161   }
3162   return true;
3163 }
3164
3165 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3166   SmallVector<int, 8> M;
3167   N->getMask(M);
3168   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3169 }
3170
3171 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3172 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3173 /// MOVSD, and MOVD, i.e. setting the lowest element.
3174 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3175   if (VT.getVectorElementType().getSizeInBits() < 32)
3176     return false;
3177
3178   int NumElts = VT.getVectorNumElements();
3179
3180   if (!isUndefOrEqual(Mask[0], NumElts))
3181     return false;
3182
3183   for (int i = 1; i < NumElts; ++i)
3184     if (!isUndefOrEqual(Mask[i], i))
3185       return false;
3186
3187   return true;
3188 }
3189
3190 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3191   SmallVector<int, 8> M;
3192   N->getMask(M);
3193   return ::isMOVLMask(M, N->getValueType(0));
3194 }
3195
3196 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3197 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3198 /// element of vector 2 and the other elements to come from vector 1 in order.
3199 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3200                                bool V2IsSplat = false, bool V2IsUndef = false) {
3201   int NumOps = VT.getVectorNumElements();
3202   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3203     return false;
3204
3205   if (!isUndefOrEqual(Mask[0], 0))
3206     return false;
3207
3208   for (int i = 1; i < NumOps; ++i)
3209     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3210           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3211           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3212       return false;
3213
3214   return true;
3215 }
3216
3217 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3218                            bool V2IsUndef = false) {
3219   SmallVector<int, 8> M;
3220   N->getMask(M);
3221   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3222 }
3223
3224 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3225 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3226 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3227   if (N->getValueType(0).getVectorNumElements() != 4)
3228     return false;
3229
3230   // Expect 1, 1, 3, 3
3231   for (unsigned i = 0; i < 2; ++i) {
3232     int Elt = N->getMaskElt(i);
3233     if (Elt >= 0 && Elt != 1)
3234       return false;
3235   }
3236
3237   bool HasHi = false;
3238   for (unsigned i = 2; i < 4; ++i) {
3239     int Elt = N->getMaskElt(i);
3240     if (Elt >= 0 && Elt != 3)
3241       return false;
3242     if (Elt == 3)
3243       HasHi = true;
3244   }
3245   // Don't use movshdup if it can be done with a shufps.
3246   // FIXME: verify that matching u, u, 3, 3 is what we want.
3247   return HasHi;
3248 }
3249
3250 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3251 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3252 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3253   if (N->getValueType(0).getVectorNumElements() != 4)
3254     return false;
3255
3256   // Expect 0, 0, 2, 2
3257   for (unsigned i = 0; i < 2; ++i)
3258     if (N->getMaskElt(i) > 0)
3259       return false;
3260
3261   bool HasHi = false;
3262   for (unsigned i = 2; i < 4; ++i) {
3263     int Elt = N->getMaskElt(i);
3264     if (Elt >= 0 && Elt != 2)
3265       return false;
3266     if (Elt == 2)
3267       HasHi = true;
3268   }
3269   // Don't use movsldup if it can be done with a shufps.
3270   return HasHi;
3271 }
3272
3273 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3274 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3275 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3276   int e = N->getValueType(0).getVectorNumElements() / 2;
3277
3278   for (int i = 0; i < e; ++i)
3279     if (!isUndefOrEqual(N->getMaskElt(i), i))
3280       return false;
3281   for (int i = 0; i < e; ++i)
3282     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3283       return false;
3284   return true;
3285 }
3286
3287 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3288 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3289 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3291   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3292
3293   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3294   unsigned Mask = 0;
3295   for (int i = 0; i < NumOperands; ++i) {
3296     int Val = SVOp->getMaskElt(NumOperands-i-1);
3297     if (Val < 0) Val = 0;
3298     if (Val >= NumOperands) Val -= NumOperands;
3299     Mask |= Val;
3300     if (i != NumOperands - 1)
3301       Mask <<= Shift;
3302   }
3303   return Mask;
3304 }
3305
3306 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3307 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3308 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3309   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3310   unsigned Mask = 0;
3311   // 8 nodes, but we only care about the last 4.
3312   for (unsigned i = 7; i >= 4; --i) {
3313     int Val = SVOp->getMaskElt(i);
3314     if (Val >= 0)
3315       Mask |= (Val - 4);
3316     if (i != 4)
3317       Mask <<= 2;
3318   }
3319   return Mask;
3320 }
3321
3322 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3323 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3324 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3325   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3326   unsigned Mask = 0;
3327   // 8 nodes, but we only care about the first 4.
3328   for (int i = 3; i >= 0; --i) {
3329     int Val = SVOp->getMaskElt(i);
3330     if (Val >= 0)
3331       Mask |= Val;
3332     if (i != 0)
3333       Mask <<= 2;
3334   }
3335   return Mask;
3336 }
3337
3338 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3339 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3340 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3341   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3342   EVT VVT = N->getValueType(0);
3343   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3344   int Val = 0;
3345
3346   unsigned i, e;
3347   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3348     Val = SVOp->getMaskElt(i);
3349     if (Val >= 0)
3350       break;
3351   }
3352   return (Val - i) * EltSize;
3353 }
3354
3355 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3356 /// constant +0.0.
3357 bool X86::isZeroNode(SDValue Elt) {
3358   return ((isa<ConstantSDNode>(Elt) &&
3359            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3360           (isa<ConstantFPSDNode>(Elt) &&
3361            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3362 }
3363
3364 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3365 /// their permute mask.
3366 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3367                                     SelectionDAG &DAG) {
3368   EVT VT = SVOp->getValueType(0);
3369   unsigned NumElems = VT.getVectorNumElements();
3370   SmallVector<int, 8> MaskVec;
3371
3372   for (unsigned i = 0; i != NumElems; ++i) {
3373     int idx = SVOp->getMaskElt(i);
3374     if (idx < 0)
3375       MaskVec.push_back(idx);
3376     else if (idx < (int)NumElems)
3377       MaskVec.push_back(idx + NumElems);
3378     else
3379       MaskVec.push_back(idx - NumElems);
3380   }
3381   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3382                               SVOp->getOperand(0), &MaskVec[0]);
3383 }
3384
3385 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3386 /// the two vector operands have swapped position.
3387 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3388   unsigned NumElems = VT.getVectorNumElements();
3389   for (unsigned i = 0; i != NumElems; ++i) {
3390     int idx = Mask[i];
3391     if (idx < 0)
3392       continue;
3393     else if (idx < (int)NumElems)
3394       Mask[i] = idx + NumElems;
3395     else
3396       Mask[i] = idx - NumElems;
3397   }
3398 }
3399
3400 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3401 /// match movhlps. The lower half elements should come from upper half of
3402 /// V1 (and in order), and the upper half elements should come from the upper
3403 /// half of V2 (and in order).
3404 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3405   if (Op->getValueType(0).getVectorNumElements() != 4)
3406     return false;
3407   for (unsigned i = 0, e = 2; i != e; ++i)
3408     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3409       return false;
3410   for (unsigned i = 2; i != 4; ++i)
3411     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3412       return false;
3413   return true;
3414 }
3415
3416 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3417 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3418 /// required.
3419 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3420   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3421     return false;
3422   N = N->getOperand(0).getNode();
3423   if (!ISD::isNON_EXTLoad(N))
3424     return false;
3425   if (LD)
3426     *LD = cast<LoadSDNode>(N);
3427   return true;
3428 }
3429
3430 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3431 /// match movlp{s|d}. The lower half elements should come from lower half of
3432 /// V1 (and in order), and the upper half elements should come from the upper
3433 /// half of V2 (and in order). And since V1 will become the source of the
3434 /// MOVLP, it must be either a vector load or a scalar load to vector.
3435 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3436                                ShuffleVectorSDNode *Op) {
3437   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3438     return false;
3439   // Is V2 is a vector load, don't do this transformation. We will try to use
3440   // load folding shufps op.
3441   if (ISD::isNON_EXTLoad(V2))
3442     return false;
3443
3444   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3445
3446   if (NumElems != 2 && NumElems != 4)
3447     return false;
3448   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3449     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3450       return false;
3451   for (unsigned i = NumElems/2; i != NumElems; ++i)
3452     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3453       return false;
3454   return true;
3455 }
3456
3457 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3458 /// all the same.
3459 static bool isSplatVector(SDNode *N) {
3460   if (N->getOpcode() != ISD::BUILD_VECTOR)
3461     return false;
3462
3463   SDValue SplatValue = N->getOperand(0);
3464   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3465     if (N->getOperand(i) != SplatValue)
3466       return false;
3467   return true;
3468 }
3469
3470 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3471 /// to an zero vector.
3472 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3473 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3474   SDValue V1 = N->getOperand(0);
3475   SDValue V2 = N->getOperand(1);
3476   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3477   for (unsigned i = 0; i != NumElems; ++i) {
3478     int Idx = N->getMaskElt(i);
3479     if (Idx >= (int)NumElems) {
3480       unsigned Opc = V2.getOpcode();
3481       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3482         continue;
3483       if (Opc != ISD::BUILD_VECTOR ||
3484           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3485         return false;
3486     } else if (Idx >= 0) {
3487       unsigned Opc = V1.getOpcode();
3488       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3489         continue;
3490       if (Opc != ISD::BUILD_VECTOR ||
3491           !X86::isZeroNode(V1.getOperand(Idx)))
3492         return false;
3493     }
3494   }
3495   return true;
3496 }
3497
3498 /// getZeroVector - Returns a vector of specified type with all zero elements.
3499 ///
3500 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3501                              DebugLoc dl) {
3502   assert(VT.isVector() && "Expected a vector type");
3503
3504   // Always build SSE zero vectors as <4 x i32> bitcasted
3505   // to their dest type. This ensures they get CSE'd.
3506   SDValue Vec;
3507   if (VT.getSizeInBits() == 128) {  // SSE
3508     if (HasSSE2) {  // SSE2
3509       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3510       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3511     } else { // SSE1
3512       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3513       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3514     }
3515   } else if (VT.getSizeInBits() == 256) { // AVX
3516     // 256-bit logic and arithmetic instructions in AVX are
3517     // all floating-point, no support for integer ops. Default
3518     // to emitting fp zeroed vectors then.
3519     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3520     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3521     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3522   }
3523   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3524 }
3525
3526 /// getOnesVector - Returns a vector of specified type with all bits set.
3527 ///
3528 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3529   assert(VT.isVector() && "Expected a vector type");
3530
3531   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3532   // type.  This ensures they get CSE'd.
3533   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3534   SDValue Vec;
3535   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3536   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3537 }
3538
3539
3540 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3541 /// that point to V2 points to its first element.
3542 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3543   EVT VT = SVOp->getValueType(0);
3544   unsigned NumElems = VT.getVectorNumElements();
3545
3546   bool Changed = false;
3547   SmallVector<int, 8> MaskVec;
3548   SVOp->getMask(MaskVec);
3549
3550   for (unsigned i = 0; i != NumElems; ++i) {
3551     if (MaskVec[i] > (int)NumElems) {
3552       MaskVec[i] = NumElems;
3553       Changed = true;
3554     }
3555   }
3556   if (Changed)
3557     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3558                                 SVOp->getOperand(1), &MaskVec[0]);
3559   return SDValue(SVOp, 0);
3560 }
3561
3562 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3563 /// operation of specified width.
3564 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3565                        SDValue V2) {
3566   unsigned NumElems = VT.getVectorNumElements();
3567   SmallVector<int, 8> Mask;
3568   Mask.push_back(NumElems);
3569   for (unsigned i = 1; i != NumElems; ++i)
3570     Mask.push_back(i);
3571   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3572 }
3573
3574 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3575 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3576                           SDValue V2) {
3577   unsigned NumElems = VT.getVectorNumElements();
3578   SmallVector<int, 8> Mask;
3579   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3580     Mask.push_back(i);
3581     Mask.push_back(i + NumElems);
3582   }
3583   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3584 }
3585
3586 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3587 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3588                           SDValue V2) {
3589   unsigned NumElems = VT.getVectorNumElements();
3590   unsigned Half = NumElems/2;
3591   SmallVector<int, 8> Mask;
3592   for (unsigned i = 0; i != Half; ++i) {
3593     Mask.push_back(i + Half);
3594     Mask.push_back(i + NumElems + Half);
3595   }
3596   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3597 }
3598
3599 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3600 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3601   EVT PVT = MVT::v4f32;
3602   EVT VT = SV->getValueType(0);
3603   DebugLoc dl = SV->getDebugLoc();
3604   SDValue V1 = SV->getOperand(0);
3605   int NumElems = VT.getVectorNumElements();
3606   int EltNo = SV->getSplatIndex();
3607
3608   // unpack elements to the correct location
3609   while (NumElems > 4) {
3610     if (EltNo < NumElems/2) {
3611       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3612     } else {
3613       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3614       EltNo -= NumElems/2;
3615     }
3616     NumElems >>= 1;
3617   }
3618
3619   // Perform the splat.
3620   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3621   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3622   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3623   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3624 }
3625
3626 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3627 /// vector of zero or undef vector.  This produces a shuffle where the low
3628 /// element of V2 is swizzled into the zero/undef vector, landing at element
3629 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3630 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3631                                              bool isZero, bool HasSSE2,
3632                                              SelectionDAG &DAG) {
3633   EVT VT = V2.getValueType();
3634   SDValue V1 = isZero
3635     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3636   unsigned NumElems = VT.getVectorNumElements();
3637   SmallVector<int, 16> MaskVec;
3638   for (unsigned i = 0; i != NumElems; ++i)
3639     // If this is the insertion idx, put the low elt of V2 here.
3640     MaskVec.push_back(i == Idx ? NumElems : i);
3641   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3642 }
3643
3644 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3645 /// element of the result of the vector shuffle.
3646 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3647                             unsigned Depth) {
3648   if (Depth == 6)
3649     return SDValue();  // Limit search depth.
3650
3651   SDValue V = SDValue(N, 0);
3652   EVT VT = V.getValueType();
3653   unsigned Opcode = V.getOpcode();
3654
3655   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3656   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3657     Index = SV->getMaskElt(Index);
3658
3659     if (Index < 0)
3660       return DAG.getUNDEF(VT.getVectorElementType());
3661
3662     int NumElems = VT.getVectorNumElements();
3663     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3664     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3665   }
3666
3667   // Recurse into target specific vector shuffles to find scalars.
3668   if (isTargetShuffle(Opcode)) {
3669     int NumElems = VT.getVectorNumElements();
3670     SmallVector<unsigned, 16> ShuffleMask;
3671     SDValue ImmN;
3672
3673     switch(Opcode) {
3674     case X86ISD::SHUFPS:
3675     case X86ISD::SHUFPD:
3676       ImmN = N->getOperand(N->getNumOperands()-1);
3677       DecodeSHUFPSMask(NumElems,
3678                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3679                        ShuffleMask);
3680       break;
3681     case X86ISD::PUNPCKHBW:
3682     case X86ISD::PUNPCKHWD:
3683     case X86ISD::PUNPCKHDQ:
3684     case X86ISD::PUNPCKHQDQ:
3685       DecodePUNPCKHMask(NumElems, ShuffleMask);
3686       break;
3687     case X86ISD::UNPCKHPS:
3688     case X86ISD::UNPCKHPD:
3689       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3690       break;
3691     case X86ISD::PUNPCKLBW:
3692     case X86ISD::PUNPCKLWD:
3693     case X86ISD::PUNPCKLDQ:
3694     case X86ISD::PUNPCKLQDQ:
3695       DecodePUNPCKLMask(NumElems, ShuffleMask);
3696       break;
3697     case X86ISD::UNPCKLPS:
3698     case X86ISD::UNPCKLPD:
3699       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3700       break;
3701     case X86ISD::MOVHLPS:
3702       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3703       break;
3704     case X86ISD::MOVLHPS:
3705       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3706       break;
3707     case X86ISD::PSHUFD:
3708       ImmN = N->getOperand(N->getNumOperands()-1);
3709       DecodePSHUFMask(NumElems,
3710                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3711                       ShuffleMask);
3712       break;
3713     case X86ISD::PSHUFHW:
3714       ImmN = N->getOperand(N->getNumOperands()-1);
3715       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3716                         ShuffleMask);
3717       break;
3718     case X86ISD::PSHUFLW:
3719       ImmN = N->getOperand(N->getNumOperands()-1);
3720       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3721                         ShuffleMask);
3722       break;
3723     case X86ISD::MOVSS:
3724     case X86ISD::MOVSD: {
3725       // The index 0 always comes from the first element of the second source,
3726       // this is why MOVSS and MOVSD are used in the first place. The other
3727       // elements come from the other positions of the first source vector.
3728       unsigned OpNum = (Index == 0) ? 1 : 0;
3729       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3730                                  Depth+1);
3731     }
3732     default:
3733       assert("not implemented for target shuffle node");
3734       return SDValue();
3735     }
3736
3737     Index = ShuffleMask[Index];
3738     if (Index < 0)
3739       return DAG.getUNDEF(VT.getVectorElementType());
3740
3741     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3742     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3743                                Depth+1);
3744   }
3745
3746   // Actual nodes that may contain scalar elements
3747   if (Opcode == ISD::BITCAST) {
3748     V = V.getOperand(0);
3749     EVT SrcVT = V.getValueType();
3750     unsigned NumElems = VT.getVectorNumElements();
3751
3752     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3753       return SDValue();
3754   }
3755
3756   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3757     return (Index == 0) ? V.getOperand(0)
3758                           : DAG.getUNDEF(VT.getVectorElementType());
3759
3760   if (V.getOpcode() == ISD::BUILD_VECTOR)
3761     return V.getOperand(Index);
3762
3763   return SDValue();
3764 }
3765
3766 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3767 /// shuffle operation which come from a consecutively from a zero. The
3768 /// search can start in two diferent directions, from left or right.
3769 static
3770 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3771                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3772   int i = 0;
3773
3774   while (i < NumElems) {
3775     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3776     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3777     if (!(Elt.getNode() &&
3778          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3779       break;
3780     ++i;
3781   }
3782
3783   return i;
3784 }
3785
3786 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3787 /// MaskE correspond consecutively to elements from one of the vector operands,
3788 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3789 static
3790 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3791                               int OpIdx, int NumElems, unsigned &OpNum) {
3792   bool SeenV1 = false;
3793   bool SeenV2 = false;
3794
3795   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3796     int Idx = SVOp->getMaskElt(i);
3797     // Ignore undef indicies
3798     if (Idx < 0)
3799       continue;
3800
3801     if (Idx < NumElems)
3802       SeenV1 = true;
3803     else
3804       SeenV2 = true;
3805
3806     // Only accept consecutive elements from the same vector
3807     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3808       return false;
3809   }
3810
3811   OpNum = SeenV1 ? 0 : 1;
3812   return true;
3813 }
3814
3815 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3816 /// logical left shift of a vector.
3817 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3818                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3819   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3820   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3821               false /* check zeros from right */, DAG);
3822   unsigned OpSrc;
3823
3824   if (!NumZeros)
3825     return false;
3826
3827   // Considering the elements in the mask that are not consecutive zeros,
3828   // check if they consecutively come from only one of the source vectors.
3829   //
3830   //               V1 = {X, A, B, C}     0
3831   //                         \  \  \    /
3832   //   vector_shuffle V1, V2 <1, 2, 3, X>
3833   //
3834   if (!isShuffleMaskConsecutive(SVOp,
3835             0,                   // Mask Start Index
3836             NumElems-NumZeros-1, // Mask End Index
3837             NumZeros,            // Where to start looking in the src vector
3838             NumElems,            // Number of elements in vector
3839             OpSrc))              // Which source operand ?
3840     return false;
3841
3842   isLeft = false;
3843   ShAmt = NumZeros;
3844   ShVal = SVOp->getOperand(OpSrc);
3845   return true;
3846 }
3847
3848 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3849 /// logical left shift of a vector.
3850 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3851                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3852   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3853   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3854               true /* check zeros from left */, DAG);
3855   unsigned OpSrc;
3856
3857   if (!NumZeros)
3858     return false;
3859
3860   // Considering the elements in the mask that are not consecutive zeros,
3861   // check if they consecutively come from only one of the source vectors.
3862   //
3863   //                           0    { A, B, X, X } = V2
3864   //                          / \    /  /
3865   //   vector_shuffle V1, V2 <X, X, 4, 5>
3866   //
3867   if (!isShuffleMaskConsecutive(SVOp,
3868             NumZeros,     // Mask Start Index
3869             NumElems-1,   // Mask End Index
3870             0,            // Where to start looking in the src vector
3871             NumElems,     // Number of elements in vector
3872             OpSrc))       // Which source operand ?
3873     return false;
3874
3875   isLeft = true;
3876   ShAmt = NumZeros;
3877   ShVal = SVOp->getOperand(OpSrc);
3878   return true;
3879 }
3880
3881 /// isVectorShift - Returns true if the shuffle can be implemented as a
3882 /// logical left or right shift of a vector.
3883 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3884                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3885   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3886       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3887     return true;
3888
3889   return false;
3890 }
3891
3892 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3893 ///
3894 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3895                                        unsigned NumNonZero, unsigned NumZero,
3896                                        SelectionDAG &DAG,
3897                                        const TargetLowering &TLI) {
3898   if (NumNonZero > 8)
3899     return SDValue();
3900
3901   DebugLoc dl = Op.getDebugLoc();
3902   SDValue V(0, 0);
3903   bool First = true;
3904   for (unsigned i = 0; i < 16; ++i) {
3905     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3906     if (ThisIsNonZero && First) {
3907       if (NumZero)
3908         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3909       else
3910         V = DAG.getUNDEF(MVT::v8i16);
3911       First = false;
3912     }
3913
3914     if ((i & 1) != 0) {
3915       SDValue ThisElt(0, 0), LastElt(0, 0);
3916       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3917       if (LastIsNonZero) {
3918         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3919                               MVT::i16, Op.getOperand(i-1));
3920       }
3921       if (ThisIsNonZero) {
3922         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3923         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3924                               ThisElt, DAG.getConstant(8, MVT::i8));
3925         if (LastIsNonZero)
3926           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3927       } else
3928         ThisElt = LastElt;
3929
3930       if (ThisElt.getNode())
3931         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3932                         DAG.getIntPtrConstant(i/2));
3933     }
3934   }
3935
3936   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3937 }
3938
3939 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3940 ///
3941 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3942                                      unsigned NumNonZero, unsigned NumZero,
3943                                      SelectionDAG &DAG,
3944                                      const TargetLowering &TLI) {
3945   if (NumNonZero > 4)
3946     return SDValue();
3947
3948   DebugLoc dl = Op.getDebugLoc();
3949   SDValue V(0, 0);
3950   bool First = true;
3951   for (unsigned i = 0; i < 8; ++i) {
3952     bool isNonZero = (NonZeros & (1 << i)) != 0;
3953     if (isNonZero) {
3954       if (First) {
3955         if (NumZero)
3956           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3957         else
3958           V = DAG.getUNDEF(MVT::v8i16);
3959         First = false;
3960       }
3961       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3962                       MVT::v8i16, V, Op.getOperand(i),
3963                       DAG.getIntPtrConstant(i));
3964     }
3965   }
3966
3967   return V;
3968 }
3969
3970 /// getVShift - Return a vector logical shift node.
3971 ///
3972 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3973                          unsigned NumBits, SelectionDAG &DAG,
3974                          const TargetLowering &TLI, DebugLoc dl) {
3975   EVT ShVT = MVT::v2i64;
3976   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3977   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3978   return DAG.getNode(ISD::BITCAST, dl, VT,
3979                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3980                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3981 }
3982
3983 SDValue
3984 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3985                                           SelectionDAG &DAG) const {
3986
3987   // Check if the scalar load can be widened into a vector load. And if
3988   // the address is "base + cst" see if the cst can be "absorbed" into
3989   // the shuffle mask.
3990   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3991     SDValue Ptr = LD->getBasePtr();
3992     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3993       return SDValue();
3994     EVT PVT = LD->getValueType(0);
3995     if (PVT != MVT::i32 && PVT != MVT::f32)
3996       return SDValue();
3997
3998     int FI = -1;
3999     int64_t Offset = 0;
4000     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4001       FI = FINode->getIndex();
4002       Offset = 0;
4003     } else if (Ptr.getOpcode() == ISD::ADD &&
4004                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4005                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4006       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4007       Offset = Ptr.getConstantOperandVal(1);
4008       Ptr = Ptr.getOperand(0);
4009     } else {
4010       return SDValue();
4011     }
4012
4013     SDValue Chain = LD->getChain();
4014     // Make sure the stack object alignment is at least 16.
4015     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4016     if (DAG.InferPtrAlignment(Ptr) < 16) {
4017       if (MFI->isFixedObjectIndex(FI)) {
4018         // Can't change the alignment. FIXME: It's possible to compute
4019         // the exact stack offset and reference FI + adjust offset instead.
4020         // If someone *really* cares about this. That's the way to implement it.
4021         return SDValue();
4022       } else {
4023         MFI->setObjectAlignment(FI, 16);
4024       }
4025     }
4026
4027     // (Offset % 16) must be multiple of 4. Then address is then
4028     // Ptr + (Offset & ~15).
4029     if (Offset < 0)
4030       return SDValue();
4031     if ((Offset % 16) & 3)
4032       return SDValue();
4033     int64_t StartOffset = Offset & ~15;
4034     if (StartOffset)
4035       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4036                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4037
4038     int EltNo = (Offset - StartOffset) >> 2;
4039     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4040     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4041     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4042                              LD->getPointerInfo().getWithOffset(StartOffset),
4043                              false, false, 0);
4044     // Canonicalize it to a v4i32 shuffle.
4045     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4046     return DAG.getNode(ISD::BITCAST, dl, VT,
4047                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4048                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4049   }
4050
4051   return SDValue();
4052 }
4053
4054 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4055 /// vector of type 'VT', see if the elements can be replaced by a single large
4056 /// load which has the same value as a build_vector whose operands are 'elts'.
4057 ///
4058 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4059 ///
4060 /// FIXME: we'd also like to handle the case where the last elements are zero
4061 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4062 /// There's even a handy isZeroNode for that purpose.
4063 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4064                                         DebugLoc &DL, SelectionDAG &DAG) {
4065   EVT EltVT = VT.getVectorElementType();
4066   unsigned NumElems = Elts.size();
4067
4068   LoadSDNode *LDBase = NULL;
4069   unsigned LastLoadedElt = -1U;
4070
4071   // For each element in the initializer, see if we've found a load or an undef.
4072   // If we don't find an initial load element, or later load elements are
4073   // non-consecutive, bail out.
4074   for (unsigned i = 0; i < NumElems; ++i) {
4075     SDValue Elt = Elts[i];
4076
4077     if (!Elt.getNode() ||
4078         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4079       return SDValue();
4080     if (!LDBase) {
4081       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4082         return SDValue();
4083       LDBase = cast<LoadSDNode>(Elt.getNode());
4084       LastLoadedElt = i;
4085       continue;
4086     }
4087     if (Elt.getOpcode() == ISD::UNDEF)
4088       continue;
4089
4090     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4091     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4092       return SDValue();
4093     LastLoadedElt = i;
4094   }
4095
4096   // If we have found an entire vector of loads and undefs, then return a large
4097   // load of the entire vector width starting at the base pointer.  If we found
4098   // consecutive loads for the low half, generate a vzext_load node.
4099   if (LastLoadedElt == NumElems - 1) {
4100     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4101       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4102                          LDBase->getPointerInfo(),
4103                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4104     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4105                        LDBase->getPointerInfo(),
4106                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4107                        LDBase->getAlignment());
4108   } else if (NumElems == 4 && LastLoadedElt == 1) {
4109     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4110     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4111     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4112                                               Ops, 2, MVT::i32,
4113                                               LDBase->getMemOperand());
4114     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4115   }
4116   return SDValue();
4117 }
4118
4119 SDValue
4120 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4121   DebugLoc dl = Op.getDebugLoc();
4122   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4123   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4124   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4125   // is present, so AllOnes is ignored.
4126   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4127       (Op.getValueType().getSizeInBits() != 256 &&
4128        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4129     // Canonicalize this to <4 x i32> (SSE) to
4130     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4131     // eliminated on x86-32 hosts.
4132     if (Op.getValueType() == MVT::v4i32)
4133       return Op;
4134
4135     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4136       return getOnesVector(Op.getValueType(), DAG, dl);
4137     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4138   }
4139
4140   EVT VT = Op.getValueType();
4141   EVT ExtVT = VT.getVectorElementType();
4142   unsigned EVTBits = ExtVT.getSizeInBits();
4143
4144   unsigned NumElems = Op.getNumOperands();
4145   unsigned NumZero  = 0;
4146   unsigned NumNonZero = 0;
4147   unsigned NonZeros = 0;
4148   bool IsAllConstants = true;
4149   SmallSet<SDValue, 8> Values;
4150   for (unsigned i = 0; i < NumElems; ++i) {
4151     SDValue Elt = Op.getOperand(i);
4152     if (Elt.getOpcode() == ISD::UNDEF)
4153       continue;
4154     Values.insert(Elt);
4155     if (Elt.getOpcode() != ISD::Constant &&
4156         Elt.getOpcode() != ISD::ConstantFP)
4157       IsAllConstants = false;
4158     if (X86::isZeroNode(Elt))
4159       NumZero++;
4160     else {
4161       NonZeros |= (1 << i);
4162       NumNonZero++;
4163     }
4164   }
4165
4166   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4167   if (NumNonZero == 0)
4168     return DAG.getUNDEF(VT);
4169
4170   // Special case for single non-zero, non-undef, element.
4171   if (NumNonZero == 1) {
4172     unsigned Idx = CountTrailingZeros_32(NonZeros);
4173     SDValue Item = Op.getOperand(Idx);
4174
4175     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4176     // the value are obviously zero, truncate the value to i32 and do the
4177     // insertion that way.  Only do this if the value is non-constant or if the
4178     // value is a constant being inserted into element 0.  It is cheaper to do
4179     // a constant pool load than it is to do a movd + shuffle.
4180     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4181         (!IsAllConstants || Idx == 0)) {
4182       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4183         // Handle SSE only.
4184         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4185         EVT VecVT = MVT::v4i32;
4186         unsigned VecElts = 4;
4187
4188         // Truncate the value (which may itself be a constant) to i32, and
4189         // convert it to a vector with movd (S2V+shuffle to zero extend).
4190         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4191         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4192         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4193                                            Subtarget->hasSSE2(), DAG);
4194
4195         // Now we have our 32-bit value zero extended in the low element of
4196         // a vector.  If Idx != 0, swizzle it into place.
4197         if (Idx != 0) {
4198           SmallVector<int, 4> Mask;
4199           Mask.push_back(Idx);
4200           for (unsigned i = 1; i != VecElts; ++i)
4201             Mask.push_back(i);
4202           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4203                                       DAG.getUNDEF(Item.getValueType()),
4204                                       &Mask[0]);
4205         }
4206         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4207       }
4208     }
4209
4210     // If we have a constant or non-constant insertion into the low element of
4211     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4212     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4213     // depending on what the source datatype is.
4214     if (Idx == 0) {
4215       if (NumZero == 0) {
4216         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4217       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4218           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4219         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4220         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4221         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4222                                            DAG);
4223       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4224         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4225         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4226         EVT MiddleVT = MVT::v4i32;
4227         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4228         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4229                                            Subtarget->hasSSE2(), DAG);
4230         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4231       }
4232     }
4233
4234     // Is it a vector logical left shift?
4235     if (NumElems == 2 && Idx == 1 &&
4236         X86::isZeroNode(Op.getOperand(0)) &&
4237         !X86::isZeroNode(Op.getOperand(1))) {
4238       unsigned NumBits = VT.getSizeInBits();
4239       return getVShift(true, VT,
4240                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4241                                    VT, Op.getOperand(1)),
4242                        NumBits/2, DAG, *this, dl);
4243     }
4244
4245     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4246       return SDValue();
4247
4248     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4249     // is a non-constant being inserted into an element other than the low one,
4250     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4251     // movd/movss) to move this into the low element, then shuffle it into
4252     // place.
4253     if (EVTBits == 32) {
4254       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4255
4256       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4257       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4258                                          Subtarget->hasSSE2(), DAG);
4259       SmallVector<int, 8> MaskVec;
4260       for (unsigned i = 0; i < NumElems; i++)
4261         MaskVec.push_back(i == Idx ? 0 : 1);
4262       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4263     }
4264   }
4265
4266   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4267   if (Values.size() == 1) {
4268     if (EVTBits == 32) {
4269       // Instead of a shuffle like this:
4270       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4271       // Check if it's possible to issue this instead.
4272       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4273       unsigned Idx = CountTrailingZeros_32(NonZeros);
4274       SDValue Item = Op.getOperand(Idx);
4275       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4276         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4277     }
4278     return SDValue();
4279   }
4280
4281   // A vector full of immediates; various special cases are already
4282   // handled, so this is best done with a single constant-pool load.
4283   if (IsAllConstants)
4284     return SDValue();
4285
4286   // Let legalizer expand 2-wide build_vectors.
4287   if (EVTBits == 64) {
4288     if (NumNonZero == 1) {
4289       // One half is zero or undef.
4290       unsigned Idx = CountTrailingZeros_32(NonZeros);
4291       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4292                                  Op.getOperand(Idx));
4293       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4294                                          Subtarget->hasSSE2(), DAG);
4295     }
4296     return SDValue();
4297   }
4298
4299   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4300   if (EVTBits == 8 && NumElems == 16) {
4301     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4302                                         *this);
4303     if (V.getNode()) return V;
4304   }
4305
4306   if (EVTBits == 16 && NumElems == 8) {
4307     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4308                                       *this);
4309     if (V.getNode()) return V;
4310   }
4311
4312   // If element VT is == 32 bits, turn it into a number of shuffles.
4313   SmallVector<SDValue, 8> V;
4314   V.resize(NumElems);
4315   if (NumElems == 4 && NumZero > 0) {
4316     for (unsigned i = 0; i < 4; ++i) {
4317       bool isZero = !(NonZeros & (1 << i));
4318       if (isZero)
4319         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4320       else
4321         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4322     }
4323
4324     for (unsigned i = 0; i < 2; ++i) {
4325       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4326         default: break;
4327         case 0:
4328           V[i] = V[i*2];  // Must be a zero vector.
4329           break;
4330         case 1:
4331           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4332           break;
4333         case 2:
4334           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4335           break;
4336         case 3:
4337           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4338           break;
4339       }
4340     }
4341
4342     SmallVector<int, 8> MaskVec;
4343     bool Reverse = (NonZeros & 0x3) == 2;
4344     for (unsigned i = 0; i < 2; ++i)
4345       MaskVec.push_back(Reverse ? 1-i : i);
4346     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4347     for (unsigned i = 0; i < 2; ++i)
4348       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4349     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4350   }
4351
4352   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4353     // Check for a build vector of consecutive loads.
4354     for (unsigned i = 0; i < NumElems; ++i)
4355       V[i] = Op.getOperand(i);
4356
4357     // Check for elements which are consecutive loads.
4358     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4359     if (LD.getNode())
4360       return LD;
4361
4362     // For SSE 4.1, use insertps to put the high elements into the low element.
4363     if (getSubtarget()->hasSSE41()) {
4364       SDValue Result;
4365       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4366         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4367       else
4368         Result = DAG.getUNDEF(VT);
4369
4370       for (unsigned i = 1; i < NumElems; ++i) {
4371         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4372         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4373                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4374       }
4375       return Result;
4376     }
4377
4378     // Otherwise, expand into a number of unpckl*, start by extending each of
4379     // our (non-undef) elements to the full vector width with the element in the
4380     // bottom slot of the vector (which generates no code for SSE).
4381     for (unsigned i = 0; i < NumElems; ++i) {
4382       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4383         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4384       else
4385         V[i] = DAG.getUNDEF(VT);
4386     }
4387
4388     // Next, we iteratively mix elements, e.g. for v4f32:
4389     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4390     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4391     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4392     unsigned EltStride = NumElems >> 1;
4393     while (EltStride != 0) {
4394       for (unsigned i = 0; i < EltStride; ++i) {
4395         // If V[i+EltStride] is undef and this is the first round of mixing,
4396         // then it is safe to just drop this shuffle: V[i] is already in the
4397         // right place, the one element (since it's the first round) being
4398         // inserted as undef can be dropped.  This isn't safe for successive
4399         // rounds because they will permute elements within both vectors.
4400         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4401             EltStride == NumElems/2)
4402           continue;
4403
4404         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4405       }
4406       EltStride >>= 1;
4407     }
4408     return V[0];
4409   }
4410   return SDValue();
4411 }
4412
4413 SDValue
4414 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4415   // We support concatenate two MMX registers and place them in a MMX
4416   // register.  This is better than doing a stack convert.
4417   DebugLoc dl = Op.getDebugLoc();
4418   EVT ResVT = Op.getValueType();
4419   assert(Op.getNumOperands() == 2);
4420   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4421          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4422   int Mask[2];
4423   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4424   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4425   InVec = Op.getOperand(1);
4426   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4427     unsigned NumElts = ResVT.getVectorNumElements();
4428     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4429     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4430                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4431   } else {
4432     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4433     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4434     Mask[0] = 0; Mask[1] = 2;
4435     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4436   }
4437   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4438 }
4439
4440 // v8i16 shuffles - Prefer shuffles in the following order:
4441 // 1. [all]   pshuflw, pshufhw, optional move
4442 // 2. [ssse3] 1 x pshufb
4443 // 3. [ssse3] 2 x pshufb + 1 x por
4444 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4445 SDValue
4446 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4447                                             SelectionDAG &DAG) const {
4448   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4449   SDValue V1 = SVOp->getOperand(0);
4450   SDValue V2 = SVOp->getOperand(1);
4451   DebugLoc dl = SVOp->getDebugLoc();
4452   SmallVector<int, 8> MaskVals;
4453
4454   // Determine if more than 1 of the words in each of the low and high quadwords
4455   // of the result come from the same quadword of one of the two inputs.  Undef
4456   // mask values count as coming from any quadword, for better codegen.
4457   SmallVector<unsigned, 4> LoQuad(4);
4458   SmallVector<unsigned, 4> HiQuad(4);
4459   BitVector InputQuads(4);
4460   for (unsigned i = 0; i < 8; ++i) {
4461     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4462     int EltIdx = SVOp->getMaskElt(i);
4463     MaskVals.push_back(EltIdx);
4464     if (EltIdx < 0) {
4465       ++Quad[0];
4466       ++Quad[1];
4467       ++Quad[2];
4468       ++Quad[3];
4469       continue;
4470     }
4471     ++Quad[EltIdx / 4];
4472     InputQuads.set(EltIdx / 4);
4473   }
4474
4475   int BestLoQuad = -1;
4476   unsigned MaxQuad = 1;
4477   for (unsigned i = 0; i < 4; ++i) {
4478     if (LoQuad[i] > MaxQuad) {
4479       BestLoQuad = i;
4480       MaxQuad = LoQuad[i];
4481     }
4482   }
4483
4484   int BestHiQuad = -1;
4485   MaxQuad = 1;
4486   for (unsigned i = 0; i < 4; ++i) {
4487     if (HiQuad[i] > MaxQuad) {
4488       BestHiQuad = i;
4489       MaxQuad = HiQuad[i];
4490     }
4491   }
4492
4493   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4494   // of the two input vectors, shuffle them into one input vector so only a
4495   // single pshufb instruction is necessary. If There are more than 2 input
4496   // quads, disable the next transformation since it does not help SSSE3.
4497   bool V1Used = InputQuads[0] || InputQuads[1];
4498   bool V2Used = InputQuads[2] || InputQuads[3];
4499   if (Subtarget->hasSSSE3()) {
4500     if (InputQuads.count() == 2 && V1Used && V2Used) {
4501       BestLoQuad = InputQuads.find_first();
4502       BestHiQuad = InputQuads.find_next(BestLoQuad);
4503     }
4504     if (InputQuads.count() > 2) {
4505       BestLoQuad = -1;
4506       BestHiQuad = -1;
4507     }
4508   }
4509
4510   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4511   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4512   // words from all 4 input quadwords.
4513   SDValue NewV;
4514   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4515     SmallVector<int, 8> MaskV;
4516     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4517     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4518     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4519                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4520                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4521     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4522
4523     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4524     // source words for the shuffle, to aid later transformations.
4525     bool AllWordsInNewV = true;
4526     bool InOrder[2] = { true, true };
4527     for (unsigned i = 0; i != 8; ++i) {
4528       int idx = MaskVals[i];
4529       if (idx != (int)i)
4530         InOrder[i/4] = false;
4531       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4532         continue;
4533       AllWordsInNewV = false;
4534       break;
4535     }
4536
4537     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4538     if (AllWordsInNewV) {
4539       for (int i = 0; i != 8; ++i) {
4540         int idx = MaskVals[i];
4541         if (idx < 0)
4542           continue;
4543         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4544         if ((idx != i) && idx < 4)
4545           pshufhw = false;
4546         if ((idx != i) && idx > 3)
4547           pshuflw = false;
4548       }
4549       V1 = NewV;
4550       V2Used = false;
4551       BestLoQuad = 0;
4552       BestHiQuad = 1;
4553     }
4554
4555     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4556     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4557     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4558       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4559       unsigned TargetMask = 0;
4560       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4561                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4562       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4563                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4564       V1 = NewV.getOperand(0);
4565       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4566     }
4567   }
4568
4569   // If we have SSSE3, and all words of the result are from 1 input vector,
4570   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4571   // is present, fall back to case 4.
4572   if (Subtarget->hasSSSE3()) {
4573     SmallVector<SDValue,16> pshufbMask;
4574
4575     // If we have elements from both input vectors, set the high bit of the
4576     // shuffle mask element to zero out elements that come from V2 in the V1
4577     // mask, and elements that come from V1 in the V2 mask, so that the two
4578     // results can be OR'd together.
4579     bool TwoInputs = V1Used && V2Used;
4580     for (unsigned i = 0; i != 8; ++i) {
4581       int EltIdx = MaskVals[i] * 2;
4582       if (TwoInputs && (EltIdx >= 16)) {
4583         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4584         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4585         continue;
4586       }
4587       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4588       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4589     }
4590     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4591     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4592                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4593                                  MVT::v16i8, &pshufbMask[0], 16));
4594     if (!TwoInputs)
4595       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4596
4597     // Calculate the shuffle mask for the second input, shuffle it, and
4598     // OR it with the first shuffled input.
4599     pshufbMask.clear();
4600     for (unsigned i = 0; i != 8; ++i) {
4601       int EltIdx = MaskVals[i] * 2;
4602       if (EltIdx < 16) {
4603         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4604         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4605         continue;
4606       }
4607       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4608       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4609     }
4610     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4611     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4612                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4613                                  MVT::v16i8, &pshufbMask[0], 16));
4614     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4615     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4616   }
4617
4618   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4619   // and update MaskVals with new element order.
4620   BitVector InOrder(8);
4621   if (BestLoQuad >= 0) {
4622     SmallVector<int, 8> MaskV;
4623     for (int i = 0; i != 4; ++i) {
4624       int idx = MaskVals[i];
4625       if (idx < 0) {
4626         MaskV.push_back(-1);
4627         InOrder.set(i);
4628       } else if ((idx / 4) == BestLoQuad) {
4629         MaskV.push_back(idx & 3);
4630         InOrder.set(i);
4631       } else {
4632         MaskV.push_back(-1);
4633       }
4634     }
4635     for (unsigned i = 4; i != 8; ++i)
4636       MaskV.push_back(i);
4637     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4638                                 &MaskV[0]);
4639
4640     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4641       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4642                                NewV.getOperand(0),
4643                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4644                                DAG);
4645   }
4646
4647   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4648   // and update MaskVals with the new element order.
4649   if (BestHiQuad >= 0) {
4650     SmallVector<int, 8> MaskV;
4651     for (unsigned i = 0; i != 4; ++i)
4652       MaskV.push_back(i);
4653     for (unsigned i = 4; i != 8; ++i) {
4654       int idx = MaskVals[i];
4655       if (idx < 0) {
4656         MaskV.push_back(-1);
4657         InOrder.set(i);
4658       } else if ((idx / 4) == BestHiQuad) {
4659         MaskV.push_back((idx & 3) + 4);
4660         InOrder.set(i);
4661       } else {
4662         MaskV.push_back(-1);
4663       }
4664     }
4665     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4666                                 &MaskV[0]);
4667
4668     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4669       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4670                               NewV.getOperand(0),
4671                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4672                               DAG);
4673   }
4674
4675   // In case BestHi & BestLo were both -1, which means each quadword has a word
4676   // from each of the four input quadwords, calculate the InOrder bitvector now
4677   // before falling through to the insert/extract cleanup.
4678   if (BestLoQuad == -1 && BestHiQuad == -1) {
4679     NewV = V1;
4680     for (int i = 0; i != 8; ++i)
4681       if (MaskVals[i] < 0 || MaskVals[i] == i)
4682         InOrder.set(i);
4683   }
4684
4685   // The other elements are put in the right place using pextrw and pinsrw.
4686   for (unsigned i = 0; i != 8; ++i) {
4687     if (InOrder[i])
4688       continue;
4689     int EltIdx = MaskVals[i];
4690     if (EltIdx < 0)
4691       continue;
4692     SDValue ExtOp = (EltIdx < 8)
4693     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4694                   DAG.getIntPtrConstant(EltIdx))
4695     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4696                   DAG.getIntPtrConstant(EltIdx - 8));
4697     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4698                        DAG.getIntPtrConstant(i));
4699   }
4700   return NewV;
4701 }
4702
4703 // v16i8 shuffles - Prefer shuffles in the following order:
4704 // 1. [ssse3] 1 x pshufb
4705 // 2. [ssse3] 2 x pshufb + 1 x por
4706 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4707 static
4708 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4709                                  SelectionDAG &DAG,
4710                                  const X86TargetLowering &TLI) {
4711   SDValue V1 = SVOp->getOperand(0);
4712   SDValue V2 = SVOp->getOperand(1);
4713   DebugLoc dl = SVOp->getDebugLoc();
4714   SmallVector<int, 16> MaskVals;
4715   SVOp->getMask(MaskVals);
4716
4717   // If we have SSSE3, case 1 is generated when all result bytes come from
4718   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4719   // present, fall back to case 3.
4720   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4721   bool V1Only = true;
4722   bool V2Only = true;
4723   for (unsigned i = 0; i < 16; ++i) {
4724     int EltIdx = MaskVals[i];
4725     if (EltIdx < 0)
4726       continue;
4727     if (EltIdx < 16)
4728       V2Only = false;
4729     else
4730       V1Only = false;
4731   }
4732
4733   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4734   if (TLI.getSubtarget()->hasSSSE3()) {
4735     SmallVector<SDValue,16> pshufbMask;
4736
4737     // If all result elements are from one input vector, then only translate
4738     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4739     //
4740     // Otherwise, we have elements from both input vectors, and must zero out
4741     // elements that come from V2 in the first mask, and V1 in the second mask
4742     // so that we can OR them together.
4743     bool TwoInputs = !(V1Only || V2Only);
4744     for (unsigned i = 0; i != 16; ++i) {
4745       int EltIdx = MaskVals[i];
4746       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4747         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4748         continue;
4749       }
4750       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4751     }
4752     // If all the elements are from V2, assign it to V1 and return after
4753     // building the first pshufb.
4754     if (V2Only)
4755       V1 = V2;
4756     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4757                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4758                                  MVT::v16i8, &pshufbMask[0], 16));
4759     if (!TwoInputs)
4760       return V1;
4761
4762     // Calculate the shuffle mask for the second input, shuffle it, and
4763     // OR it with the first shuffled input.
4764     pshufbMask.clear();
4765     for (unsigned i = 0; i != 16; ++i) {
4766       int EltIdx = MaskVals[i];
4767       if (EltIdx < 16) {
4768         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4769         continue;
4770       }
4771       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4772     }
4773     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4774                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4775                                  MVT::v16i8, &pshufbMask[0], 16));
4776     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4777   }
4778
4779   // No SSSE3 - Calculate in place words and then fix all out of place words
4780   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4781   // the 16 different words that comprise the two doublequadword input vectors.
4782   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4783   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4784   SDValue NewV = V2Only ? V2 : V1;
4785   for (int i = 0; i != 8; ++i) {
4786     int Elt0 = MaskVals[i*2];
4787     int Elt1 = MaskVals[i*2+1];
4788
4789     // This word of the result is all undef, skip it.
4790     if (Elt0 < 0 && Elt1 < 0)
4791       continue;
4792
4793     // This word of the result is already in the correct place, skip it.
4794     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4795       continue;
4796     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4797       continue;
4798
4799     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4800     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4801     SDValue InsElt;
4802
4803     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4804     // using a single extract together, load it and store it.
4805     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4806       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4807                            DAG.getIntPtrConstant(Elt1 / 2));
4808       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4809                         DAG.getIntPtrConstant(i));
4810       continue;
4811     }
4812
4813     // If Elt1 is defined, extract it from the appropriate source.  If the
4814     // source byte is not also odd, shift the extracted word left 8 bits
4815     // otherwise clear the bottom 8 bits if we need to do an or.
4816     if (Elt1 >= 0) {
4817       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4818                            DAG.getIntPtrConstant(Elt1 / 2));
4819       if ((Elt1 & 1) == 0)
4820         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4821                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4822       else if (Elt0 >= 0)
4823         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4824                              DAG.getConstant(0xFF00, MVT::i16));
4825     }
4826     // If Elt0 is defined, extract it from the appropriate source.  If the
4827     // source byte is not also even, shift the extracted word right 8 bits. If
4828     // Elt1 was also defined, OR the extracted values together before
4829     // inserting them in the result.
4830     if (Elt0 >= 0) {
4831       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4832                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4833       if ((Elt0 & 1) != 0)
4834         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4835                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4836       else if (Elt1 >= 0)
4837         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4838                              DAG.getConstant(0x00FF, MVT::i16));
4839       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4840                          : InsElt0;
4841     }
4842     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4843                        DAG.getIntPtrConstant(i));
4844   }
4845   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4846 }
4847
4848 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4849 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4850 /// done when every pair / quad of shuffle mask elements point to elements in
4851 /// the right sequence. e.g.
4852 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4853 static
4854 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4855                                  SelectionDAG &DAG, DebugLoc dl) {
4856   EVT VT = SVOp->getValueType(0);
4857   SDValue V1 = SVOp->getOperand(0);
4858   SDValue V2 = SVOp->getOperand(1);
4859   unsigned NumElems = VT.getVectorNumElements();
4860   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4861   EVT NewVT;
4862   switch (VT.getSimpleVT().SimpleTy) {
4863   default: assert(false && "Unexpected!");
4864   case MVT::v4f32: NewVT = MVT::v2f64; break;
4865   case MVT::v4i32: NewVT = MVT::v2i64; break;
4866   case MVT::v8i16: NewVT = MVT::v4i32; break;
4867   case MVT::v16i8: NewVT = MVT::v4i32; break;
4868   }
4869
4870   int Scale = NumElems / NewWidth;
4871   SmallVector<int, 8> MaskVec;
4872   for (unsigned i = 0; i < NumElems; i += Scale) {
4873     int StartIdx = -1;
4874     for (int j = 0; j < Scale; ++j) {
4875       int EltIdx = SVOp->getMaskElt(i+j);
4876       if (EltIdx < 0)
4877         continue;
4878       if (StartIdx == -1)
4879         StartIdx = EltIdx - (EltIdx % Scale);
4880       if (EltIdx != StartIdx + j)
4881         return SDValue();
4882     }
4883     if (StartIdx == -1)
4884       MaskVec.push_back(-1);
4885     else
4886       MaskVec.push_back(StartIdx / Scale);
4887   }
4888
4889   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4890   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4891   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4892 }
4893
4894 /// getVZextMovL - Return a zero-extending vector move low node.
4895 ///
4896 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4897                             SDValue SrcOp, SelectionDAG &DAG,
4898                             const X86Subtarget *Subtarget, DebugLoc dl) {
4899   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4900     LoadSDNode *LD = NULL;
4901     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4902       LD = dyn_cast<LoadSDNode>(SrcOp);
4903     if (!LD) {
4904       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4905       // instead.
4906       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4907       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4908           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4909           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4910           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4911         // PR2108
4912         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4913         return DAG.getNode(ISD::BITCAST, dl, VT,
4914                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4915                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4916                                                    OpVT,
4917                                                    SrcOp.getOperand(0)
4918                                                           .getOperand(0))));
4919       }
4920     }
4921   }
4922
4923   return DAG.getNode(ISD::BITCAST, dl, VT,
4924                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4925                                  DAG.getNode(ISD::BITCAST, dl,
4926                                              OpVT, SrcOp)));
4927 }
4928
4929 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4930 /// shuffles.
4931 static SDValue
4932 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4933   SDValue V1 = SVOp->getOperand(0);
4934   SDValue V2 = SVOp->getOperand(1);
4935   DebugLoc dl = SVOp->getDebugLoc();
4936   EVT VT = SVOp->getValueType(0);
4937
4938   SmallVector<std::pair<int, int>, 8> Locs;
4939   Locs.resize(4);
4940   SmallVector<int, 8> Mask1(4U, -1);
4941   SmallVector<int, 8> PermMask;
4942   SVOp->getMask(PermMask);
4943
4944   unsigned NumHi = 0;
4945   unsigned NumLo = 0;
4946   for (unsigned i = 0; i != 4; ++i) {
4947     int Idx = PermMask[i];
4948     if (Idx < 0) {
4949       Locs[i] = std::make_pair(-1, -1);
4950     } else {
4951       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4952       if (Idx < 4) {
4953         Locs[i] = std::make_pair(0, NumLo);
4954         Mask1[NumLo] = Idx;
4955         NumLo++;
4956       } else {
4957         Locs[i] = std::make_pair(1, NumHi);
4958         if (2+NumHi < 4)
4959           Mask1[2+NumHi] = Idx;
4960         NumHi++;
4961       }
4962     }
4963   }
4964
4965   if (NumLo <= 2 && NumHi <= 2) {
4966     // If no more than two elements come from either vector. This can be
4967     // implemented with two shuffles. First shuffle gather the elements.
4968     // The second shuffle, which takes the first shuffle as both of its
4969     // vector operands, put the elements into the right order.
4970     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4971
4972     SmallVector<int, 8> Mask2(4U, -1);
4973
4974     for (unsigned i = 0; i != 4; ++i) {
4975       if (Locs[i].first == -1)
4976         continue;
4977       else {
4978         unsigned Idx = (i < 2) ? 0 : 4;
4979         Idx += Locs[i].first * 2 + Locs[i].second;
4980         Mask2[i] = Idx;
4981       }
4982     }
4983
4984     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4985   } else if (NumLo == 3 || NumHi == 3) {
4986     // Otherwise, we must have three elements from one vector, call it X, and
4987     // one element from the other, call it Y.  First, use a shufps to build an
4988     // intermediate vector with the one element from Y and the element from X
4989     // that will be in the same half in the final destination (the indexes don't
4990     // matter). Then, use a shufps to build the final vector, taking the half
4991     // containing the element from Y from the intermediate, and the other half
4992     // from X.
4993     if (NumHi == 3) {
4994       // Normalize it so the 3 elements come from V1.
4995       CommuteVectorShuffleMask(PermMask, VT);
4996       std::swap(V1, V2);
4997     }
4998
4999     // Find the element from V2.
5000     unsigned HiIndex;
5001     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5002       int Val = PermMask[HiIndex];
5003       if (Val < 0)
5004         continue;
5005       if (Val >= 4)
5006         break;
5007     }
5008
5009     Mask1[0] = PermMask[HiIndex];
5010     Mask1[1] = -1;
5011     Mask1[2] = PermMask[HiIndex^1];
5012     Mask1[3] = -1;
5013     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5014
5015     if (HiIndex >= 2) {
5016       Mask1[0] = PermMask[0];
5017       Mask1[1] = PermMask[1];
5018       Mask1[2] = HiIndex & 1 ? 6 : 4;
5019       Mask1[3] = HiIndex & 1 ? 4 : 6;
5020       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5021     } else {
5022       Mask1[0] = HiIndex & 1 ? 2 : 0;
5023       Mask1[1] = HiIndex & 1 ? 0 : 2;
5024       Mask1[2] = PermMask[2];
5025       Mask1[3] = PermMask[3];
5026       if (Mask1[2] >= 0)
5027         Mask1[2] += 4;
5028       if (Mask1[3] >= 0)
5029         Mask1[3] += 4;
5030       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5031     }
5032   }
5033
5034   // Break it into (shuffle shuffle_hi, shuffle_lo).
5035   Locs.clear();
5036   SmallVector<int,8> LoMask(4U, -1);
5037   SmallVector<int,8> HiMask(4U, -1);
5038
5039   SmallVector<int,8> *MaskPtr = &LoMask;
5040   unsigned MaskIdx = 0;
5041   unsigned LoIdx = 0;
5042   unsigned HiIdx = 2;
5043   for (unsigned i = 0; i != 4; ++i) {
5044     if (i == 2) {
5045       MaskPtr = &HiMask;
5046       MaskIdx = 1;
5047       LoIdx = 0;
5048       HiIdx = 2;
5049     }
5050     int Idx = PermMask[i];
5051     if (Idx < 0) {
5052       Locs[i] = std::make_pair(-1, -1);
5053     } else if (Idx < 4) {
5054       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5055       (*MaskPtr)[LoIdx] = Idx;
5056       LoIdx++;
5057     } else {
5058       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5059       (*MaskPtr)[HiIdx] = Idx;
5060       HiIdx++;
5061     }
5062   }
5063
5064   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5065   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5066   SmallVector<int, 8> MaskOps;
5067   for (unsigned i = 0; i != 4; ++i) {
5068     if (Locs[i].first == -1) {
5069       MaskOps.push_back(-1);
5070     } else {
5071       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5072       MaskOps.push_back(Idx);
5073     }
5074   }
5075   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5076 }
5077
5078 static bool MayFoldVectorLoad(SDValue V) {
5079   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5080     V = V.getOperand(0);
5081   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5082     V = V.getOperand(0);
5083   if (MayFoldLoad(V))
5084     return true;
5085   return false;
5086 }
5087
5088 // FIXME: the version above should always be used. Since there's
5089 // a bug where several vector shuffles can't be folded because the
5090 // DAG is not updated during lowering and a node claims to have two
5091 // uses while it only has one, use this version, and let isel match
5092 // another instruction if the load really happens to have more than
5093 // one use. Remove this version after this bug get fixed.
5094 // rdar://8434668, PR8156
5095 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5096   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5097     V = V.getOperand(0);
5098   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5099     V = V.getOperand(0);
5100   if (ISD::isNormalLoad(V.getNode()))
5101     return true;
5102   return false;
5103 }
5104
5105 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5106 /// a vector extract, and if both can be later optimized into a single load.
5107 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5108 /// here because otherwise a target specific shuffle node is going to be
5109 /// emitted for this shuffle, and the optimization not done.
5110 /// FIXME: This is probably not the best approach, but fix the problem
5111 /// until the right path is decided.
5112 static
5113 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5114                                          const TargetLowering &TLI) {
5115   EVT VT = V.getValueType();
5116   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5117
5118   // Be sure that the vector shuffle is present in a pattern like this:
5119   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5120   if (!V.hasOneUse())
5121     return false;
5122
5123   SDNode *N = *V.getNode()->use_begin();
5124   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5125     return false;
5126
5127   SDValue EltNo = N->getOperand(1);
5128   if (!isa<ConstantSDNode>(EltNo))
5129     return false;
5130
5131   // If the bit convert changed the number of elements, it is unsafe
5132   // to examine the mask.
5133   bool HasShuffleIntoBitcast = false;
5134   if (V.getOpcode() == ISD::BITCAST) {
5135     EVT SrcVT = V.getOperand(0).getValueType();
5136     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5137       return false;
5138     V = V.getOperand(0);
5139     HasShuffleIntoBitcast = true;
5140   }
5141
5142   // Select the input vector, guarding against out of range extract vector.
5143   unsigned NumElems = VT.getVectorNumElements();
5144   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5145   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5146   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5147
5148   // Skip one more bit_convert if necessary
5149   if (V.getOpcode() == ISD::BITCAST)
5150     V = V.getOperand(0);
5151
5152   if (ISD::isNormalLoad(V.getNode())) {
5153     // Is the original load suitable?
5154     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5155
5156     // FIXME: avoid the multi-use bug that is preventing lots of
5157     // of foldings to be detected, this is still wrong of course, but
5158     // give the temporary desired behavior, and if it happens that
5159     // the load has real more uses, during isel it will not fold, and
5160     // will generate poor code.
5161     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5162       return false;
5163
5164     if (!HasShuffleIntoBitcast)
5165       return true;
5166
5167     // If there's a bitcast before the shuffle, check if the load type and
5168     // alignment is valid.
5169     unsigned Align = LN0->getAlignment();
5170     unsigned NewAlign =
5171       TLI.getTargetData()->getABITypeAlignment(
5172                                     VT.getTypeForEVT(*DAG.getContext()));
5173
5174     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5175       return false;
5176   }
5177
5178   return true;
5179 }
5180
5181 static
5182 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5183   EVT VT = Op.getValueType();
5184
5185   // Canonizalize to v2f64.
5186   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5187   return DAG.getNode(ISD::BITCAST, dl, VT,
5188                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5189                                           V1, DAG));
5190 }
5191
5192 static
5193 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5194                         bool HasSSE2) {
5195   SDValue V1 = Op.getOperand(0);
5196   SDValue V2 = Op.getOperand(1);
5197   EVT VT = Op.getValueType();
5198
5199   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5200
5201   if (HasSSE2 && VT == MVT::v2f64)
5202     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5203
5204   // v4f32 or v4i32
5205   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5206 }
5207
5208 static
5209 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5210   SDValue V1 = Op.getOperand(0);
5211   SDValue V2 = Op.getOperand(1);
5212   EVT VT = Op.getValueType();
5213
5214   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5215          "unsupported shuffle type");
5216
5217   if (V2.getOpcode() == ISD::UNDEF)
5218     V2 = V1;
5219
5220   // v4i32 or v4f32
5221   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5222 }
5223
5224 static
5225 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5226   SDValue V1 = Op.getOperand(0);
5227   SDValue V2 = Op.getOperand(1);
5228   EVT VT = Op.getValueType();
5229   unsigned NumElems = VT.getVectorNumElements();
5230
5231   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5232   // operand of these instructions is only memory, so check if there's a
5233   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5234   // same masks.
5235   bool CanFoldLoad = false;
5236
5237   // Trivial case, when V2 comes from a load.
5238   if (MayFoldVectorLoad(V2))
5239     CanFoldLoad = true;
5240
5241   // When V1 is a load, it can be folded later into a store in isel, example:
5242   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5243   //    turns into:
5244   //  (MOVLPSmr addr:$src1, VR128:$src2)
5245   // So, recognize this potential and also use MOVLPS or MOVLPD
5246   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5247     CanFoldLoad = true;
5248
5249   if (CanFoldLoad) {
5250     if (HasSSE2 && NumElems == 2)
5251       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5252
5253     if (NumElems == 4)
5254       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5255   }
5256
5257   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5258   // movl and movlp will both match v2i64, but v2i64 is never matched by
5259   // movl earlier because we make it strict to avoid messing with the movlp load
5260   // folding logic (see the code above getMOVLP call). Match it here then,
5261   // this is horrible, but will stay like this until we move all shuffle
5262   // matching to x86 specific nodes. Note that for the 1st condition all
5263   // types are matched with movsd.
5264   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5265     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5266   else if (HasSSE2)
5267     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5268
5269
5270   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5271
5272   // Invert the operand order and use SHUFPS to match it.
5273   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5274                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5275 }
5276
5277 static inline unsigned getUNPCKLOpcode(EVT VT) {
5278   switch(VT.getSimpleVT().SimpleTy) {
5279   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5280   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5281   case MVT::v4f32: return X86ISD::UNPCKLPS;
5282   case MVT::v2f64: return X86ISD::UNPCKLPD;
5283   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5284   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5285   default:
5286     llvm_unreachable("Unknow type for unpckl");
5287   }
5288   return 0;
5289 }
5290
5291 static inline unsigned getUNPCKHOpcode(EVT VT) {
5292   switch(VT.getSimpleVT().SimpleTy) {
5293   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5294   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5295   case MVT::v4f32: return X86ISD::UNPCKHPS;
5296   case MVT::v2f64: return X86ISD::UNPCKHPD;
5297   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5298   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5299   default:
5300     llvm_unreachable("Unknow type for unpckh");
5301   }
5302   return 0;
5303 }
5304
5305 static
5306 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5307                                const TargetLowering &TLI,
5308                                const X86Subtarget *Subtarget) {
5309   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5310   EVT VT = Op.getValueType();
5311   DebugLoc dl = Op.getDebugLoc();
5312   SDValue V1 = Op.getOperand(0);
5313   SDValue V2 = Op.getOperand(1);
5314
5315   if (isZeroShuffle(SVOp))
5316     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5317
5318   // Handle splat operations
5319   if (SVOp->isSplat()) {
5320     // Special case, this is the only place now where it's
5321     // allowed to return a vector_shuffle operation without
5322     // using a target specific node, because *hopefully* it
5323     // will be optimized away by the dag combiner.
5324     if (VT.getVectorNumElements() <= 4 &&
5325         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5326       return Op;
5327
5328     // Handle splats by matching through known masks
5329     if (VT.getVectorNumElements() <= 4)
5330       return SDValue();
5331
5332     // Canonicalize all of the remaining to v4f32.
5333     return PromoteSplat(SVOp, DAG);
5334   }
5335
5336   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5337   // do it!
5338   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5339     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5340     if (NewOp.getNode())
5341       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5342   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5343     // FIXME: Figure out a cleaner way to do this.
5344     // Try to make use of movq to zero out the top part.
5345     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5346       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5347       if (NewOp.getNode()) {
5348         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5349           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5350                               DAG, Subtarget, dl);
5351       }
5352     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5353       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5354       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5355         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5356                             DAG, Subtarget, dl);
5357     }
5358   }
5359   return SDValue();
5360 }
5361
5362 SDValue
5363 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5365   SDValue V1 = Op.getOperand(0);
5366   SDValue V2 = Op.getOperand(1);
5367   EVT VT = Op.getValueType();
5368   DebugLoc dl = Op.getDebugLoc();
5369   unsigned NumElems = VT.getVectorNumElements();
5370   bool isMMX = VT.getSizeInBits() == 64;
5371   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5372   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5373   bool V1IsSplat = false;
5374   bool V2IsSplat = false;
5375   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5376   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5377   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5378   MachineFunction &MF = DAG.getMachineFunction();
5379   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5380
5381   // Shuffle operations on MMX not supported.
5382   if (isMMX)
5383     return Op;
5384
5385   // Vector shuffle lowering takes 3 steps:
5386   //
5387   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5388   //    narrowing and commutation of operands should be handled.
5389   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5390   //    shuffle nodes.
5391   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5392   //    so the shuffle can be broken into other shuffles and the legalizer can
5393   //    try the lowering again.
5394   //
5395   // The general ideia is that no vector_shuffle operation should be left to
5396   // be matched during isel, all of them must be converted to a target specific
5397   // node here.
5398
5399   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5400   // narrowing and commutation of operands should be handled. The actual code
5401   // doesn't include all of those, work in progress...
5402   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5403   if (NewOp.getNode())
5404     return NewOp;
5405
5406   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5407   // unpckh_undef). Only use pshufd if speed is more important than size.
5408   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5409     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5410       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5411   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5412     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5413       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5414
5415   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5416       RelaxedMayFoldVectorLoad(V1))
5417     return getMOVDDup(Op, dl, V1, DAG);
5418
5419   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5420     return getMOVHighToLow(Op, dl, DAG);
5421
5422   // Use to match splats
5423   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5424       (VT == MVT::v2f64 || VT == MVT::v2i64))
5425     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5426
5427   if (X86::isPSHUFDMask(SVOp)) {
5428     // The actual implementation will match the mask in the if above and then
5429     // during isel it can match several different instructions, not only pshufd
5430     // as its name says, sad but true, emulate the behavior for now...
5431     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5432         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5433
5434     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5435
5436     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5437       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5438
5439     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5440       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5441                                   TargetMask, DAG);
5442
5443     if (VT == MVT::v4f32)
5444       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5445                                   TargetMask, DAG);
5446   }
5447
5448   // Check if this can be converted into a logical shift.
5449   bool isLeft = false;
5450   unsigned ShAmt = 0;
5451   SDValue ShVal;
5452   bool isShift = getSubtarget()->hasSSE2() &&
5453     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5454   if (isShift && ShVal.hasOneUse()) {
5455     // If the shifted value has multiple uses, it may be cheaper to use
5456     // v_set0 + movlhps or movhlps, etc.
5457     EVT EltVT = VT.getVectorElementType();
5458     ShAmt *= EltVT.getSizeInBits();
5459     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5460   }
5461
5462   if (X86::isMOVLMask(SVOp)) {
5463     if (V1IsUndef)
5464       return V2;
5465     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5466       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5467     if (!X86::isMOVLPMask(SVOp)) {
5468       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5469         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5470
5471       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5472         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5473     }
5474   }
5475
5476   // FIXME: fold these into legal mask.
5477   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5478     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5479
5480   if (X86::isMOVHLPSMask(SVOp))
5481     return getMOVHighToLow(Op, dl, DAG);
5482
5483   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5484     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5485
5486   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5487     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5488
5489   if (X86::isMOVLPMask(SVOp))
5490     return getMOVLP(Op, dl, DAG, HasSSE2);
5491
5492   if (ShouldXformToMOVHLPS(SVOp) ||
5493       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5494     return CommuteVectorShuffle(SVOp, DAG);
5495
5496   if (isShift) {
5497     // No better options. Use a vshl / vsrl.
5498     EVT EltVT = VT.getVectorElementType();
5499     ShAmt *= EltVT.getSizeInBits();
5500     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5501   }
5502
5503   bool Commuted = false;
5504   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5505   // 1,1,1,1 -> v8i16 though.
5506   V1IsSplat = isSplatVector(V1.getNode());
5507   V2IsSplat = isSplatVector(V2.getNode());
5508
5509   // Canonicalize the splat or undef, if present, to be on the RHS.
5510   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5511     Op = CommuteVectorShuffle(SVOp, DAG);
5512     SVOp = cast<ShuffleVectorSDNode>(Op);
5513     V1 = SVOp->getOperand(0);
5514     V2 = SVOp->getOperand(1);
5515     std::swap(V1IsSplat, V2IsSplat);
5516     std::swap(V1IsUndef, V2IsUndef);
5517     Commuted = true;
5518   }
5519
5520   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5521     // Shuffling low element of v1 into undef, just return v1.
5522     if (V2IsUndef)
5523       return V1;
5524     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5525     // the instruction selector will not match, so get a canonical MOVL with
5526     // swapped operands to undo the commute.
5527     return getMOVL(DAG, dl, VT, V2, V1);
5528   }
5529
5530   if (X86::isUNPCKLMask(SVOp))
5531     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5532
5533   if (X86::isUNPCKHMask(SVOp))
5534     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5535
5536   if (V2IsSplat) {
5537     // Normalize mask so all entries that point to V2 points to its first
5538     // element then try to match unpck{h|l} again. If match, return a
5539     // new vector_shuffle with the corrected mask.
5540     SDValue NewMask = NormalizeMask(SVOp, DAG);
5541     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5542     if (NSVOp != SVOp) {
5543       if (X86::isUNPCKLMask(NSVOp, true)) {
5544         return NewMask;
5545       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5546         return NewMask;
5547       }
5548     }
5549   }
5550
5551   if (Commuted) {
5552     // Commute is back and try unpck* again.
5553     // FIXME: this seems wrong.
5554     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5555     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5556
5557     if (X86::isUNPCKLMask(NewSVOp))
5558       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5559
5560     if (X86::isUNPCKHMask(NewSVOp))
5561       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5562   }
5563
5564   // Normalize the node to match x86 shuffle ops if needed
5565   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5566     return CommuteVectorShuffle(SVOp, DAG);
5567
5568   // The checks below are all present in isShuffleMaskLegal, but they are
5569   // inlined here right now to enable us to directly emit target specific
5570   // nodes, and remove one by one until they don't return Op anymore.
5571   SmallVector<int, 16> M;
5572   SVOp->getMask(M);
5573
5574   if (isPALIGNRMask(M, VT, HasSSSE3))
5575     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5576                                 X86::getShufflePALIGNRImmediate(SVOp),
5577                                 DAG);
5578
5579   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5580       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5581     if (VT == MVT::v2f64)
5582       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5583     if (VT == MVT::v2i64)
5584       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5585   }
5586
5587   if (isPSHUFHWMask(M, VT))
5588     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5589                                 X86::getShufflePSHUFHWImmediate(SVOp),
5590                                 DAG);
5591
5592   if (isPSHUFLWMask(M, VT))
5593     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5594                                 X86::getShufflePSHUFLWImmediate(SVOp),
5595                                 DAG);
5596
5597   if (isSHUFPMask(M, VT)) {
5598     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5599     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5600       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5601                                   TargetMask, DAG);
5602     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5603       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5604                                   TargetMask, DAG);
5605   }
5606
5607   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5608     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5609       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5610   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5611     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5612       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5613
5614   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5615   if (VT == MVT::v8i16) {
5616     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5617     if (NewOp.getNode())
5618       return NewOp;
5619   }
5620
5621   if (VT == MVT::v16i8) {
5622     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5623     if (NewOp.getNode())
5624       return NewOp;
5625   }
5626
5627   // Handle all 4 wide cases with a number of shuffles.
5628   if (NumElems == 4)
5629     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5630
5631   return SDValue();
5632 }
5633
5634 SDValue
5635 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5636                                                 SelectionDAG &DAG) const {
5637   EVT VT = Op.getValueType();
5638   DebugLoc dl = Op.getDebugLoc();
5639   if (VT.getSizeInBits() == 8) {
5640     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5641                                     Op.getOperand(0), Op.getOperand(1));
5642     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5643                                     DAG.getValueType(VT));
5644     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5645   } else if (VT.getSizeInBits() == 16) {
5646     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5647     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5648     if (Idx == 0)
5649       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5650                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5651                                      DAG.getNode(ISD::BITCAST, dl,
5652                                                  MVT::v4i32,
5653                                                  Op.getOperand(0)),
5654                                      Op.getOperand(1)));
5655     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5656                                     Op.getOperand(0), Op.getOperand(1));
5657     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5658                                     DAG.getValueType(VT));
5659     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5660   } else if (VT == MVT::f32) {
5661     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5662     // the result back to FR32 register. It's only worth matching if the
5663     // result has a single use which is a store or a bitcast to i32.  And in
5664     // the case of a store, it's not worth it if the index is a constant 0,
5665     // because a MOVSSmr can be used instead, which is smaller and faster.
5666     if (!Op.hasOneUse())
5667       return SDValue();
5668     SDNode *User = *Op.getNode()->use_begin();
5669     if ((User->getOpcode() != ISD::STORE ||
5670          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5671           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5672         (User->getOpcode() != ISD::BITCAST ||
5673          User->getValueType(0) != MVT::i32))
5674       return SDValue();
5675     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5676                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5677                                               Op.getOperand(0)),
5678                                               Op.getOperand(1));
5679     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5680   } else if (VT == MVT::i32) {
5681     // ExtractPS works with constant index.
5682     if (isa<ConstantSDNode>(Op.getOperand(1)))
5683       return Op;
5684   }
5685   return SDValue();
5686 }
5687
5688
5689 SDValue
5690 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5691                                            SelectionDAG &DAG) const {
5692   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5693     return SDValue();
5694
5695   if (Subtarget->hasSSE41()) {
5696     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5697     if (Res.getNode())
5698       return Res;
5699   }
5700
5701   EVT VT = Op.getValueType();
5702   DebugLoc dl = Op.getDebugLoc();
5703   // TODO: handle v16i8.
5704   if (VT.getSizeInBits() == 16) {
5705     SDValue Vec = Op.getOperand(0);
5706     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5707     if (Idx == 0)
5708       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5709                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5710                                      DAG.getNode(ISD::BITCAST, dl,
5711                                                  MVT::v4i32, Vec),
5712                                      Op.getOperand(1)));
5713     // Transform it so it match pextrw which produces a 32-bit result.
5714     EVT EltVT = MVT::i32;
5715     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5716                                     Op.getOperand(0), Op.getOperand(1));
5717     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5718                                     DAG.getValueType(VT));
5719     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5720   } else if (VT.getSizeInBits() == 32) {
5721     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5722     if (Idx == 0)
5723       return Op;
5724
5725     // SHUFPS the element to the lowest double word, then movss.
5726     int Mask[4] = { Idx, -1, -1, -1 };
5727     EVT VVT = Op.getOperand(0).getValueType();
5728     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5729                                        DAG.getUNDEF(VVT), Mask);
5730     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5731                        DAG.getIntPtrConstant(0));
5732   } else if (VT.getSizeInBits() == 64) {
5733     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5734     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5735     //        to match extract_elt for f64.
5736     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5737     if (Idx == 0)
5738       return Op;
5739
5740     // UNPCKHPD the element to the lowest double word, then movsd.
5741     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5742     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5743     int Mask[2] = { 1, -1 };
5744     EVT VVT = Op.getOperand(0).getValueType();
5745     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5746                                        DAG.getUNDEF(VVT), Mask);
5747     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5748                        DAG.getIntPtrConstant(0));
5749   }
5750
5751   return SDValue();
5752 }
5753
5754 SDValue
5755 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5756                                                SelectionDAG &DAG) const {
5757   EVT VT = Op.getValueType();
5758   EVT EltVT = VT.getVectorElementType();
5759   DebugLoc dl = Op.getDebugLoc();
5760
5761   SDValue N0 = Op.getOperand(0);
5762   SDValue N1 = Op.getOperand(1);
5763   SDValue N2 = Op.getOperand(2);
5764
5765   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5766       isa<ConstantSDNode>(N2)) {
5767     unsigned Opc;
5768     if (VT == MVT::v8i16)
5769       Opc = X86ISD::PINSRW;
5770     else if (VT == MVT::v16i8)
5771       Opc = X86ISD::PINSRB;
5772     else
5773       Opc = X86ISD::PINSRB;
5774
5775     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5776     // argument.
5777     if (N1.getValueType() != MVT::i32)
5778       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5779     if (N2.getValueType() != MVT::i32)
5780       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5781     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5782   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5783     // Bits [7:6] of the constant are the source select.  This will always be
5784     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5785     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5786     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5787     // Bits [5:4] of the constant are the destination select.  This is the
5788     //  value of the incoming immediate.
5789     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5790     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5791     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5792     // Create this as a scalar to vector..
5793     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5794     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5795   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5796     // PINSR* works with constant index.
5797     return Op;
5798   }
5799   return SDValue();
5800 }
5801
5802 SDValue
5803 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5804   EVT VT = Op.getValueType();
5805   EVT EltVT = VT.getVectorElementType();
5806
5807   if (Subtarget->hasSSE41())
5808     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5809
5810   if (EltVT == MVT::i8)
5811     return SDValue();
5812
5813   DebugLoc dl = Op.getDebugLoc();
5814   SDValue N0 = Op.getOperand(0);
5815   SDValue N1 = Op.getOperand(1);
5816   SDValue N2 = Op.getOperand(2);
5817
5818   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5819     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5820     // as its second argument.
5821     if (N1.getValueType() != MVT::i32)
5822       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5823     if (N2.getValueType() != MVT::i32)
5824       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5825     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5826   }
5827   return SDValue();
5828 }
5829
5830 SDValue
5831 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5832   DebugLoc dl = Op.getDebugLoc();
5833
5834   if (Op.getValueType() == MVT::v1i64 &&
5835       Op.getOperand(0).getValueType() == MVT::i64)
5836     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5837
5838   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5839   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5840          "Expected an SSE type!");
5841   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5842                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5843 }
5844
5845 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5846 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5847 // one of the above mentioned nodes. It has to be wrapped because otherwise
5848 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5849 // be used to form addressing mode. These wrapped nodes will be selected
5850 // into MOV32ri.
5851 SDValue
5852 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5853   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5854
5855   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5856   // global base reg.
5857   unsigned char OpFlag = 0;
5858   unsigned WrapperKind = X86ISD::Wrapper;
5859   CodeModel::Model M = getTargetMachine().getCodeModel();
5860
5861   if (Subtarget->isPICStyleRIPRel() &&
5862       (M == CodeModel::Small || M == CodeModel::Kernel))
5863     WrapperKind = X86ISD::WrapperRIP;
5864   else if (Subtarget->isPICStyleGOT())
5865     OpFlag = X86II::MO_GOTOFF;
5866   else if (Subtarget->isPICStyleStubPIC())
5867     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5868
5869   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5870                                              CP->getAlignment(),
5871                                              CP->getOffset(), OpFlag);
5872   DebugLoc DL = CP->getDebugLoc();
5873   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5874   // With PIC, the address is actually $g + Offset.
5875   if (OpFlag) {
5876     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5877                          DAG.getNode(X86ISD::GlobalBaseReg,
5878                                      DebugLoc(), getPointerTy()),
5879                          Result);
5880   }
5881
5882   return Result;
5883 }
5884
5885 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5886   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5887
5888   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5889   // global base reg.
5890   unsigned char OpFlag = 0;
5891   unsigned WrapperKind = X86ISD::Wrapper;
5892   CodeModel::Model M = getTargetMachine().getCodeModel();
5893
5894   if (Subtarget->isPICStyleRIPRel() &&
5895       (M == CodeModel::Small || M == CodeModel::Kernel))
5896     WrapperKind = X86ISD::WrapperRIP;
5897   else if (Subtarget->isPICStyleGOT())
5898     OpFlag = X86II::MO_GOTOFF;
5899   else if (Subtarget->isPICStyleStubPIC())
5900     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5901
5902   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5903                                           OpFlag);
5904   DebugLoc DL = JT->getDebugLoc();
5905   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5906
5907   // With PIC, the address is actually $g + Offset.
5908   if (OpFlag)
5909     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5910                          DAG.getNode(X86ISD::GlobalBaseReg,
5911                                      DebugLoc(), getPointerTy()),
5912                          Result);
5913
5914   return Result;
5915 }
5916
5917 SDValue
5918 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5919   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5920
5921   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5922   // global base reg.
5923   unsigned char OpFlag = 0;
5924   unsigned WrapperKind = X86ISD::Wrapper;
5925   CodeModel::Model M = getTargetMachine().getCodeModel();
5926
5927   if (Subtarget->isPICStyleRIPRel() &&
5928       (M == CodeModel::Small || M == CodeModel::Kernel))
5929     WrapperKind = X86ISD::WrapperRIP;
5930   else if (Subtarget->isPICStyleGOT())
5931     OpFlag = X86II::MO_GOTOFF;
5932   else if (Subtarget->isPICStyleStubPIC())
5933     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5934
5935   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5936
5937   DebugLoc DL = Op.getDebugLoc();
5938   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5939
5940
5941   // With PIC, the address is actually $g + Offset.
5942   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5943       !Subtarget->is64Bit()) {
5944     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5945                          DAG.getNode(X86ISD::GlobalBaseReg,
5946                                      DebugLoc(), getPointerTy()),
5947                          Result);
5948   }
5949
5950   return Result;
5951 }
5952
5953 SDValue
5954 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5955   // Create the TargetBlockAddressAddress node.
5956   unsigned char OpFlags =
5957     Subtarget->ClassifyBlockAddressReference();
5958   CodeModel::Model M = getTargetMachine().getCodeModel();
5959   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5960   DebugLoc dl = Op.getDebugLoc();
5961   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5962                                        /*isTarget=*/true, OpFlags);
5963
5964   if (Subtarget->isPICStyleRIPRel() &&
5965       (M == CodeModel::Small || M == CodeModel::Kernel))
5966     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5967   else
5968     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5969
5970   // With PIC, the address is actually $g + Offset.
5971   if (isGlobalRelativeToPICBase(OpFlags)) {
5972     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5973                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5974                          Result);
5975   }
5976
5977   return Result;
5978 }
5979
5980 SDValue
5981 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5982                                       int64_t Offset,
5983                                       SelectionDAG &DAG) const {
5984   // Create the TargetGlobalAddress node, folding in the constant
5985   // offset if it is legal.
5986   unsigned char OpFlags =
5987     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5988   CodeModel::Model M = getTargetMachine().getCodeModel();
5989   SDValue Result;
5990   if (OpFlags == X86II::MO_NO_FLAG &&
5991       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5992     // A direct static reference to a global.
5993     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5994     Offset = 0;
5995   } else {
5996     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5997   }
5998
5999   if (Subtarget->isPICStyleRIPRel() &&
6000       (M == CodeModel::Small || M == CodeModel::Kernel))
6001     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6002   else
6003     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6004
6005   // With PIC, the address is actually $g + Offset.
6006   if (isGlobalRelativeToPICBase(OpFlags)) {
6007     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6008                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6009                          Result);
6010   }
6011
6012   // For globals that require a load from a stub to get the address, emit the
6013   // load.
6014   if (isGlobalStubReference(OpFlags))
6015     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6016                          MachinePointerInfo::getGOT(), false, false, 0);
6017
6018   // If there was a non-zero offset that we didn't fold, create an explicit
6019   // addition for it.
6020   if (Offset != 0)
6021     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6022                          DAG.getConstant(Offset, getPointerTy()));
6023
6024   return Result;
6025 }
6026
6027 SDValue
6028 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6029   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6030   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6031   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6032 }
6033
6034 static SDValue
6035 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6036            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6037            unsigned char OperandFlags) {
6038   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6039   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6040   DebugLoc dl = GA->getDebugLoc();
6041   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6042                                            GA->getValueType(0),
6043                                            GA->getOffset(),
6044                                            OperandFlags);
6045   if (InFlag) {
6046     SDValue Ops[] = { Chain,  TGA, *InFlag };
6047     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6048   } else {
6049     SDValue Ops[]  = { Chain, TGA };
6050     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6051   }
6052
6053   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6054   MFI->setAdjustsStack(true);
6055
6056   SDValue Flag = Chain.getValue(1);
6057   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6058 }
6059
6060 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6061 static SDValue
6062 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6063                                 const EVT PtrVT) {
6064   SDValue InFlag;
6065   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6066   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6067                                      DAG.getNode(X86ISD::GlobalBaseReg,
6068                                                  DebugLoc(), PtrVT), InFlag);
6069   InFlag = Chain.getValue(1);
6070
6071   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6072 }
6073
6074 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6075 static SDValue
6076 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6077                                 const EVT PtrVT) {
6078   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6079                     X86::RAX, X86II::MO_TLSGD);
6080 }
6081
6082 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6083 // "local exec" model.
6084 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6085                                    const EVT PtrVT, TLSModel::Model model,
6086                                    bool is64Bit) {
6087   DebugLoc dl = GA->getDebugLoc();
6088
6089   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6090   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6091                                                          is64Bit ? 257 : 256));
6092
6093   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6094                                       DAG.getIntPtrConstant(0),
6095                                       MachinePointerInfo(Ptr), false, false, 0);
6096
6097   unsigned char OperandFlags = 0;
6098   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6099   // initialexec.
6100   unsigned WrapperKind = X86ISD::Wrapper;
6101   if (model == TLSModel::LocalExec) {
6102     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6103   } else if (is64Bit) {
6104     assert(model == TLSModel::InitialExec);
6105     OperandFlags = X86II::MO_GOTTPOFF;
6106     WrapperKind = X86ISD::WrapperRIP;
6107   } else {
6108     assert(model == TLSModel::InitialExec);
6109     OperandFlags = X86II::MO_INDNTPOFF;
6110   }
6111
6112   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6113   // exec)
6114   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6115                                            GA->getValueType(0),
6116                                            GA->getOffset(), OperandFlags);
6117   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6118
6119   if (model == TLSModel::InitialExec)
6120     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6121                          MachinePointerInfo::getGOT(), false, false, 0);
6122
6123   // The address of the thread local variable is the add of the thread
6124   // pointer with the offset of the variable.
6125   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6126 }
6127
6128 SDValue
6129 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6130
6131   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6132   const GlobalValue *GV = GA->getGlobal();
6133
6134   if (Subtarget->isTargetELF()) {
6135     // TODO: implement the "local dynamic" model
6136     // TODO: implement the "initial exec"model for pic executables
6137
6138     // If GV is an alias then use the aliasee for determining
6139     // thread-localness.
6140     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6141       GV = GA->resolveAliasedGlobal(false);
6142
6143     TLSModel::Model model
6144       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6145
6146     switch (model) {
6147       case TLSModel::GeneralDynamic:
6148       case TLSModel::LocalDynamic: // not implemented
6149         if (Subtarget->is64Bit())
6150           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6151         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6152
6153       case TLSModel::InitialExec:
6154       case TLSModel::LocalExec:
6155         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6156                                    Subtarget->is64Bit());
6157     }
6158   } else if (Subtarget->isTargetDarwin()) {
6159     // Darwin only has one model of TLS.  Lower to that.
6160     unsigned char OpFlag = 0;
6161     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6162                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6163
6164     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6165     // global base reg.
6166     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6167                   !Subtarget->is64Bit();
6168     if (PIC32)
6169       OpFlag = X86II::MO_TLVP_PIC_BASE;
6170     else
6171       OpFlag = X86II::MO_TLVP;
6172     DebugLoc DL = Op.getDebugLoc();
6173     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6174                                                 getPointerTy(),
6175                                                 GA->getOffset(), OpFlag);
6176     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6177
6178     // With PIC32, the address is actually $g + Offset.
6179     if (PIC32)
6180       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6181                            DAG.getNode(X86ISD::GlobalBaseReg,
6182                                        DebugLoc(), getPointerTy()),
6183                            Offset);
6184
6185     // Lowering the machine isd will make sure everything is in the right
6186     // location.
6187     SDValue Args[] = { Offset };
6188     SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6189
6190     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6191     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6192     MFI->setAdjustsStack(true);
6193
6194     // And our return value (tls address) is in the standard call return value
6195     // location.
6196     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6197     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6198   }
6199
6200   assert(false &&
6201          "TLS not implemented for this target.");
6202
6203   llvm_unreachable("Unreachable");
6204   return SDValue();
6205 }
6206
6207
6208 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6209 /// take a 2 x i32 value to shift plus a shift amount.
6210 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6211   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6212   EVT VT = Op.getValueType();
6213   unsigned VTBits = VT.getSizeInBits();
6214   DebugLoc dl = Op.getDebugLoc();
6215   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6216   SDValue ShOpLo = Op.getOperand(0);
6217   SDValue ShOpHi = Op.getOperand(1);
6218   SDValue ShAmt  = Op.getOperand(2);
6219   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6220                                      DAG.getConstant(VTBits - 1, MVT::i8))
6221                        : DAG.getConstant(0, VT);
6222
6223   SDValue Tmp2, Tmp3;
6224   if (Op.getOpcode() == ISD::SHL_PARTS) {
6225     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6226     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6227   } else {
6228     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6229     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6230   }
6231
6232   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6233                                 DAG.getConstant(VTBits, MVT::i8));
6234   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6235                              AndNode, DAG.getConstant(0, MVT::i8));
6236
6237   SDValue Hi, Lo;
6238   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6239   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6240   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6241
6242   if (Op.getOpcode() == ISD::SHL_PARTS) {
6243     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6244     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6245   } else {
6246     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6247     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6248   }
6249
6250   SDValue Ops[2] = { Lo, Hi };
6251   return DAG.getMergeValues(Ops, 2, dl);
6252 }
6253
6254 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6255                                            SelectionDAG &DAG) const {
6256   EVT SrcVT = Op.getOperand(0).getValueType();
6257
6258   if (SrcVT.isVector())
6259     return SDValue();
6260
6261   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6262          "Unknown SINT_TO_FP to lower!");
6263
6264   // These are really Legal; return the operand so the caller accepts it as
6265   // Legal.
6266   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6267     return Op;
6268   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6269       Subtarget->is64Bit()) {
6270     return Op;
6271   }
6272
6273   DebugLoc dl = Op.getDebugLoc();
6274   unsigned Size = SrcVT.getSizeInBits()/8;
6275   MachineFunction &MF = DAG.getMachineFunction();
6276   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6277   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6278   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6279                                StackSlot,
6280                                MachinePointerInfo::getFixedStack(SSFI),
6281                                false, false, 0);
6282   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6283 }
6284
6285 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6286                                      SDValue StackSlot,
6287                                      SelectionDAG &DAG) const {
6288   // Build the FILD
6289   DebugLoc DL = Op.getDebugLoc();
6290   SDVTList Tys;
6291   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6292   if (useSSE)
6293     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6294   else
6295     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6296
6297   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6298
6299   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6300   MachineMemOperand *MMO =
6301     DAG.getMachineFunction()
6302     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6303                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6304
6305   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6306   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6307                                            X86ISD::FILD, DL,
6308                                            Tys, Ops, array_lengthof(Ops),
6309                                            SrcVT, MMO);
6310
6311   if (useSSE) {
6312     Chain = Result.getValue(1);
6313     SDValue InFlag = Result.getValue(2);
6314
6315     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6316     // shouldn't be necessary except that RFP cannot be live across
6317     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6318     MachineFunction &MF = DAG.getMachineFunction();
6319     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6320     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6321     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6322     Tys = DAG.getVTList(MVT::Other);
6323     SDValue Ops[] = {
6324       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6325     };
6326     MachineMemOperand *MMO =
6327       DAG.getMachineFunction()
6328       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6329                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6330
6331     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6332                                     Ops, array_lengthof(Ops),
6333                                     Op.getValueType(), MMO);
6334     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6335                          MachinePointerInfo::getFixedStack(SSFI),
6336                          false, false, 0);
6337   }
6338
6339   return Result;
6340 }
6341
6342 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6343 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6344                                                SelectionDAG &DAG) const {
6345   // This algorithm is not obvious. Here it is in C code, more or less:
6346   /*
6347     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6348       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6349       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6350
6351       // Copy ints to xmm registers.
6352       __m128i xh = _mm_cvtsi32_si128( hi );
6353       __m128i xl = _mm_cvtsi32_si128( lo );
6354
6355       // Combine into low half of a single xmm register.
6356       __m128i x = _mm_unpacklo_epi32( xh, xl );
6357       __m128d d;
6358       double sd;
6359
6360       // Merge in appropriate exponents to give the integer bits the right
6361       // magnitude.
6362       x = _mm_unpacklo_epi32( x, exp );
6363
6364       // Subtract away the biases to deal with the IEEE-754 double precision
6365       // implicit 1.
6366       d = _mm_sub_pd( (__m128d) x, bias );
6367
6368       // All conversions up to here are exact. The correctly rounded result is
6369       // calculated using the current rounding mode using the following
6370       // horizontal add.
6371       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6372       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6373                                 // store doesn't really need to be here (except
6374                                 // maybe to zero the other double)
6375       return sd;
6376     }
6377   */
6378
6379   DebugLoc dl = Op.getDebugLoc();
6380   LLVMContext *Context = DAG.getContext();
6381
6382   // Build some magic constants.
6383   std::vector<Constant*> CV0;
6384   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6385   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6386   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6387   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6388   Constant *C0 = ConstantVector::get(CV0);
6389   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6390
6391   std::vector<Constant*> CV1;
6392   CV1.push_back(
6393     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6394   CV1.push_back(
6395     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6396   Constant *C1 = ConstantVector::get(CV1);
6397   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6398
6399   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6400                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6401                                         Op.getOperand(0),
6402                                         DAG.getIntPtrConstant(1)));
6403   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6404                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6405                                         Op.getOperand(0),
6406                                         DAG.getIntPtrConstant(0)));
6407   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6408   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6409                               MachinePointerInfo::getConstantPool(),
6410                               false, false, 16);
6411   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6412   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6413   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6414                               MachinePointerInfo::getConstantPool(),
6415                               false, false, 16);
6416   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6417
6418   // Add the halves; easiest way is to swap them into another reg first.
6419   int ShufMask[2] = { 1, -1 };
6420   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6421                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6422   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6423   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6424                      DAG.getIntPtrConstant(0));
6425 }
6426
6427 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6428 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6429                                                SelectionDAG &DAG) const {
6430   DebugLoc dl = Op.getDebugLoc();
6431   // FP constant to bias correct the final result.
6432   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6433                                    MVT::f64);
6434
6435   // Load the 32-bit value into an XMM register.
6436   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6437                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6438                                          Op.getOperand(0),
6439                                          DAG.getIntPtrConstant(0)));
6440
6441   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6442                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6443                      DAG.getIntPtrConstant(0));
6444
6445   // Or the load with the bias.
6446   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6447                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6448                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6449                                                    MVT::v2f64, Load)),
6450                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6451                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6452                                                    MVT::v2f64, Bias)));
6453   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6454                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6455                    DAG.getIntPtrConstant(0));
6456
6457   // Subtract the bias.
6458   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6459
6460   // Handle final rounding.
6461   EVT DestVT = Op.getValueType();
6462
6463   if (DestVT.bitsLT(MVT::f64)) {
6464     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6465                        DAG.getIntPtrConstant(0));
6466   } else if (DestVT.bitsGT(MVT::f64)) {
6467     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6468   }
6469
6470   // Handle final rounding.
6471   return Sub;
6472 }
6473
6474 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6475                                            SelectionDAG &DAG) const {
6476   SDValue N0 = Op.getOperand(0);
6477   DebugLoc dl = Op.getDebugLoc();
6478
6479   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6480   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6481   // the optimization here.
6482   if (DAG.SignBitIsZero(N0))
6483     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6484
6485   EVT SrcVT = N0.getValueType();
6486   EVT DstVT = Op.getValueType();
6487   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6488     return LowerUINT_TO_FP_i64(Op, DAG);
6489   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6490     return LowerUINT_TO_FP_i32(Op, DAG);
6491
6492   // Make a 64-bit buffer, and use it to build an FILD.
6493   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6494   if (SrcVT == MVT::i32) {
6495     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6496     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6497                                      getPointerTy(), StackSlot, WordOff);
6498     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6499                                   StackSlot, MachinePointerInfo(),
6500                                   false, false, 0);
6501     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6502                                   OffsetSlot, MachinePointerInfo(),
6503                                   false, false, 0);
6504     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6505     return Fild;
6506   }
6507
6508   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6509   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6510                                 StackSlot, MachinePointerInfo(),
6511                                false, false, 0);
6512   // For i64 source, we need to add the appropriate power of 2 if the input
6513   // was negative.  This is the same as the optimization in
6514   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6515   // we must be careful to do the computation in x87 extended precision, not
6516   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6517   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6518   MachineMemOperand *MMO =
6519     DAG.getMachineFunction()
6520     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6521                           MachineMemOperand::MOLoad, 8, 8);
6522
6523   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6524   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6525   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6526                                          MVT::i64, MMO);
6527
6528   APInt FF(32, 0x5F800000ULL);
6529
6530   // Check whether the sign bit is set.
6531   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6532                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6533                                  ISD::SETLT);
6534
6535   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6536   SDValue FudgePtr = DAG.getConstantPool(
6537                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6538                                          getPointerTy());
6539
6540   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6541   SDValue Zero = DAG.getIntPtrConstant(0);
6542   SDValue Four = DAG.getIntPtrConstant(4);
6543   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6544                                Zero, Four);
6545   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6546
6547   // Load the value out, extending it from f32 to f80.
6548   // FIXME: Avoid the extend by constructing the right constant pool?
6549   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6550                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6551                                  MVT::f32, false, false, 4);
6552   // Extend everything to 80 bits to force it to be done on x87.
6553   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6554   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6555 }
6556
6557 std::pair<SDValue,SDValue> X86TargetLowering::
6558 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6559   DebugLoc DL = Op.getDebugLoc();
6560
6561   EVT DstTy = Op.getValueType();
6562
6563   if (!IsSigned) {
6564     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6565     DstTy = MVT::i64;
6566   }
6567
6568   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6569          DstTy.getSimpleVT() >= MVT::i16 &&
6570          "Unknown FP_TO_SINT to lower!");
6571
6572   // These are really Legal.
6573   if (DstTy == MVT::i32 &&
6574       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6575     return std::make_pair(SDValue(), SDValue());
6576   if (Subtarget->is64Bit() &&
6577       DstTy == MVT::i64 &&
6578       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6579     return std::make_pair(SDValue(), SDValue());
6580
6581   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6582   // stack slot.
6583   MachineFunction &MF = DAG.getMachineFunction();
6584   unsigned MemSize = DstTy.getSizeInBits()/8;
6585   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6586   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6587
6588
6589
6590   unsigned Opc;
6591   switch (DstTy.getSimpleVT().SimpleTy) {
6592   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6593   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6594   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6595   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6596   }
6597
6598   SDValue Chain = DAG.getEntryNode();
6599   SDValue Value = Op.getOperand(0);
6600   EVT TheVT = Op.getOperand(0).getValueType();
6601   if (isScalarFPTypeInSSEReg(TheVT)) {
6602     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6603     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6604                          MachinePointerInfo::getFixedStack(SSFI),
6605                          false, false, 0);
6606     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6607     SDValue Ops[] = {
6608       Chain, StackSlot, DAG.getValueType(TheVT)
6609     };
6610
6611     MachineMemOperand *MMO =
6612       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6613                               MachineMemOperand::MOLoad, MemSize, MemSize);
6614     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6615                                     DstTy, MMO);
6616     Chain = Value.getValue(1);
6617     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6618     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6619   }
6620
6621   MachineMemOperand *MMO =
6622     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6623                             MachineMemOperand::MOStore, MemSize, MemSize);
6624
6625   // Build the FP_TO_INT*_IN_MEM
6626   SDValue Ops[] = { Chain, Value, StackSlot };
6627   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6628                                          Ops, 3, DstTy, MMO);
6629
6630   return std::make_pair(FIST, StackSlot);
6631 }
6632
6633 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6634                                            SelectionDAG &DAG) const {
6635   if (Op.getValueType().isVector())
6636     return SDValue();
6637
6638   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6639   SDValue FIST = Vals.first, StackSlot = Vals.second;
6640   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6641   if (FIST.getNode() == 0) return Op;
6642
6643   // Load the result.
6644   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6645                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6646 }
6647
6648 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6649                                            SelectionDAG &DAG) const {
6650   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6651   SDValue FIST = Vals.first, StackSlot = Vals.second;
6652   assert(FIST.getNode() && "Unexpected failure");
6653
6654   // Load the result.
6655   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6656                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6657 }
6658
6659 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6660                                      SelectionDAG &DAG) const {
6661   LLVMContext *Context = DAG.getContext();
6662   DebugLoc dl = Op.getDebugLoc();
6663   EVT VT = Op.getValueType();
6664   EVT EltVT = VT;
6665   if (VT.isVector())
6666     EltVT = VT.getVectorElementType();
6667   std::vector<Constant*> CV;
6668   if (EltVT == MVT::f64) {
6669     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6670     CV.push_back(C);
6671     CV.push_back(C);
6672   } else {
6673     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6674     CV.push_back(C);
6675     CV.push_back(C);
6676     CV.push_back(C);
6677     CV.push_back(C);
6678   }
6679   Constant *C = ConstantVector::get(CV);
6680   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6681   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6682                              MachinePointerInfo::getConstantPool(),
6683                              false, false, 16);
6684   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6685 }
6686
6687 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6688   LLVMContext *Context = DAG.getContext();
6689   DebugLoc dl = Op.getDebugLoc();
6690   EVT VT = Op.getValueType();
6691   EVT EltVT = VT;
6692   if (VT.isVector())
6693     EltVT = VT.getVectorElementType();
6694   std::vector<Constant*> CV;
6695   if (EltVT == MVT::f64) {
6696     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6697     CV.push_back(C);
6698     CV.push_back(C);
6699   } else {
6700     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6701     CV.push_back(C);
6702     CV.push_back(C);
6703     CV.push_back(C);
6704     CV.push_back(C);
6705   }
6706   Constant *C = ConstantVector::get(CV);
6707   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6708   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6709                              MachinePointerInfo::getConstantPool(),
6710                              false, false, 16);
6711   if (VT.isVector()) {
6712     return DAG.getNode(ISD::BITCAST, dl, VT,
6713                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6714                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6715                                 Op.getOperand(0)),
6716                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6717   } else {
6718     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6719   }
6720 }
6721
6722 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6723   LLVMContext *Context = DAG.getContext();
6724   SDValue Op0 = Op.getOperand(0);
6725   SDValue Op1 = Op.getOperand(1);
6726   DebugLoc dl = Op.getDebugLoc();
6727   EVT VT = Op.getValueType();
6728   EVT SrcVT = Op1.getValueType();
6729
6730   // If second operand is smaller, extend it first.
6731   if (SrcVT.bitsLT(VT)) {
6732     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6733     SrcVT = VT;
6734   }
6735   // And if it is bigger, shrink it first.
6736   if (SrcVT.bitsGT(VT)) {
6737     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6738     SrcVT = VT;
6739   }
6740
6741   // At this point the operands and the result should have the same
6742   // type, and that won't be f80 since that is not custom lowered.
6743
6744   // First get the sign bit of second operand.
6745   std::vector<Constant*> CV;
6746   if (SrcVT == MVT::f64) {
6747     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6748     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6749   } else {
6750     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6751     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6752     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6753     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6754   }
6755   Constant *C = ConstantVector::get(CV);
6756   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6757   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6758                               MachinePointerInfo::getConstantPool(),
6759                               false, false, 16);
6760   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6761
6762   // Shift sign bit right or left if the two operands have different types.
6763   if (SrcVT.bitsGT(VT)) {
6764     // Op0 is MVT::f32, Op1 is MVT::f64.
6765     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6766     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6767                           DAG.getConstant(32, MVT::i32));
6768     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6769     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6770                           DAG.getIntPtrConstant(0));
6771   }
6772
6773   // Clear first operand sign bit.
6774   CV.clear();
6775   if (VT == MVT::f64) {
6776     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6777     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6778   } else {
6779     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6780     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6781     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6782     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6783   }
6784   C = ConstantVector::get(CV);
6785   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6786   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6787                               MachinePointerInfo::getConstantPool(),
6788                               false, false, 16);
6789   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6790
6791   // Or the value with the sign bit.
6792   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6793 }
6794
6795 /// Emit nodes that will be selected as "test Op0,Op0", or something
6796 /// equivalent.
6797 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6798                                     SelectionDAG &DAG) const {
6799   DebugLoc dl = Op.getDebugLoc();
6800
6801   // CF and OF aren't always set the way we want. Determine which
6802   // of these we need.
6803   bool NeedCF = false;
6804   bool NeedOF = false;
6805   switch (X86CC) {
6806   default: break;
6807   case X86::COND_A: case X86::COND_AE:
6808   case X86::COND_B: case X86::COND_BE:
6809     NeedCF = true;
6810     break;
6811   case X86::COND_G: case X86::COND_GE:
6812   case X86::COND_L: case X86::COND_LE:
6813   case X86::COND_O: case X86::COND_NO:
6814     NeedOF = true;
6815     break;
6816   }
6817
6818   // See if we can use the EFLAGS value from the operand instead of
6819   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6820   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6821   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6822     // Emit a CMP with 0, which is the TEST pattern.
6823     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6824                        DAG.getConstant(0, Op.getValueType()));
6825
6826   unsigned Opcode = 0;
6827   unsigned NumOperands = 0;
6828   switch (Op.getNode()->getOpcode()) {
6829   case ISD::ADD:
6830     // Due to an isel shortcoming, be conservative if this add is likely to be
6831     // selected as part of a load-modify-store instruction. When the root node
6832     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6833     // uses of other nodes in the match, such as the ADD in this case. This
6834     // leads to the ADD being left around and reselected, with the result being
6835     // two adds in the output.  Alas, even if none our users are stores, that
6836     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6837     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6838     // climbing the DAG back to the root, and it doesn't seem to be worth the
6839     // effort.
6840     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6841            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6842       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6843         goto default_case;
6844
6845     if (ConstantSDNode *C =
6846         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6847       // An add of one will be selected as an INC.
6848       if (C->getAPIntValue() == 1) {
6849         Opcode = X86ISD::INC;
6850         NumOperands = 1;
6851         break;
6852       }
6853
6854       // An add of negative one (subtract of one) will be selected as a DEC.
6855       if (C->getAPIntValue().isAllOnesValue()) {
6856         Opcode = X86ISD::DEC;
6857         NumOperands = 1;
6858         break;
6859       }
6860     }
6861
6862     // Otherwise use a regular EFLAGS-setting add.
6863     Opcode = X86ISD::ADD;
6864     NumOperands = 2;
6865     break;
6866   case ISD::AND: {
6867     // If the primary and result isn't used, don't bother using X86ISD::AND,
6868     // because a TEST instruction will be better.
6869     bool NonFlagUse = false;
6870     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6871            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6872       SDNode *User = *UI;
6873       unsigned UOpNo = UI.getOperandNo();
6874       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6875         // Look pass truncate.
6876         UOpNo = User->use_begin().getOperandNo();
6877         User = *User->use_begin();
6878       }
6879
6880       if (User->getOpcode() != ISD::BRCOND &&
6881           User->getOpcode() != ISD::SETCC &&
6882           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6883         NonFlagUse = true;
6884         break;
6885       }
6886     }
6887
6888     if (!NonFlagUse)
6889       break;
6890   }
6891     // FALL THROUGH
6892   case ISD::SUB:
6893   case ISD::OR:
6894   case ISD::XOR:
6895     // Due to the ISEL shortcoming noted above, be conservative if this op is
6896     // likely to be selected as part of a load-modify-store instruction.
6897     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6898            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6899       if (UI->getOpcode() == ISD::STORE)
6900         goto default_case;
6901
6902     // Otherwise use a regular EFLAGS-setting instruction.
6903     switch (Op.getNode()->getOpcode()) {
6904     default: llvm_unreachable("unexpected operator!");
6905     case ISD::SUB: Opcode = X86ISD::SUB; break;
6906     case ISD::OR:  Opcode = X86ISD::OR;  break;
6907     case ISD::XOR: Opcode = X86ISD::XOR; break;
6908     case ISD::AND: Opcode = X86ISD::AND; break;
6909     }
6910
6911     NumOperands = 2;
6912     break;
6913   case X86ISD::ADD:
6914   case X86ISD::SUB:
6915   case X86ISD::INC:
6916   case X86ISD::DEC:
6917   case X86ISD::OR:
6918   case X86ISD::XOR:
6919   case X86ISD::AND:
6920     return SDValue(Op.getNode(), 1);
6921   default:
6922   default_case:
6923     break;
6924   }
6925
6926   if (Opcode == 0)
6927     // Emit a CMP with 0, which is the TEST pattern.
6928     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6929                        DAG.getConstant(0, Op.getValueType()));
6930
6931   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6932   SmallVector<SDValue, 4> Ops;
6933   for (unsigned i = 0; i != NumOperands; ++i)
6934     Ops.push_back(Op.getOperand(i));
6935
6936   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6937   DAG.ReplaceAllUsesWith(Op, New);
6938   return SDValue(New.getNode(), 1);
6939 }
6940
6941 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6942 /// equivalent.
6943 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6944                                    SelectionDAG &DAG) const {
6945   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6946     if (C->getAPIntValue() == 0)
6947       return EmitTest(Op0, X86CC, DAG);
6948
6949   DebugLoc dl = Op0.getDebugLoc();
6950   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6951 }
6952
6953 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6954 /// if it's possible.
6955 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6956                                      DebugLoc dl, SelectionDAG &DAG) const {
6957   SDValue Op0 = And.getOperand(0);
6958   SDValue Op1 = And.getOperand(1);
6959   if (Op0.getOpcode() == ISD::TRUNCATE)
6960     Op0 = Op0.getOperand(0);
6961   if (Op1.getOpcode() == ISD::TRUNCATE)
6962     Op1 = Op1.getOperand(0);
6963
6964   SDValue LHS, RHS;
6965   if (Op1.getOpcode() == ISD::SHL)
6966     std::swap(Op0, Op1);
6967   if (Op0.getOpcode() == ISD::SHL) {
6968     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6969       if (And00C->getZExtValue() == 1) {
6970         // If we looked past a truncate, check that it's only truncating away
6971         // known zeros.
6972         unsigned BitWidth = Op0.getValueSizeInBits();
6973         unsigned AndBitWidth = And.getValueSizeInBits();
6974         if (BitWidth > AndBitWidth) {
6975           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6976           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6977           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6978             return SDValue();
6979         }
6980         LHS = Op1;
6981         RHS = Op0.getOperand(1);
6982       }
6983   } else if (Op1.getOpcode() == ISD::Constant) {
6984     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6985     SDValue AndLHS = Op0;
6986     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6987       LHS = AndLHS.getOperand(0);
6988       RHS = AndLHS.getOperand(1);
6989     }
6990   }
6991
6992   if (LHS.getNode()) {
6993     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6994     // instruction.  Since the shift amount is in-range-or-undefined, we know
6995     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6996     // the encoding for the i16 version is larger than the i32 version.
6997     // Also promote i16 to i32 for performance / code size reason.
6998     if (LHS.getValueType() == MVT::i8 ||
6999         LHS.getValueType() == MVT::i16)
7000       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7001
7002     // If the operand types disagree, extend the shift amount to match.  Since
7003     // BT ignores high bits (like shifts) we can use anyextend.
7004     if (LHS.getValueType() != RHS.getValueType())
7005       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7006
7007     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7008     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7009     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7010                        DAG.getConstant(Cond, MVT::i8), BT);
7011   }
7012
7013   return SDValue();
7014 }
7015
7016 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7017   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7018   SDValue Op0 = Op.getOperand(0);
7019   SDValue Op1 = Op.getOperand(1);
7020   DebugLoc dl = Op.getDebugLoc();
7021   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7022
7023   // Optimize to BT if possible.
7024   // Lower (X & (1 << N)) == 0 to BT(X, N).
7025   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7026   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7027   if (Op0.getOpcode() == ISD::AND &&
7028       Op0.hasOneUse() &&
7029       Op1.getOpcode() == ISD::Constant &&
7030       cast<ConstantSDNode>(Op1)->isNullValue() &&
7031       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7032     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7033     if (NewSetCC.getNode())
7034       return NewSetCC;
7035   }
7036
7037   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7038   if (Op0.getOpcode() == X86ISD::SETCC &&
7039       Op1.getOpcode() == ISD::Constant &&
7040       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7041        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7042       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7043     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7044     bool Invert = (CC == ISD::SETNE) ^
7045       cast<ConstantSDNode>(Op1)->isNullValue();
7046     if (Invert)
7047       CCode = X86::GetOppositeBranchCondition(CCode);
7048     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7049                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7050   }
7051
7052   bool isFP = Op1.getValueType().isFloatingPoint();
7053   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7054   if (X86CC == X86::COND_INVALID)
7055     return SDValue();
7056
7057   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7058
7059   // Use sbb x, x to materialize carry bit into a GPR.
7060   if (X86CC == X86::COND_B)
7061     return DAG.getNode(ISD::AND, dl, MVT::i8,
7062                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7063                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7064                        DAG.getConstant(1, MVT::i8));
7065
7066   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7067                      DAG.getConstant(X86CC, MVT::i8), Cond);
7068 }
7069
7070 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7071   SDValue Cond;
7072   SDValue Op0 = Op.getOperand(0);
7073   SDValue Op1 = Op.getOperand(1);
7074   SDValue CC = Op.getOperand(2);
7075   EVT VT = Op.getValueType();
7076   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7077   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7078   DebugLoc dl = Op.getDebugLoc();
7079
7080   if (isFP) {
7081     unsigned SSECC = 8;
7082     EVT VT0 = Op0.getValueType();
7083     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7084     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7085     bool Swap = false;
7086
7087     switch (SetCCOpcode) {
7088     default: break;
7089     case ISD::SETOEQ:
7090     case ISD::SETEQ:  SSECC = 0; break;
7091     case ISD::SETOGT:
7092     case ISD::SETGT: Swap = true; // Fallthrough
7093     case ISD::SETLT:
7094     case ISD::SETOLT: SSECC = 1; break;
7095     case ISD::SETOGE:
7096     case ISD::SETGE: Swap = true; // Fallthrough
7097     case ISD::SETLE:
7098     case ISD::SETOLE: SSECC = 2; break;
7099     case ISD::SETUO:  SSECC = 3; break;
7100     case ISD::SETUNE:
7101     case ISD::SETNE:  SSECC = 4; break;
7102     case ISD::SETULE: Swap = true;
7103     case ISD::SETUGE: SSECC = 5; break;
7104     case ISD::SETULT: Swap = true;
7105     case ISD::SETUGT: SSECC = 6; break;
7106     case ISD::SETO:   SSECC = 7; break;
7107     }
7108     if (Swap)
7109       std::swap(Op0, Op1);
7110
7111     // In the two special cases we can't handle, emit two comparisons.
7112     if (SSECC == 8) {
7113       if (SetCCOpcode == ISD::SETUEQ) {
7114         SDValue UNORD, EQ;
7115         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7116         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7117         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7118       }
7119       else if (SetCCOpcode == ISD::SETONE) {
7120         SDValue ORD, NEQ;
7121         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7122         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7123         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7124       }
7125       llvm_unreachable("Illegal FP comparison");
7126     }
7127     // Handle all other FP comparisons here.
7128     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7129   }
7130
7131   // We are handling one of the integer comparisons here.  Since SSE only has
7132   // GT and EQ comparisons for integer, swapping operands and multiple
7133   // operations may be required for some comparisons.
7134   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7135   bool Swap = false, Invert = false, FlipSigns = false;
7136
7137   switch (VT.getSimpleVT().SimpleTy) {
7138   default: break;
7139   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7140   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7141   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7142   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7143   }
7144
7145   switch (SetCCOpcode) {
7146   default: break;
7147   case ISD::SETNE:  Invert = true;
7148   case ISD::SETEQ:  Opc = EQOpc; break;
7149   case ISD::SETLT:  Swap = true;
7150   case ISD::SETGT:  Opc = GTOpc; break;
7151   case ISD::SETGE:  Swap = true;
7152   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7153   case ISD::SETULT: Swap = true;
7154   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7155   case ISD::SETUGE: Swap = true;
7156   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7157   }
7158   if (Swap)
7159     std::swap(Op0, Op1);
7160
7161   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7162   // bits of the inputs before performing those operations.
7163   if (FlipSigns) {
7164     EVT EltVT = VT.getVectorElementType();
7165     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7166                                       EltVT);
7167     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7168     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7169                                     SignBits.size());
7170     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7171     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7172   }
7173
7174   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7175
7176   // If the logical-not of the result is required, perform that now.
7177   if (Invert)
7178     Result = DAG.getNOT(dl, Result, VT);
7179
7180   return Result;
7181 }
7182
7183 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7184 static bool isX86LogicalCmp(SDValue Op) {
7185   unsigned Opc = Op.getNode()->getOpcode();
7186   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7187     return true;
7188   if (Op.getResNo() == 1 &&
7189       (Opc == X86ISD::ADD ||
7190        Opc == X86ISD::SUB ||
7191        Opc == X86ISD::SMUL ||
7192        Opc == X86ISD::UMUL ||
7193        Opc == X86ISD::INC ||
7194        Opc == X86ISD::DEC ||
7195        Opc == X86ISD::OR ||
7196        Opc == X86ISD::XOR ||
7197        Opc == X86ISD::AND))
7198     return true;
7199
7200   return false;
7201 }
7202
7203 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7204   bool addTest = true;
7205   SDValue Cond  = Op.getOperand(0);
7206   DebugLoc dl = Op.getDebugLoc();
7207   SDValue CC;
7208
7209   if (Cond.getOpcode() == ISD::SETCC) {
7210     SDValue NewCond = LowerSETCC(Cond, DAG);
7211     if (NewCond.getNode())
7212       Cond = NewCond;
7213   }
7214
7215   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7216   SDValue Op1 = Op.getOperand(1);
7217   SDValue Op2 = Op.getOperand(2);
7218   if (Cond.getOpcode() == X86ISD::SETCC &&
7219       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7220     SDValue Cmp = Cond.getOperand(1);
7221     if (Cmp.getOpcode() == X86ISD::CMP) {
7222       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7223       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7224       ConstantSDNode *RHSC =
7225         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7226       if (N1C && N1C->isAllOnesValue() &&
7227           N2C && N2C->isNullValue() &&
7228           RHSC && RHSC->isNullValue()) {
7229         SDValue CmpOp0 = Cmp.getOperand(0);
7230         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7231                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7232         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7233                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7234       }
7235     }
7236   }
7237
7238   // Look pass (and (setcc_carry (cmp ...)), 1).
7239   if (Cond.getOpcode() == ISD::AND &&
7240       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7241     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7242     if (C && C->getAPIntValue() == 1)
7243       Cond = Cond.getOperand(0);
7244   }
7245
7246   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7247   // setting operand in place of the X86ISD::SETCC.
7248   if (Cond.getOpcode() == X86ISD::SETCC ||
7249       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7250     CC = Cond.getOperand(0);
7251
7252     SDValue Cmp = Cond.getOperand(1);
7253     unsigned Opc = Cmp.getOpcode();
7254     EVT VT = Op.getValueType();
7255
7256     bool IllegalFPCMov = false;
7257     if (VT.isFloatingPoint() && !VT.isVector() &&
7258         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7259       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7260
7261     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7262         Opc == X86ISD::BT) { // FIXME
7263       Cond = Cmp;
7264       addTest = false;
7265     }
7266   }
7267
7268   if (addTest) {
7269     // Look pass the truncate.
7270     if (Cond.getOpcode() == ISD::TRUNCATE)
7271       Cond = Cond.getOperand(0);
7272
7273     // We know the result of AND is compared against zero. Try to match
7274     // it to BT.
7275     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7276       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7277       if (NewSetCC.getNode()) {
7278         CC = NewSetCC.getOperand(0);
7279         Cond = NewSetCC.getOperand(1);
7280         addTest = false;
7281       }
7282     }
7283   }
7284
7285   if (addTest) {
7286     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7287     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7288   }
7289
7290   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7291   // condition is true.
7292   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7293   SDValue Ops[] = { Op2, Op1, CC, Cond };
7294   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7295 }
7296
7297 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7298 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7299 // from the AND / OR.
7300 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7301   Opc = Op.getOpcode();
7302   if (Opc != ISD::OR && Opc != ISD::AND)
7303     return false;
7304   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7305           Op.getOperand(0).hasOneUse() &&
7306           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7307           Op.getOperand(1).hasOneUse());
7308 }
7309
7310 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7311 // 1 and that the SETCC node has a single use.
7312 static bool isXor1OfSetCC(SDValue Op) {
7313   if (Op.getOpcode() != ISD::XOR)
7314     return false;
7315   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7316   if (N1C && N1C->getAPIntValue() == 1) {
7317     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7318       Op.getOperand(0).hasOneUse();
7319   }
7320   return false;
7321 }
7322
7323 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7324   bool addTest = true;
7325   SDValue Chain = Op.getOperand(0);
7326   SDValue Cond  = Op.getOperand(1);
7327   SDValue Dest  = Op.getOperand(2);
7328   DebugLoc dl = Op.getDebugLoc();
7329   SDValue CC;
7330
7331   if (Cond.getOpcode() == ISD::SETCC) {
7332     SDValue NewCond = LowerSETCC(Cond, DAG);
7333     if (NewCond.getNode())
7334       Cond = NewCond;
7335   }
7336 #if 0
7337   // FIXME: LowerXALUO doesn't handle these!!
7338   else if (Cond.getOpcode() == X86ISD::ADD  ||
7339            Cond.getOpcode() == X86ISD::SUB  ||
7340            Cond.getOpcode() == X86ISD::SMUL ||
7341            Cond.getOpcode() == X86ISD::UMUL)
7342     Cond = LowerXALUO(Cond, DAG);
7343 #endif
7344
7345   // Look pass (and (setcc_carry (cmp ...)), 1).
7346   if (Cond.getOpcode() == ISD::AND &&
7347       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7348     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7349     if (C && C->getAPIntValue() == 1)
7350       Cond = Cond.getOperand(0);
7351   }
7352
7353   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7354   // setting operand in place of the X86ISD::SETCC.
7355   if (Cond.getOpcode() == X86ISD::SETCC ||
7356       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7357     CC = Cond.getOperand(0);
7358
7359     SDValue Cmp = Cond.getOperand(1);
7360     unsigned Opc = Cmp.getOpcode();
7361     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7362     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7363       Cond = Cmp;
7364       addTest = false;
7365     } else {
7366       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7367       default: break;
7368       case X86::COND_O:
7369       case X86::COND_B:
7370         // These can only come from an arithmetic instruction with overflow,
7371         // e.g. SADDO, UADDO.
7372         Cond = Cond.getNode()->getOperand(1);
7373         addTest = false;
7374         break;
7375       }
7376     }
7377   } else {
7378     unsigned CondOpc;
7379     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7380       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7381       if (CondOpc == ISD::OR) {
7382         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7383         // two branches instead of an explicit OR instruction with a
7384         // separate test.
7385         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7386             isX86LogicalCmp(Cmp)) {
7387           CC = Cond.getOperand(0).getOperand(0);
7388           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7389                               Chain, Dest, CC, Cmp);
7390           CC = Cond.getOperand(1).getOperand(0);
7391           Cond = Cmp;
7392           addTest = false;
7393         }
7394       } else { // ISD::AND
7395         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7396         // two branches instead of an explicit AND instruction with a
7397         // separate test. However, we only do this if this block doesn't
7398         // have a fall-through edge, because this requires an explicit
7399         // jmp when the condition is false.
7400         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7401             isX86LogicalCmp(Cmp) &&
7402             Op.getNode()->hasOneUse()) {
7403           X86::CondCode CCode =
7404             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7405           CCode = X86::GetOppositeBranchCondition(CCode);
7406           CC = DAG.getConstant(CCode, MVT::i8);
7407           SDNode *User = *Op.getNode()->use_begin();
7408           // Look for an unconditional branch following this conditional branch.
7409           // We need this because we need to reverse the successors in order
7410           // to implement FCMP_OEQ.
7411           if (User->getOpcode() == ISD::BR) {
7412             SDValue FalseBB = User->getOperand(1);
7413             SDNode *NewBR =
7414               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7415             assert(NewBR == User);
7416             (void)NewBR;
7417             Dest = FalseBB;
7418
7419             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7420                                 Chain, Dest, CC, Cmp);
7421             X86::CondCode CCode =
7422               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7423             CCode = X86::GetOppositeBranchCondition(CCode);
7424             CC = DAG.getConstant(CCode, MVT::i8);
7425             Cond = Cmp;
7426             addTest = false;
7427           }
7428         }
7429       }
7430     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7431       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7432       // It should be transformed during dag combiner except when the condition
7433       // is set by a arithmetics with overflow node.
7434       X86::CondCode CCode =
7435         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7436       CCode = X86::GetOppositeBranchCondition(CCode);
7437       CC = DAG.getConstant(CCode, MVT::i8);
7438       Cond = Cond.getOperand(0).getOperand(1);
7439       addTest = false;
7440     }
7441   }
7442
7443   if (addTest) {
7444     // Look pass the truncate.
7445     if (Cond.getOpcode() == ISD::TRUNCATE)
7446       Cond = Cond.getOperand(0);
7447
7448     // We know the result of AND is compared against zero. Try to match
7449     // it to BT.
7450     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7451       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7452       if (NewSetCC.getNode()) {
7453         CC = NewSetCC.getOperand(0);
7454         Cond = NewSetCC.getOperand(1);
7455         addTest = false;
7456       }
7457     }
7458   }
7459
7460   if (addTest) {
7461     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7462     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7463   }
7464   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7465                      Chain, Dest, CC, Cond);
7466 }
7467
7468
7469 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7470 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7471 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7472 // that the guard pages used by the OS virtual memory manager are allocated in
7473 // correct sequence.
7474 SDValue
7475 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7476                                            SelectionDAG &DAG) const {
7477   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7478          "This should be used only on Windows targets");
7479   DebugLoc dl = Op.getDebugLoc();
7480
7481   // Get the inputs.
7482   SDValue Chain = Op.getOperand(0);
7483   SDValue Size  = Op.getOperand(1);
7484   // FIXME: Ensure alignment here
7485
7486   SDValue Flag;
7487
7488   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7489
7490   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7491   Flag = Chain.getValue(1);
7492
7493   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7494
7495   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7496   Flag = Chain.getValue(1);
7497
7498   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7499
7500   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7501   return DAG.getMergeValues(Ops1, 2, dl);
7502 }
7503
7504 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7505   MachineFunction &MF = DAG.getMachineFunction();
7506   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7507
7508   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7509   DebugLoc DL = Op.getDebugLoc();
7510
7511   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7512     // vastart just stores the address of the VarArgsFrameIndex slot into the
7513     // memory location argument.
7514     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7515                                    getPointerTy());
7516     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7517                         MachinePointerInfo(SV), false, false, 0);
7518   }
7519
7520   // __va_list_tag:
7521   //   gp_offset         (0 - 6 * 8)
7522   //   fp_offset         (48 - 48 + 8 * 16)
7523   //   overflow_arg_area (point to parameters coming in memory).
7524   //   reg_save_area
7525   SmallVector<SDValue, 8> MemOps;
7526   SDValue FIN = Op.getOperand(1);
7527   // Store gp_offset
7528   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7529                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7530                                                MVT::i32),
7531                                FIN, MachinePointerInfo(SV), false, false, 0);
7532   MemOps.push_back(Store);
7533
7534   // Store fp_offset
7535   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7536                     FIN, DAG.getIntPtrConstant(4));
7537   Store = DAG.getStore(Op.getOperand(0), DL,
7538                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7539                                        MVT::i32),
7540                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7541   MemOps.push_back(Store);
7542
7543   // Store ptr to overflow_arg_area
7544   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7545                     FIN, DAG.getIntPtrConstant(4));
7546   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7547                                     getPointerTy());
7548   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7549                        MachinePointerInfo(SV, 8),
7550                        false, false, 0);
7551   MemOps.push_back(Store);
7552
7553   // Store ptr to reg_save_area.
7554   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7555                     FIN, DAG.getIntPtrConstant(8));
7556   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7557                                     getPointerTy());
7558   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7559                        MachinePointerInfo(SV, 16), false, false, 0);
7560   MemOps.push_back(Store);
7561   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7562                      &MemOps[0], MemOps.size());
7563 }
7564
7565 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7566   assert(Subtarget->is64Bit() &&
7567          "LowerVAARG only handles 64-bit va_arg!");
7568   assert((Subtarget->isTargetLinux() ||
7569           Subtarget->isTargetDarwin()) &&
7570           "Unhandled target in LowerVAARG");
7571   assert(Op.getNode()->getNumOperands() == 4);
7572   SDValue Chain = Op.getOperand(0);
7573   SDValue SrcPtr = Op.getOperand(1);
7574   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7575   unsigned Align = Op.getConstantOperandVal(3);
7576   DebugLoc dl = Op.getDebugLoc();
7577
7578   EVT ArgVT = Op.getNode()->getValueType(0);
7579   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7580   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7581   uint8_t ArgMode;
7582
7583   // Decide which area this value should be read from.
7584   // TODO: Implement the AMD64 ABI in its entirety. This simple
7585   // selection mechanism works only for the basic types.
7586   if (ArgVT == MVT::f80) {
7587     llvm_unreachable("va_arg for f80 not yet implemented");
7588   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7589     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7590   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7591     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7592   } else {
7593     llvm_unreachable("Unhandled argument type in LowerVAARG");
7594   }
7595
7596   if (ArgMode == 2) {
7597     // Sanity Check: Make sure using fp_offset makes sense.
7598     assert(!UseSoftFloat &&
7599            !(DAG.getMachineFunction()
7600                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7601            Subtarget->hasSSE1());
7602   }
7603
7604   // Insert VAARG_64 node into the DAG
7605   // VAARG_64 returns two values: Variable Argument Address, Chain
7606   SmallVector<SDValue, 11> InstOps;
7607   InstOps.push_back(Chain);
7608   InstOps.push_back(SrcPtr);
7609   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7610   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7611   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7612   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7613   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7614                                           VTs, &InstOps[0], InstOps.size(),
7615                                           MVT::i64,
7616                                           MachinePointerInfo(SV),
7617                                           /*Align=*/0,
7618                                           /*Volatile=*/false,
7619                                           /*ReadMem=*/true,
7620                                           /*WriteMem=*/true);
7621   Chain = VAARG.getValue(1);
7622
7623   // Load the next argument and return it
7624   return DAG.getLoad(ArgVT, dl,
7625                      Chain,
7626                      VAARG,
7627                      MachinePointerInfo(),
7628                      false, false, 0);
7629 }
7630
7631 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7632   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7633   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7634   SDValue Chain = Op.getOperand(0);
7635   SDValue DstPtr = Op.getOperand(1);
7636   SDValue SrcPtr = Op.getOperand(2);
7637   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7638   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7639   DebugLoc DL = Op.getDebugLoc();
7640
7641   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7642                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7643                        false,
7644                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7645 }
7646
7647 SDValue
7648 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7649   DebugLoc dl = Op.getDebugLoc();
7650   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7651   switch (IntNo) {
7652   default: return SDValue();    // Don't custom lower most intrinsics.
7653   // Comparison intrinsics.
7654   case Intrinsic::x86_sse_comieq_ss:
7655   case Intrinsic::x86_sse_comilt_ss:
7656   case Intrinsic::x86_sse_comile_ss:
7657   case Intrinsic::x86_sse_comigt_ss:
7658   case Intrinsic::x86_sse_comige_ss:
7659   case Intrinsic::x86_sse_comineq_ss:
7660   case Intrinsic::x86_sse_ucomieq_ss:
7661   case Intrinsic::x86_sse_ucomilt_ss:
7662   case Intrinsic::x86_sse_ucomile_ss:
7663   case Intrinsic::x86_sse_ucomigt_ss:
7664   case Intrinsic::x86_sse_ucomige_ss:
7665   case Intrinsic::x86_sse_ucomineq_ss:
7666   case Intrinsic::x86_sse2_comieq_sd:
7667   case Intrinsic::x86_sse2_comilt_sd:
7668   case Intrinsic::x86_sse2_comile_sd:
7669   case Intrinsic::x86_sse2_comigt_sd:
7670   case Intrinsic::x86_sse2_comige_sd:
7671   case Intrinsic::x86_sse2_comineq_sd:
7672   case Intrinsic::x86_sse2_ucomieq_sd:
7673   case Intrinsic::x86_sse2_ucomilt_sd:
7674   case Intrinsic::x86_sse2_ucomile_sd:
7675   case Intrinsic::x86_sse2_ucomigt_sd:
7676   case Intrinsic::x86_sse2_ucomige_sd:
7677   case Intrinsic::x86_sse2_ucomineq_sd: {
7678     unsigned Opc = 0;
7679     ISD::CondCode CC = ISD::SETCC_INVALID;
7680     switch (IntNo) {
7681     default: break;
7682     case Intrinsic::x86_sse_comieq_ss:
7683     case Intrinsic::x86_sse2_comieq_sd:
7684       Opc = X86ISD::COMI;
7685       CC = ISD::SETEQ;
7686       break;
7687     case Intrinsic::x86_sse_comilt_ss:
7688     case Intrinsic::x86_sse2_comilt_sd:
7689       Opc = X86ISD::COMI;
7690       CC = ISD::SETLT;
7691       break;
7692     case Intrinsic::x86_sse_comile_ss:
7693     case Intrinsic::x86_sse2_comile_sd:
7694       Opc = X86ISD::COMI;
7695       CC = ISD::SETLE;
7696       break;
7697     case Intrinsic::x86_sse_comigt_ss:
7698     case Intrinsic::x86_sse2_comigt_sd:
7699       Opc = X86ISD::COMI;
7700       CC = ISD::SETGT;
7701       break;
7702     case Intrinsic::x86_sse_comige_ss:
7703     case Intrinsic::x86_sse2_comige_sd:
7704       Opc = X86ISD::COMI;
7705       CC = ISD::SETGE;
7706       break;
7707     case Intrinsic::x86_sse_comineq_ss:
7708     case Intrinsic::x86_sse2_comineq_sd:
7709       Opc = X86ISD::COMI;
7710       CC = ISD::SETNE;
7711       break;
7712     case Intrinsic::x86_sse_ucomieq_ss:
7713     case Intrinsic::x86_sse2_ucomieq_sd:
7714       Opc = X86ISD::UCOMI;
7715       CC = ISD::SETEQ;
7716       break;
7717     case Intrinsic::x86_sse_ucomilt_ss:
7718     case Intrinsic::x86_sse2_ucomilt_sd:
7719       Opc = X86ISD::UCOMI;
7720       CC = ISD::SETLT;
7721       break;
7722     case Intrinsic::x86_sse_ucomile_ss:
7723     case Intrinsic::x86_sse2_ucomile_sd:
7724       Opc = X86ISD::UCOMI;
7725       CC = ISD::SETLE;
7726       break;
7727     case Intrinsic::x86_sse_ucomigt_ss:
7728     case Intrinsic::x86_sse2_ucomigt_sd:
7729       Opc = X86ISD::UCOMI;
7730       CC = ISD::SETGT;
7731       break;
7732     case Intrinsic::x86_sse_ucomige_ss:
7733     case Intrinsic::x86_sse2_ucomige_sd:
7734       Opc = X86ISD::UCOMI;
7735       CC = ISD::SETGE;
7736       break;
7737     case Intrinsic::x86_sse_ucomineq_ss:
7738     case Intrinsic::x86_sse2_ucomineq_sd:
7739       Opc = X86ISD::UCOMI;
7740       CC = ISD::SETNE;
7741       break;
7742     }
7743
7744     SDValue LHS = Op.getOperand(1);
7745     SDValue RHS = Op.getOperand(2);
7746     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7747     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7748     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7749     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7750                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7751     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7752   }
7753   // ptest and testp intrinsics. The intrinsic these come from are designed to
7754   // return an integer value, not just an instruction so lower it to the ptest
7755   // or testp pattern and a setcc for the result.
7756   case Intrinsic::x86_sse41_ptestz:
7757   case Intrinsic::x86_sse41_ptestc:
7758   case Intrinsic::x86_sse41_ptestnzc:
7759   case Intrinsic::x86_avx_ptestz_256:
7760   case Intrinsic::x86_avx_ptestc_256:
7761   case Intrinsic::x86_avx_ptestnzc_256:
7762   case Intrinsic::x86_avx_vtestz_ps:
7763   case Intrinsic::x86_avx_vtestc_ps:
7764   case Intrinsic::x86_avx_vtestnzc_ps:
7765   case Intrinsic::x86_avx_vtestz_pd:
7766   case Intrinsic::x86_avx_vtestc_pd:
7767   case Intrinsic::x86_avx_vtestnzc_pd:
7768   case Intrinsic::x86_avx_vtestz_ps_256:
7769   case Intrinsic::x86_avx_vtestc_ps_256:
7770   case Intrinsic::x86_avx_vtestnzc_ps_256:
7771   case Intrinsic::x86_avx_vtestz_pd_256:
7772   case Intrinsic::x86_avx_vtestc_pd_256:
7773   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7774     bool IsTestPacked = false;
7775     unsigned X86CC = 0;
7776     switch (IntNo) {
7777     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7778     case Intrinsic::x86_avx_vtestz_ps:
7779     case Intrinsic::x86_avx_vtestz_pd:
7780     case Intrinsic::x86_avx_vtestz_ps_256:
7781     case Intrinsic::x86_avx_vtestz_pd_256:
7782       IsTestPacked = true; // Fallthrough
7783     case Intrinsic::x86_sse41_ptestz:
7784     case Intrinsic::x86_avx_ptestz_256:
7785       // ZF = 1
7786       X86CC = X86::COND_E;
7787       break;
7788     case Intrinsic::x86_avx_vtestc_ps:
7789     case Intrinsic::x86_avx_vtestc_pd:
7790     case Intrinsic::x86_avx_vtestc_ps_256:
7791     case Intrinsic::x86_avx_vtestc_pd_256:
7792       IsTestPacked = true; // Fallthrough
7793     case Intrinsic::x86_sse41_ptestc:
7794     case Intrinsic::x86_avx_ptestc_256:
7795       // CF = 1
7796       X86CC = X86::COND_B;
7797       break;
7798     case Intrinsic::x86_avx_vtestnzc_ps:
7799     case Intrinsic::x86_avx_vtestnzc_pd:
7800     case Intrinsic::x86_avx_vtestnzc_ps_256:
7801     case Intrinsic::x86_avx_vtestnzc_pd_256:
7802       IsTestPacked = true; // Fallthrough
7803     case Intrinsic::x86_sse41_ptestnzc:
7804     case Intrinsic::x86_avx_ptestnzc_256:
7805       // ZF and CF = 0
7806       X86CC = X86::COND_A;
7807       break;
7808     }
7809
7810     SDValue LHS = Op.getOperand(1);
7811     SDValue RHS = Op.getOperand(2);
7812     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7813     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7814     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7815     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7816     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7817   }
7818
7819   // Fix vector shift instructions where the last operand is a non-immediate
7820   // i32 value.
7821   case Intrinsic::x86_sse2_pslli_w:
7822   case Intrinsic::x86_sse2_pslli_d:
7823   case Intrinsic::x86_sse2_pslli_q:
7824   case Intrinsic::x86_sse2_psrli_w:
7825   case Intrinsic::x86_sse2_psrli_d:
7826   case Intrinsic::x86_sse2_psrli_q:
7827   case Intrinsic::x86_sse2_psrai_w:
7828   case Intrinsic::x86_sse2_psrai_d:
7829   case Intrinsic::x86_mmx_pslli_w:
7830   case Intrinsic::x86_mmx_pslli_d:
7831   case Intrinsic::x86_mmx_pslli_q:
7832   case Intrinsic::x86_mmx_psrli_w:
7833   case Intrinsic::x86_mmx_psrli_d:
7834   case Intrinsic::x86_mmx_psrli_q:
7835   case Intrinsic::x86_mmx_psrai_w:
7836   case Intrinsic::x86_mmx_psrai_d: {
7837     SDValue ShAmt = Op.getOperand(2);
7838     if (isa<ConstantSDNode>(ShAmt))
7839       return SDValue();
7840
7841     unsigned NewIntNo = 0;
7842     EVT ShAmtVT = MVT::v4i32;
7843     switch (IntNo) {
7844     case Intrinsic::x86_sse2_pslli_w:
7845       NewIntNo = Intrinsic::x86_sse2_psll_w;
7846       break;
7847     case Intrinsic::x86_sse2_pslli_d:
7848       NewIntNo = Intrinsic::x86_sse2_psll_d;
7849       break;
7850     case Intrinsic::x86_sse2_pslli_q:
7851       NewIntNo = Intrinsic::x86_sse2_psll_q;
7852       break;
7853     case Intrinsic::x86_sse2_psrli_w:
7854       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7855       break;
7856     case Intrinsic::x86_sse2_psrli_d:
7857       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7858       break;
7859     case Intrinsic::x86_sse2_psrli_q:
7860       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7861       break;
7862     case Intrinsic::x86_sse2_psrai_w:
7863       NewIntNo = Intrinsic::x86_sse2_psra_w;
7864       break;
7865     case Intrinsic::x86_sse2_psrai_d:
7866       NewIntNo = Intrinsic::x86_sse2_psra_d;
7867       break;
7868     default: {
7869       ShAmtVT = MVT::v2i32;
7870       switch (IntNo) {
7871       case Intrinsic::x86_mmx_pslli_w:
7872         NewIntNo = Intrinsic::x86_mmx_psll_w;
7873         break;
7874       case Intrinsic::x86_mmx_pslli_d:
7875         NewIntNo = Intrinsic::x86_mmx_psll_d;
7876         break;
7877       case Intrinsic::x86_mmx_pslli_q:
7878         NewIntNo = Intrinsic::x86_mmx_psll_q;
7879         break;
7880       case Intrinsic::x86_mmx_psrli_w:
7881         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7882         break;
7883       case Intrinsic::x86_mmx_psrli_d:
7884         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7885         break;
7886       case Intrinsic::x86_mmx_psrli_q:
7887         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7888         break;
7889       case Intrinsic::x86_mmx_psrai_w:
7890         NewIntNo = Intrinsic::x86_mmx_psra_w;
7891         break;
7892       case Intrinsic::x86_mmx_psrai_d:
7893         NewIntNo = Intrinsic::x86_mmx_psra_d;
7894         break;
7895       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7896       }
7897       break;
7898     }
7899     }
7900
7901     // The vector shift intrinsics with scalars uses 32b shift amounts but
7902     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7903     // to be zero.
7904     SDValue ShOps[4];
7905     ShOps[0] = ShAmt;
7906     ShOps[1] = DAG.getConstant(0, MVT::i32);
7907     if (ShAmtVT == MVT::v4i32) {
7908       ShOps[2] = DAG.getUNDEF(MVT::i32);
7909       ShOps[3] = DAG.getUNDEF(MVT::i32);
7910       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7911     } else {
7912       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7913 // FIXME this must be lowered to get rid of the invalid type.
7914     }
7915
7916     EVT VT = Op.getValueType();
7917     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7918     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7919                        DAG.getConstant(NewIntNo, MVT::i32),
7920                        Op.getOperand(1), ShAmt);
7921   }
7922   }
7923 }
7924
7925 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7926                                            SelectionDAG &DAG) const {
7927   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7928   MFI->setReturnAddressIsTaken(true);
7929
7930   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7931   DebugLoc dl = Op.getDebugLoc();
7932
7933   if (Depth > 0) {
7934     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7935     SDValue Offset =
7936       DAG.getConstant(TD->getPointerSize(),
7937                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7938     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7939                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7940                                    FrameAddr, Offset),
7941                        MachinePointerInfo(), false, false, 0);
7942   }
7943
7944   // Just load the return address.
7945   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7946   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7947                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7948 }
7949
7950 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7951   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7952   MFI->setFrameAddressIsTaken(true);
7953
7954   EVT VT = Op.getValueType();
7955   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7956   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7957   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7958   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7959   while (Depth--)
7960     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7961                             MachinePointerInfo(),
7962                             false, false, 0);
7963   return FrameAddr;
7964 }
7965
7966 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7967                                                      SelectionDAG &DAG) const {
7968   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7969 }
7970
7971 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7972   MachineFunction &MF = DAG.getMachineFunction();
7973   SDValue Chain     = Op.getOperand(0);
7974   SDValue Offset    = Op.getOperand(1);
7975   SDValue Handler   = Op.getOperand(2);
7976   DebugLoc dl       = Op.getDebugLoc();
7977
7978   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7979                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7980                                      getPointerTy());
7981   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7982
7983   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7984                                   DAG.getIntPtrConstant(TD->getPointerSize()));
7985   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7986   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
7987                        false, false, 0);
7988   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7989   MF.getRegInfo().addLiveOut(StoreAddrReg);
7990
7991   return DAG.getNode(X86ISD::EH_RETURN, dl,
7992                      MVT::Other,
7993                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7994 }
7995
7996 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7997                                              SelectionDAG &DAG) const {
7998   SDValue Root = Op.getOperand(0);
7999   SDValue Trmp = Op.getOperand(1); // trampoline
8000   SDValue FPtr = Op.getOperand(2); // nested function
8001   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8002   DebugLoc dl  = Op.getDebugLoc();
8003
8004   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8005
8006   if (Subtarget->is64Bit()) {
8007     SDValue OutChains[6];
8008
8009     // Large code-model.
8010     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8011     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8012
8013     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8014     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8015
8016     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8017
8018     // Load the pointer to the nested function into R11.
8019     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8020     SDValue Addr = Trmp;
8021     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8022                                 Addr, MachinePointerInfo(TrmpAddr),
8023                                 false, false, 0);
8024
8025     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8026                        DAG.getConstant(2, MVT::i64));
8027     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8028                                 MachinePointerInfo(TrmpAddr, 2),
8029                                 false, false, 2);
8030
8031     // Load the 'nest' parameter value into R10.
8032     // R10 is specified in X86CallingConv.td
8033     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8034     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8035                        DAG.getConstant(10, MVT::i64));
8036     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8037                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8038                                 false, false, 0);
8039
8040     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8041                        DAG.getConstant(12, MVT::i64));
8042     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8043                                 MachinePointerInfo(TrmpAddr, 12),
8044                                 false, false, 2);
8045
8046     // Jump to the nested function.
8047     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8048     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8049                        DAG.getConstant(20, MVT::i64));
8050     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8051                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8052                                 false, false, 0);
8053
8054     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8055     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8056                        DAG.getConstant(22, MVT::i64));
8057     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8058                                 MachinePointerInfo(TrmpAddr, 22),
8059                                 false, false, 0);
8060
8061     SDValue Ops[] =
8062       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8063     return DAG.getMergeValues(Ops, 2, dl);
8064   } else {
8065     const Function *Func =
8066       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8067     CallingConv::ID CC = Func->getCallingConv();
8068     unsigned NestReg;
8069
8070     switch (CC) {
8071     default:
8072       llvm_unreachable("Unsupported calling convention");
8073     case CallingConv::C:
8074     case CallingConv::X86_StdCall: {
8075       // Pass 'nest' parameter in ECX.
8076       // Must be kept in sync with X86CallingConv.td
8077       NestReg = X86::ECX;
8078
8079       // Check that ECX wasn't needed by an 'inreg' parameter.
8080       const FunctionType *FTy = Func->getFunctionType();
8081       const AttrListPtr &Attrs = Func->getAttributes();
8082
8083       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8084         unsigned InRegCount = 0;
8085         unsigned Idx = 1;
8086
8087         for (FunctionType::param_iterator I = FTy->param_begin(),
8088              E = FTy->param_end(); I != E; ++I, ++Idx)
8089           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8090             // FIXME: should only count parameters that are lowered to integers.
8091             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8092
8093         if (InRegCount > 2) {
8094           report_fatal_error("Nest register in use - reduce number of inreg"
8095                              " parameters!");
8096         }
8097       }
8098       break;
8099     }
8100     case CallingConv::X86_FastCall:
8101     case CallingConv::X86_ThisCall:
8102     case CallingConv::Fast:
8103       // Pass 'nest' parameter in EAX.
8104       // Must be kept in sync with X86CallingConv.td
8105       NestReg = X86::EAX;
8106       break;
8107     }
8108
8109     SDValue OutChains[4];
8110     SDValue Addr, Disp;
8111
8112     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8113                        DAG.getConstant(10, MVT::i32));
8114     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8115
8116     // This is storing the opcode for MOV32ri.
8117     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8118     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8119     OutChains[0] = DAG.getStore(Root, dl,
8120                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8121                                 Trmp, MachinePointerInfo(TrmpAddr),
8122                                 false, false, 0);
8123
8124     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8125                        DAG.getConstant(1, MVT::i32));
8126     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8127                                 MachinePointerInfo(TrmpAddr, 1),
8128                                 false, false, 1);
8129
8130     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8132                        DAG.getConstant(5, MVT::i32));
8133     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8134                                 MachinePointerInfo(TrmpAddr, 5),
8135                                 false, false, 1);
8136
8137     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8138                        DAG.getConstant(6, MVT::i32));
8139     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8140                                 MachinePointerInfo(TrmpAddr, 6),
8141                                 false, false, 1);
8142
8143     SDValue Ops[] =
8144       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8145     return DAG.getMergeValues(Ops, 2, dl);
8146   }
8147 }
8148
8149 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8150                                             SelectionDAG &DAG) const {
8151   /*
8152    The rounding mode is in bits 11:10 of FPSR, and has the following
8153    settings:
8154      00 Round to nearest
8155      01 Round to -inf
8156      10 Round to +inf
8157      11 Round to 0
8158
8159   FLT_ROUNDS, on the other hand, expects the following:
8160     -1 Undefined
8161      0 Round to 0
8162      1 Round to nearest
8163      2 Round to +inf
8164      3 Round to -inf
8165
8166   To perform the conversion, we do:
8167     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8168   */
8169
8170   MachineFunction &MF = DAG.getMachineFunction();
8171   const TargetMachine &TM = MF.getTarget();
8172   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8173   unsigned StackAlignment = TFI.getStackAlignment();
8174   EVT VT = Op.getValueType();
8175   DebugLoc DL = Op.getDebugLoc();
8176
8177   // Save FP Control Word to stack slot
8178   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8179   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8180
8181
8182   MachineMemOperand *MMO =
8183    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8184                            MachineMemOperand::MOStore, 2, 2);
8185
8186   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8187   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8188                                           DAG.getVTList(MVT::Other),
8189                                           Ops, 2, MVT::i16, MMO);
8190
8191   // Load FP Control Word from stack slot
8192   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8193                             MachinePointerInfo(), false, false, 0);
8194
8195   // Transform as necessary
8196   SDValue CWD1 =
8197     DAG.getNode(ISD::SRL, DL, MVT::i16,
8198                 DAG.getNode(ISD::AND, DL, MVT::i16,
8199                             CWD, DAG.getConstant(0x800, MVT::i16)),
8200                 DAG.getConstant(11, MVT::i8));
8201   SDValue CWD2 =
8202     DAG.getNode(ISD::SRL, DL, MVT::i16,
8203                 DAG.getNode(ISD::AND, DL, MVT::i16,
8204                             CWD, DAG.getConstant(0x400, MVT::i16)),
8205                 DAG.getConstant(9, MVT::i8));
8206
8207   SDValue RetVal =
8208     DAG.getNode(ISD::AND, DL, MVT::i16,
8209                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8210                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8211                             DAG.getConstant(1, MVT::i16)),
8212                 DAG.getConstant(3, MVT::i16));
8213
8214
8215   return DAG.getNode((VT.getSizeInBits() < 16 ?
8216                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8217 }
8218
8219 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8220   EVT VT = Op.getValueType();
8221   EVT OpVT = VT;
8222   unsigned NumBits = VT.getSizeInBits();
8223   DebugLoc dl = Op.getDebugLoc();
8224
8225   Op = Op.getOperand(0);
8226   if (VT == MVT::i8) {
8227     // Zero extend to i32 since there is not an i8 bsr.
8228     OpVT = MVT::i32;
8229     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8230   }
8231
8232   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8233   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8234   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8235
8236   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8237   SDValue Ops[] = {
8238     Op,
8239     DAG.getConstant(NumBits+NumBits-1, OpVT),
8240     DAG.getConstant(X86::COND_E, MVT::i8),
8241     Op.getValue(1)
8242   };
8243   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8244
8245   // Finally xor with NumBits-1.
8246   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8247
8248   if (VT == MVT::i8)
8249     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8250   return Op;
8251 }
8252
8253 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8254   EVT VT = Op.getValueType();
8255   EVT OpVT = VT;
8256   unsigned NumBits = VT.getSizeInBits();
8257   DebugLoc dl = Op.getDebugLoc();
8258
8259   Op = Op.getOperand(0);
8260   if (VT == MVT::i8) {
8261     OpVT = MVT::i32;
8262     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8263   }
8264
8265   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8266   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8267   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8268
8269   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8270   SDValue Ops[] = {
8271     Op,
8272     DAG.getConstant(NumBits, OpVT),
8273     DAG.getConstant(X86::COND_E, MVT::i8),
8274     Op.getValue(1)
8275   };
8276   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8277
8278   if (VT == MVT::i8)
8279     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8280   return Op;
8281 }
8282
8283 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8284   EVT VT = Op.getValueType();
8285   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8286   DebugLoc dl = Op.getDebugLoc();
8287
8288   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8289   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8290   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8291   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8292   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8293   //
8294   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8295   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8296   //  return AloBlo + AloBhi + AhiBlo;
8297
8298   SDValue A = Op.getOperand(0);
8299   SDValue B = Op.getOperand(1);
8300
8301   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8302                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8303                        A, DAG.getConstant(32, MVT::i32));
8304   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8305                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8306                        B, DAG.getConstant(32, MVT::i32));
8307   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8308                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8309                        A, B);
8310   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8311                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8312                        A, Bhi);
8313   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8314                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8315                        Ahi, B);
8316   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8317                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8318                        AloBhi, DAG.getConstant(32, MVT::i32));
8319   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8320                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8321                        AhiBlo, DAG.getConstant(32, MVT::i32));
8322   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8323   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8324   return Res;
8325 }
8326
8327 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8328   EVT VT = Op.getValueType();
8329   DebugLoc dl = Op.getDebugLoc();
8330   SDValue R = Op.getOperand(0);
8331
8332   LLVMContext *Context = DAG.getContext();
8333
8334   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8335
8336   if (VT == MVT::v4i32) {
8337     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8338                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8339                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8340
8341     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8342
8343     std::vector<Constant*> CV(4, CI);
8344     Constant *C = ConstantVector::get(CV);
8345     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8346     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8347                                  MachinePointerInfo::getConstantPool(),
8348                                  false, false, 16);
8349
8350     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8351     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8352     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8353     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8354   }
8355   if (VT == MVT::v16i8) {
8356     // a = a << 5;
8357     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8358                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8359                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8360
8361     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8362     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8363
8364     std::vector<Constant*> CVM1(16, CM1);
8365     std::vector<Constant*> CVM2(16, CM2);
8366     Constant *C = ConstantVector::get(CVM1);
8367     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8368     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8369                             MachinePointerInfo::getConstantPool(),
8370                             false, false, 16);
8371
8372     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8373     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8374     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8375                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8376                     DAG.getConstant(4, MVT::i32));
8377     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8378                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8379                     R, M, Op);
8380     // a += a
8381     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8382
8383     C = ConstantVector::get(CVM2);
8384     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8385     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8386                     MachinePointerInfo::getConstantPool(),
8387                     false, false, 16);
8388
8389     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8390     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8391     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8392                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8393                     DAG.getConstant(2, MVT::i32));
8394     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8395                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8396                     R, M, Op);
8397     // a += a
8398     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8399
8400     // return pblendv(r, r+r, a);
8401     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8402                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8403                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8404     return R;
8405   }
8406   return SDValue();
8407 }
8408
8409 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8410   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8411   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8412   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8413   // has only one use.
8414   SDNode *N = Op.getNode();
8415   SDValue LHS = N->getOperand(0);
8416   SDValue RHS = N->getOperand(1);
8417   unsigned BaseOp = 0;
8418   unsigned Cond = 0;
8419   DebugLoc dl = Op.getDebugLoc();
8420
8421   switch (Op.getOpcode()) {
8422   default: llvm_unreachable("Unknown ovf instruction!");
8423   case ISD::SADDO:
8424     // A subtract of one will be selected as a INC. Note that INC doesn't
8425     // set CF, so we can't do this for UADDO.
8426     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8427       if (C->getAPIntValue() == 1) {
8428         BaseOp = X86ISD::INC;
8429         Cond = X86::COND_O;
8430         break;
8431       }
8432     BaseOp = X86ISD::ADD;
8433     Cond = X86::COND_O;
8434     break;
8435   case ISD::UADDO:
8436     BaseOp = X86ISD::ADD;
8437     Cond = X86::COND_B;
8438     break;
8439   case ISD::SSUBO:
8440     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8441     // set CF, so we can't do this for USUBO.
8442     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8443       if (C->getAPIntValue() == 1) {
8444         BaseOp = X86ISD::DEC;
8445         Cond = X86::COND_O;
8446         break;
8447       }
8448     BaseOp = X86ISD::SUB;
8449     Cond = X86::COND_O;
8450     break;
8451   case ISD::USUBO:
8452     BaseOp = X86ISD::SUB;
8453     Cond = X86::COND_B;
8454     break;
8455   case ISD::SMULO:
8456     BaseOp = X86ISD::SMUL;
8457     Cond = X86::COND_O;
8458     break;
8459   case ISD::UMULO:
8460     BaseOp = X86ISD::UMUL;
8461     Cond = X86::COND_B;
8462     break;
8463   }
8464
8465   // Also sets EFLAGS.
8466   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8467   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8468
8469   SDValue SetCC =
8470     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8471                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8472
8473   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8474   return Sum;
8475 }
8476
8477 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8478   DebugLoc dl = Op.getDebugLoc();
8479
8480   if (!Subtarget->hasSSE2()) {
8481     SDValue Chain = Op.getOperand(0);
8482     SDValue Zero = DAG.getConstant(0,
8483                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8484     SDValue Ops[] = {
8485       DAG.getRegister(X86::ESP, MVT::i32), // Base
8486       DAG.getTargetConstant(1, MVT::i8),   // Scale
8487       DAG.getRegister(0, MVT::i32),        // Index
8488       DAG.getTargetConstant(0, MVT::i32),  // Disp
8489       DAG.getRegister(0, MVT::i32),        // Segment.
8490       Zero,
8491       Chain
8492     };
8493     SDNode *Res =
8494       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8495                           array_lengthof(Ops));
8496     return SDValue(Res, 0);
8497   }
8498
8499   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8500   if (!isDev)
8501     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8502
8503   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8504   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8505   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8506   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8507
8508   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8509   if (!Op1 && !Op2 && !Op3 && Op4)
8510     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8511
8512   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8513   if (Op1 && !Op2 && !Op3 && !Op4)
8514     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8515
8516   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8517   //           (MFENCE)>;
8518   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8519 }
8520
8521 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8522   EVT T = Op.getValueType();
8523   DebugLoc DL = Op.getDebugLoc();
8524   unsigned Reg = 0;
8525   unsigned size = 0;
8526   switch(T.getSimpleVT().SimpleTy) {
8527   default:
8528     assert(false && "Invalid value type!");
8529   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8530   case MVT::i16: Reg = X86::AX;  size = 2; break;
8531   case MVT::i32: Reg = X86::EAX; size = 4; break;
8532   case MVT::i64:
8533     assert(Subtarget->is64Bit() && "Node not type legal!");
8534     Reg = X86::RAX; size = 8;
8535     break;
8536   }
8537   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8538                                     Op.getOperand(2), SDValue());
8539   SDValue Ops[] = { cpIn.getValue(0),
8540                     Op.getOperand(1),
8541                     Op.getOperand(3),
8542                     DAG.getTargetConstant(size, MVT::i8),
8543                     cpIn.getValue(1) };
8544   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8545   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8546   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8547                                            Ops, 5, T, MMO);
8548   SDValue cpOut =
8549     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8550   return cpOut;
8551 }
8552
8553 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8554                                                  SelectionDAG &DAG) const {
8555   assert(Subtarget->is64Bit() && "Result not type legalized?");
8556   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8557   SDValue TheChain = Op.getOperand(0);
8558   DebugLoc dl = Op.getDebugLoc();
8559   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8560   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8561   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8562                                    rax.getValue(2));
8563   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8564                             DAG.getConstant(32, MVT::i8));
8565   SDValue Ops[] = {
8566     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8567     rdx.getValue(1)
8568   };
8569   return DAG.getMergeValues(Ops, 2, dl);
8570 }
8571
8572 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8573                                             SelectionDAG &DAG) const {
8574   EVT SrcVT = Op.getOperand(0).getValueType();
8575   EVT DstVT = Op.getValueType();
8576   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8577           Subtarget->hasMMX() && !DisableMMX) &&
8578          "Unexpected custom BITCAST");
8579   assert((DstVT == MVT::i64 ||
8580           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8581          "Unexpected custom BITCAST");
8582   // i64 <=> MMX conversions are Legal.
8583   if (SrcVT==MVT::i64 && DstVT.isVector())
8584     return Op;
8585   if (DstVT==MVT::i64 && SrcVT.isVector())
8586     return Op;
8587   // MMX <=> MMX conversions are Legal.
8588   if (SrcVT.isVector() && DstVT.isVector())
8589     return Op;
8590   // All other conversions need to be expanded.
8591   return SDValue();
8592 }
8593 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8594   SDNode *Node = Op.getNode();
8595   DebugLoc dl = Node->getDebugLoc();
8596   EVT T = Node->getValueType(0);
8597   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8598                               DAG.getConstant(0, T), Node->getOperand(2));
8599   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8600                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8601                        Node->getOperand(0),
8602                        Node->getOperand(1), negOp,
8603                        cast<AtomicSDNode>(Node)->getSrcValue(),
8604                        cast<AtomicSDNode>(Node)->getAlignment());
8605 }
8606
8607 /// LowerOperation - Provide custom lowering hooks for some operations.
8608 ///
8609 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8610   switch (Op.getOpcode()) {
8611   default: llvm_unreachable("Should not custom lower this!");
8612   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8613   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8614   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8615   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8616   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8617   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8618   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8619   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8620   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8621   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8622   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8623   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8624   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8625   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8626   case ISD::SHL_PARTS:
8627   case ISD::SRA_PARTS:
8628   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8629   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8630   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8631   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8632   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8633   case ISD::FABS:               return LowerFABS(Op, DAG);
8634   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8635   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8636   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8637   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8638   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8639   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8640   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8641   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8642   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8643   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8644   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8645   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8646   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8647   case ISD::FRAME_TO_ARGS_OFFSET:
8648                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8649   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8650   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8651   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8652   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8653   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8654   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8655   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8656   case ISD::SHL:                return LowerSHL(Op, DAG);
8657   case ISD::SADDO:
8658   case ISD::UADDO:
8659   case ISD::SSUBO:
8660   case ISD::USUBO:
8661   case ISD::SMULO:
8662   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8663   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8664   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8665   }
8666 }
8667
8668 void X86TargetLowering::
8669 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8670                         SelectionDAG &DAG, unsigned NewOp) const {
8671   EVT T = Node->getValueType(0);
8672   DebugLoc dl = Node->getDebugLoc();
8673   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8674
8675   SDValue Chain = Node->getOperand(0);
8676   SDValue In1 = Node->getOperand(1);
8677   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8678                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8679   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8680                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8681   SDValue Ops[] = { Chain, In1, In2L, In2H };
8682   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8683   SDValue Result =
8684     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8685                             cast<MemSDNode>(Node)->getMemOperand());
8686   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8687   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8688   Results.push_back(Result.getValue(2));
8689 }
8690
8691 /// ReplaceNodeResults - Replace a node with an illegal result type
8692 /// with a new node built out of custom code.
8693 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8694                                            SmallVectorImpl<SDValue>&Results,
8695                                            SelectionDAG &DAG) const {
8696   DebugLoc dl = N->getDebugLoc();
8697   switch (N->getOpcode()) {
8698   default:
8699     assert(false && "Do not know how to custom type legalize this operation!");
8700     return;
8701   case ISD::FP_TO_SINT: {
8702     std::pair<SDValue,SDValue> Vals =
8703         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8704     SDValue FIST = Vals.first, StackSlot = Vals.second;
8705     if (FIST.getNode() != 0) {
8706       EVT VT = N->getValueType(0);
8707       // Return a load from the stack slot.
8708       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8709                                     MachinePointerInfo(), false, false, 0));
8710     }
8711     return;
8712   }
8713   case ISD::READCYCLECOUNTER: {
8714     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8715     SDValue TheChain = N->getOperand(0);
8716     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8717     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8718                                      rd.getValue(1));
8719     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8720                                      eax.getValue(2));
8721     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8722     SDValue Ops[] = { eax, edx };
8723     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8724     Results.push_back(edx.getValue(1));
8725     return;
8726   }
8727   case ISD::ATOMIC_CMP_SWAP: {
8728     EVT T = N->getValueType(0);
8729     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8730     SDValue cpInL, cpInH;
8731     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8732                         DAG.getConstant(0, MVT::i32));
8733     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8734                         DAG.getConstant(1, MVT::i32));
8735     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8736     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8737                              cpInL.getValue(1));
8738     SDValue swapInL, swapInH;
8739     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8740                           DAG.getConstant(0, MVT::i32));
8741     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8742                           DAG.getConstant(1, MVT::i32));
8743     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8744                                cpInH.getValue(1));
8745     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8746                                swapInL.getValue(1));
8747     SDValue Ops[] = { swapInH.getValue(0),
8748                       N->getOperand(1),
8749                       swapInH.getValue(1) };
8750     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8751     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8752     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8753                                              Ops, 3, T, MMO);
8754     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8755                                         MVT::i32, Result.getValue(1));
8756     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8757                                         MVT::i32, cpOutL.getValue(2));
8758     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8759     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8760     Results.push_back(cpOutH.getValue(1));
8761     return;
8762   }
8763   case ISD::ATOMIC_LOAD_ADD:
8764     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8765     return;
8766   case ISD::ATOMIC_LOAD_AND:
8767     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8768     return;
8769   case ISD::ATOMIC_LOAD_NAND:
8770     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8771     return;
8772   case ISD::ATOMIC_LOAD_OR:
8773     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8774     return;
8775   case ISD::ATOMIC_LOAD_SUB:
8776     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8777     return;
8778   case ISD::ATOMIC_LOAD_XOR:
8779     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8780     return;
8781   case ISD::ATOMIC_SWAP:
8782     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8783     return;
8784   }
8785 }
8786
8787 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8788   switch (Opcode) {
8789   default: return NULL;
8790   case X86ISD::BSF:                return "X86ISD::BSF";
8791   case X86ISD::BSR:                return "X86ISD::BSR";
8792   case X86ISD::SHLD:               return "X86ISD::SHLD";
8793   case X86ISD::SHRD:               return "X86ISD::SHRD";
8794   case X86ISD::FAND:               return "X86ISD::FAND";
8795   case X86ISD::FOR:                return "X86ISD::FOR";
8796   case X86ISD::FXOR:               return "X86ISD::FXOR";
8797   case X86ISD::FSRL:               return "X86ISD::FSRL";
8798   case X86ISD::FILD:               return "X86ISD::FILD";
8799   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8800   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8801   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8802   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8803   case X86ISD::FLD:                return "X86ISD::FLD";
8804   case X86ISD::FST:                return "X86ISD::FST";
8805   case X86ISD::CALL:               return "X86ISD::CALL";
8806   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8807   case X86ISD::BT:                 return "X86ISD::BT";
8808   case X86ISD::CMP:                return "X86ISD::CMP";
8809   case X86ISD::COMI:               return "X86ISD::COMI";
8810   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8811   case X86ISD::SETCC:              return "X86ISD::SETCC";
8812   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8813   case X86ISD::CMOV:               return "X86ISD::CMOV";
8814   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8815   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8816   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8817   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8818   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8819   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8820   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8821   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8822   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8823   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8824   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8825   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8826   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8827   case X86ISD::FMAX:               return "X86ISD::FMAX";
8828   case X86ISD::FMIN:               return "X86ISD::FMIN";
8829   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8830   case X86ISD::FRCP:               return "X86ISD::FRCP";
8831   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8832   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8833   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8834   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8835   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8836   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8837   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8838   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8839   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8840   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8841   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8842   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8843   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8844   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8845   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8846   case X86ISD::VSHL:               return "X86ISD::VSHL";
8847   case X86ISD::VSRL:               return "X86ISD::VSRL";
8848   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8849   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8850   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8851   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8852   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8853   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8854   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8855   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8856   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8857   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8858   case X86ISD::ADD:                return "X86ISD::ADD";
8859   case X86ISD::SUB:                return "X86ISD::SUB";
8860   case X86ISD::SMUL:               return "X86ISD::SMUL";
8861   case X86ISD::UMUL:               return "X86ISD::UMUL";
8862   case X86ISD::INC:                return "X86ISD::INC";
8863   case X86ISD::DEC:                return "X86ISD::DEC";
8864   case X86ISD::OR:                 return "X86ISD::OR";
8865   case X86ISD::XOR:                return "X86ISD::XOR";
8866   case X86ISD::AND:                return "X86ISD::AND";
8867   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8868   case X86ISD::PTEST:              return "X86ISD::PTEST";
8869   case X86ISD::TESTP:              return "X86ISD::TESTP";
8870   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8871   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8872   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8873   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8874   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8875   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8876   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8877   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8878   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8879   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8880   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8881   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8882   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8883   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8884   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8885   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8886   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8887   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8888   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8889   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8890   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8891   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8892   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8893   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8894   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8895   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8896   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8897   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8898   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8899   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8900   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8901   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8902   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8903   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8904   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
8905   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
8906   }
8907 }
8908
8909 // isLegalAddressingMode - Return true if the addressing mode represented
8910 // by AM is legal for this target, for a load/store of the specified type.
8911 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8912                                               const Type *Ty) const {
8913   // X86 supports extremely general addressing modes.
8914   CodeModel::Model M = getTargetMachine().getCodeModel();
8915   Reloc::Model R = getTargetMachine().getRelocationModel();
8916
8917   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8918   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8919     return false;
8920
8921   if (AM.BaseGV) {
8922     unsigned GVFlags =
8923       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8924
8925     // If a reference to this global requires an extra load, we can't fold it.
8926     if (isGlobalStubReference(GVFlags))
8927       return false;
8928
8929     // If BaseGV requires a register for the PIC base, we cannot also have a
8930     // BaseReg specified.
8931     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8932       return false;
8933
8934     // If lower 4G is not available, then we must use rip-relative addressing.
8935     if ((M != CodeModel::Small || R != Reloc::Static) &&
8936         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8937       return false;
8938   }
8939
8940   switch (AM.Scale) {
8941   case 0:
8942   case 1:
8943   case 2:
8944   case 4:
8945   case 8:
8946     // These scales always work.
8947     break;
8948   case 3:
8949   case 5:
8950   case 9:
8951     // These scales are formed with basereg+scalereg.  Only accept if there is
8952     // no basereg yet.
8953     if (AM.HasBaseReg)
8954       return false;
8955     break;
8956   default:  // Other stuff never works.
8957     return false;
8958   }
8959
8960   return true;
8961 }
8962
8963
8964 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8965   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8966     return false;
8967   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8968   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8969   if (NumBits1 <= NumBits2)
8970     return false;
8971   return true;
8972 }
8973
8974 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8975   if (!VT1.isInteger() || !VT2.isInteger())
8976     return false;
8977   unsigned NumBits1 = VT1.getSizeInBits();
8978   unsigned NumBits2 = VT2.getSizeInBits();
8979   if (NumBits1 <= NumBits2)
8980     return false;
8981   return true;
8982 }
8983
8984 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8985   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8986   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8987 }
8988
8989 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8990   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8991   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8992 }
8993
8994 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8995   // i16 instructions are longer (0x66 prefix) and potentially slower.
8996   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8997 }
8998
8999 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9000 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9001 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9002 /// are assumed to be legal.
9003 bool
9004 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9005                                       EVT VT) const {
9006   // Very little shuffling can be done for 64-bit vectors right now.
9007   if (VT.getSizeInBits() == 64)
9008     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9009
9010   // FIXME: pshufb, blends, shifts.
9011   return (VT.getVectorNumElements() == 2 ||
9012           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9013           isMOVLMask(M, VT) ||
9014           isSHUFPMask(M, VT) ||
9015           isPSHUFDMask(M, VT) ||
9016           isPSHUFHWMask(M, VT) ||
9017           isPSHUFLWMask(M, VT) ||
9018           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9019           isUNPCKLMask(M, VT) ||
9020           isUNPCKHMask(M, VT) ||
9021           isUNPCKL_v_undef_Mask(M, VT) ||
9022           isUNPCKH_v_undef_Mask(M, VT));
9023 }
9024
9025 bool
9026 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9027                                           EVT VT) const {
9028   unsigned NumElts = VT.getVectorNumElements();
9029   // FIXME: This collection of masks seems suspect.
9030   if (NumElts == 2)
9031     return true;
9032   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9033     return (isMOVLMask(Mask, VT)  ||
9034             isCommutedMOVLMask(Mask, VT, true) ||
9035             isSHUFPMask(Mask, VT) ||
9036             isCommutedSHUFPMask(Mask, VT));
9037   }
9038   return false;
9039 }
9040
9041 //===----------------------------------------------------------------------===//
9042 //                           X86 Scheduler Hooks
9043 //===----------------------------------------------------------------------===//
9044
9045 // private utility function
9046 MachineBasicBlock *
9047 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9048                                                        MachineBasicBlock *MBB,
9049                                                        unsigned regOpc,
9050                                                        unsigned immOpc,
9051                                                        unsigned LoadOpc,
9052                                                        unsigned CXchgOpc,
9053                                                        unsigned notOpc,
9054                                                        unsigned EAXreg,
9055                                                        TargetRegisterClass *RC,
9056                                                        bool invSrc) const {
9057   // For the atomic bitwise operator, we generate
9058   //   thisMBB:
9059   //   newMBB:
9060   //     ld  t1 = [bitinstr.addr]
9061   //     op  t2 = t1, [bitinstr.val]
9062   //     mov EAX = t1
9063   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9064   //     bz  newMBB
9065   //     fallthrough -->nextMBB
9066   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9067   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9068   MachineFunction::iterator MBBIter = MBB;
9069   ++MBBIter;
9070
9071   /// First build the CFG
9072   MachineFunction *F = MBB->getParent();
9073   MachineBasicBlock *thisMBB = MBB;
9074   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9075   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9076   F->insert(MBBIter, newMBB);
9077   F->insert(MBBIter, nextMBB);
9078
9079   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9080   nextMBB->splice(nextMBB->begin(), thisMBB,
9081                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9082                   thisMBB->end());
9083   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9084
9085   // Update thisMBB to fall through to newMBB
9086   thisMBB->addSuccessor(newMBB);
9087
9088   // newMBB jumps to itself and fall through to nextMBB
9089   newMBB->addSuccessor(nextMBB);
9090   newMBB->addSuccessor(newMBB);
9091
9092   // Insert instructions into newMBB based on incoming instruction
9093   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9094          "unexpected number of operands");
9095   DebugLoc dl = bInstr->getDebugLoc();
9096   MachineOperand& destOper = bInstr->getOperand(0);
9097   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9098   int numArgs = bInstr->getNumOperands() - 1;
9099   for (int i=0; i < numArgs; ++i)
9100     argOpers[i] = &bInstr->getOperand(i+1);
9101
9102   // x86 address has 4 operands: base, index, scale, and displacement
9103   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9104   int valArgIndx = lastAddrIndx + 1;
9105
9106   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9107   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9108   for (int i=0; i <= lastAddrIndx; ++i)
9109     (*MIB).addOperand(*argOpers[i]);
9110
9111   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9112   if (invSrc) {
9113     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9114   }
9115   else
9116     tt = t1;
9117
9118   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9119   assert((argOpers[valArgIndx]->isReg() ||
9120           argOpers[valArgIndx]->isImm()) &&
9121          "invalid operand");
9122   if (argOpers[valArgIndx]->isReg())
9123     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9124   else
9125     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9126   MIB.addReg(tt);
9127   (*MIB).addOperand(*argOpers[valArgIndx]);
9128
9129   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9130   MIB.addReg(t1);
9131
9132   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9133   for (int i=0; i <= lastAddrIndx; ++i)
9134     (*MIB).addOperand(*argOpers[i]);
9135   MIB.addReg(t2);
9136   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9137   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9138                     bInstr->memoperands_end());
9139
9140   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9141   MIB.addReg(EAXreg);
9142
9143   // insert branch
9144   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9145
9146   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9147   return nextMBB;
9148 }
9149
9150 // private utility function:  64 bit atomics on 32 bit host.
9151 MachineBasicBlock *
9152 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9153                                                        MachineBasicBlock *MBB,
9154                                                        unsigned regOpcL,
9155                                                        unsigned regOpcH,
9156                                                        unsigned immOpcL,
9157                                                        unsigned immOpcH,
9158                                                        bool invSrc) const {
9159   // For the atomic bitwise operator, we generate
9160   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9161   //     ld t1,t2 = [bitinstr.addr]
9162   //   newMBB:
9163   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9164   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9165   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9166   //     mov ECX, EBX <- t5, t6
9167   //     mov EAX, EDX <- t1, t2
9168   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9169   //     mov t3, t4 <- EAX, EDX
9170   //     bz  newMBB
9171   //     result in out1, out2
9172   //     fallthrough -->nextMBB
9173
9174   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9175   const unsigned LoadOpc = X86::MOV32rm;
9176   const unsigned NotOpc = X86::NOT32r;
9177   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9178   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9179   MachineFunction::iterator MBBIter = MBB;
9180   ++MBBIter;
9181
9182   /// First build the CFG
9183   MachineFunction *F = MBB->getParent();
9184   MachineBasicBlock *thisMBB = MBB;
9185   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9186   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9187   F->insert(MBBIter, newMBB);
9188   F->insert(MBBIter, nextMBB);
9189
9190   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9191   nextMBB->splice(nextMBB->begin(), thisMBB,
9192                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9193                   thisMBB->end());
9194   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9195
9196   // Update thisMBB to fall through to newMBB
9197   thisMBB->addSuccessor(newMBB);
9198
9199   // newMBB jumps to itself and fall through to nextMBB
9200   newMBB->addSuccessor(nextMBB);
9201   newMBB->addSuccessor(newMBB);
9202
9203   DebugLoc dl = bInstr->getDebugLoc();
9204   // Insert instructions into newMBB based on incoming instruction
9205   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9206   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9207          "unexpected number of operands");
9208   MachineOperand& dest1Oper = bInstr->getOperand(0);
9209   MachineOperand& dest2Oper = bInstr->getOperand(1);
9210   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9211   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9212     argOpers[i] = &bInstr->getOperand(i+2);
9213
9214     // We use some of the operands multiple times, so conservatively just
9215     // clear any kill flags that might be present.
9216     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9217       argOpers[i]->setIsKill(false);
9218   }
9219
9220   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9221   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9222
9223   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9224   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9225   for (int i=0; i <= lastAddrIndx; ++i)
9226     (*MIB).addOperand(*argOpers[i]);
9227   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9228   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9229   // add 4 to displacement.
9230   for (int i=0; i <= lastAddrIndx-2; ++i)
9231     (*MIB).addOperand(*argOpers[i]);
9232   MachineOperand newOp3 = *(argOpers[3]);
9233   if (newOp3.isImm())
9234     newOp3.setImm(newOp3.getImm()+4);
9235   else
9236     newOp3.setOffset(newOp3.getOffset()+4);
9237   (*MIB).addOperand(newOp3);
9238   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9239
9240   // t3/4 are defined later, at the bottom of the loop
9241   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9242   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9243   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9244     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9245   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9246     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9247
9248   // The subsequent operations should be using the destination registers of
9249   //the PHI instructions.
9250   if (invSrc) {
9251     t1 = F->getRegInfo().createVirtualRegister(RC);
9252     t2 = F->getRegInfo().createVirtualRegister(RC);
9253     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9254     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9255   } else {
9256     t1 = dest1Oper.getReg();
9257     t2 = dest2Oper.getReg();
9258   }
9259
9260   int valArgIndx = lastAddrIndx + 1;
9261   assert((argOpers[valArgIndx]->isReg() ||
9262           argOpers[valArgIndx]->isImm()) &&
9263          "invalid operand");
9264   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9265   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9266   if (argOpers[valArgIndx]->isReg())
9267     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9268   else
9269     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9270   if (regOpcL != X86::MOV32rr)
9271     MIB.addReg(t1);
9272   (*MIB).addOperand(*argOpers[valArgIndx]);
9273   assert(argOpers[valArgIndx + 1]->isReg() ==
9274          argOpers[valArgIndx]->isReg());
9275   assert(argOpers[valArgIndx + 1]->isImm() ==
9276          argOpers[valArgIndx]->isImm());
9277   if (argOpers[valArgIndx + 1]->isReg())
9278     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9279   else
9280     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9281   if (regOpcH != X86::MOV32rr)
9282     MIB.addReg(t2);
9283   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9284
9285   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9286   MIB.addReg(t1);
9287   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9288   MIB.addReg(t2);
9289
9290   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9291   MIB.addReg(t5);
9292   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9293   MIB.addReg(t6);
9294
9295   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9296   for (int i=0; i <= lastAddrIndx; ++i)
9297     (*MIB).addOperand(*argOpers[i]);
9298
9299   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9300   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9301                     bInstr->memoperands_end());
9302
9303   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9304   MIB.addReg(X86::EAX);
9305   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9306   MIB.addReg(X86::EDX);
9307
9308   // insert branch
9309   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9310
9311   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9312   return nextMBB;
9313 }
9314
9315 // private utility function
9316 MachineBasicBlock *
9317 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9318                                                       MachineBasicBlock *MBB,
9319                                                       unsigned cmovOpc) const {
9320   // For the atomic min/max operator, we generate
9321   //   thisMBB:
9322   //   newMBB:
9323   //     ld t1 = [min/max.addr]
9324   //     mov t2 = [min/max.val]
9325   //     cmp  t1, t2
9326   //     cmov[cond] t2 = t1
9327   //     mov EAX = t1
9328   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9329   //     bz   newMBB
9330   //     fallthrough -->nextMBB
9331   //
9332   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9333   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9334   MachineFunction::iterator MBBIter = MBB;
9335   ++MBBIter;
9336
9337   /// First build the CFG
9338   MachineFunction *F = MBB->getParent();
9339   MachineBasicBlock *thisMBB = MBB;
9340   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9341   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9342   F->insert(MBBIter, newMBB);
9343   F->insert(MBBIter, nextMBB);
9344
9345   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9346   nextMBB->splice(nextMBB->begin(), thisMBB,
9347                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9348                   thisMBB->end());
9349   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9350
9351   // Update thisMBB to fall through to newMBB
9352   thisMBB->addSuccessor(newMBB);
9353
9354   // newMBB jumps to newMBB and fall through to nextMBB
9355   newMBB->addSuccessor(nextMBB);
9356   newMBB->addSuccessor(newMBB);
9357
9358   DebugLoc dl = mInstr->getDebugLoc();
9359   // Insert instructions into newMBB based on incoming instruction
9360   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9361          "unexpected number of operands");
9362   MachineOperand& destOper = mInstr->getOperand(0);
9363   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9364   int numArgs = mInstr->getNumOperands() - 1;
9365   for (int i=0; i < numArgs; ++i)
9366     argOpers[i] = &mInstr->getOperand(i+1);
9367
9368   // x86 address has 4 operands: base, index, scale, and displacement
9369   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9370   int valArgIndx = lastAddrIndx + 1;
9371
9372   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9373   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9374   for (int i=0; i <= lastAddrIndx; ++i)
9375     (*MIB).addOperand(*argOpers[i]);
9376
9377   // We only support register and immediate values
9378   assert((argOpers[valArgIndx]->isReg() ||
9379           argOpers[valArgIndx]->isImm()) &&
9380          "invalid operand");
9381
9382   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9383   if (argOpers[valArgIndx]->isReg())
9384     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9385   else
9386     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9387   (*MIB).addOperand(*argOpers[valArgIndx]);
9388
9389   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9390   MIB.addReg(t1);
9391
9392   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9393   MIB.addReg(t1);
9394   MIB.addReg(t2);
9395
9396   // Generate movc
9397   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9398   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9399   MIB.addReg(t2);
9400   MIB.addReg(t1);
9401
9402   // Cmp and exchange if none has modified the memory location
9403   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9404   for (int i=0; i <= lastAddrIndx; ++i)
9405     (*MIB).addOperand(*argOpers[i]);
9406   MIB.addReg(t3);
9407   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9408   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9409                     mInstr->memoperands_end());
9410
9411   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9412   MIB.addReg(X86::EAX);
9413
9414   // insert branch
9415   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9416
9417   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9418   return nextMBB;
9419 }
9420
9421 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9422 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9423 // in the .td file.
9424 MachineBasicBlock *
9425 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9426                             unsigned numArgs, bool memArg) const {
9427   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9428          "Target must have SSE4.2 or AVX features enabled");
9429
9430   DebugLoc dl = MI->getDebugLoc();
9431   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9432   unsigned Opc;
9433   if (!Subtarget->hasAVX()) {
9434     if (memArg)
9435       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9436     else
9437       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9438   } else {
9439     if (memArg)
9440       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9441     else
9442       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9443   }
9444
9445   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9446   for (unsigned i = 0; i < numArgs; ++i) {
9447     MachineOperand &Op = MI->getOperand(i+1);
9448     if (!(Op.isReg() && Op.isImplicit()))
9449       MIB.addOperand(Op);
9450   }
9451   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9452     .addReg(X86::XMM0);
9453
9454   MI->eraseFromParent();
9455   return BB;
9456 }
9457
9458 MachineBasicBlock *
9459 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9460   assert(Subtarget->hasSSE3() && "Target must have SSE3 features enabled");
9461   
9462   DebugLoc dl = MI->getDebugLoc();
9463   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9464   
9465   // Address into RAX/EAX, other two args into ECX, EDX.
9466   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9467   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9468   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9469   for (int i = 0; i < X86::AddrNumOperands; ++i)
9470     MIB.addOperand(MI->getOperand(i));
9471   
9472   unsigned ValOps = X86::AddrNumOperands;
9473   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9474     .addReg(MI->getOperand(ValOps).getReg());
9475   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9476     .addReg(MI->getOperand(ValOps+1).getReg());
9477
9478   // The instruction doesn't actually take any operands though.
9479   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9480   
9481   MI->eraseFromParent(); // The pseudo is gone now.
9482   return BB;
9483 }
9484
9485 MachineBasicBlock *
9486 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9487   assert(Subtarget->hasSSE3() && "Target must have SSE3 features enabled");
9488   
9489   DebugLoc dl = MI->getDebugLoc();
9490   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9491   
9492   // First arg in ECX, the second in EAX.
9493   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9494     .addReg(MI->getOperand(0).getReg());
9495   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9496     .addReg(MI->getOperand(1).getReg());
9497     
9498   // The instruction doesn't actually take any operands though.
9499   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9500   
9501   MI->eraseFromParent(); // The pseudo is gone now.
9502   return BB;
9503 }
9504
9505 MachineBasicBlock *
9506 X86TargetLowering::EmitVAARG64WithCustomInserter(
9507                    MachineInstr *MI,
9508                    MachineBasicBlock *MBB) const {
9509   // Emit va_arg instruction on X86-64.
9510
9511   // Operands to this pseudo-instruction:
9512   // 0  ) Output        : destination address (reg)
9513   // 1-5) Input         : va_list address (addr, i64mem)
9514   // 6  ) ArgSize       : Size (in bytes) of vararg type
9515   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9516   // 8  ) Align         : Alignment of type
9517   // 9  ) EFLAGS (implicit-def)
9518
9519   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9520   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9521
9522   unsigned DestReg = MI->getOperand(0).getReg();
9523   MachineOperand &Base = MI->getOperand(1);
9524   MachineOperand &Scale = MI->getOperand(2);
9525   MachineOperand &Index = MI->getOperand(3);
9526   MachineOperand &Disp = MI->getOperand(4);
9527   MachineOperand &Segment = MI->getOperand(5);
9528   unsigned ArgSize = MI->getOperand(6).getImm();
9529   unsigned ArgMode = MI->getOperand(7).getImm();
9530   unsigned Align = MI->getOperand(8).getImm();
9531
9532   // Memory Reference
9533   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9534   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9535   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9536
9537   // Machine Information
9538   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9539   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9540   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9541   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9542   DebugLoc DL = MI->getDebugLoc();
9543
9544   // struct va_list {
9545   //   i32   gp_offset
9546   //   i32   fp_offset
9547   //   i64   overflow_area (address)
9548   //   i64   reg_save_area (address)
9549   // }
9550   // sizeof(va_list) = 24
9551   // alignment(va_list) = 8
9552
9553   unsigned TotalNumIntRegs = 6;
9554   unsigned TotalNumXMMRegs = 8;
9555   bool UseGPOffset = (ArgMode == 1);
9556   bool UseFPOffset = (ArgMode == 2);
9557   unsigned MaxOffset = TotalNumIntRegs * 8 +
9558                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9559
9560   /* Align ArgSize to a multiple of 8 */
9561   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9562   bool NeedsAlign = (Align > 8);
9563
9564   MachineBasicBlock *thisMBB = MBB;
9565   MachineBasicBlock *overflowMBB;
9566   MachineBasicBlock *offsetMBB;
9567   MachineBasicBlock *endMBB;
9568
9569   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9570   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9571   unsigned OffsetReg = 0;
9572
9573   if (!UseGPOffset && !UseFPOffset) {
9574     // If we only pull from the overflow region, we don't create a branch.
9575     // We don't need to alter control flow.
9576     OffsetDestReg = 0; // unused
9577     OverflowDestReg = DestReg;
9578
9579     offsetMBB = NULL;
9580     overflowMBB = thisMBB;
9581     endMBB = thisMBB;
9582   } else {
9583     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9584     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9585     // If not, pull from overflow_area. (branch to overflowMBB)
9586     //
9587     //       thisMBB
9588     //         |     .
9589     //         |        .
9590     //     offsetMBB   overflowMBB
9591     //         |        .
9592     //         |     .
9593     //        endMBB
9594
9595     // Registers for the PHI in endMBB
9596     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9597     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9598
9599     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9600     MachineFunction *MF = MBB->getParent();
9601     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9602     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9603     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9604
9605     MachineFunction::iterator MBBIter = MBB;
9606     ++MBBIter;
9607
9608     // Insert the new basic blocks
9609     MF->insert(MBBIter, offsetMBB);
9610     MF->insert(MBBIter, overflowMBB);
9611     MF->insert(MBBIter, endMBB);
9612
9613     // Transfer the remainder of MBB and its successor edges to endMBB.
9614     endMBB->splice(endMBB->begin(), thisMBB,
9615                     llvm::next(MachineBasicBlock::iterator(MI)),
9616                     thisMBB->end());
9617     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9618
9619     // Make offsetMBB and overflowMBB successors of thisMBB
9620     thisMBB->addSuccessor(offsetMBB);
9621     thisMBB->addSuccessor(overflowMBB);
9622
9623     // endMBB is a successor of both offsetMBB and overflowMBB
9624     offsetMBB->addSuccessor(endMBB);
9625     overflowMBB->addSuccessor(endMBB);
9626
9627     // Load the offset value into a register
9628     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9629     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9630       .addOperand(Base)
9631       .addOperand(Scale)
9632       .addOperand(Index)
9633       .addDisp(Disp, UseFPOffset ? 4 : 0)
9634       .addOperand(Segment)
9635       .setMemRefs(MMOBegin, MMOEnd);
9636
9637     // Check if there is enough room left to pull this argument.
9638     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9639       .addReg(OffsetReg)
9640       .addImm(MaxOffset + 8 - ArgSizeA8);
9641
9642     // Branch to "overflowMBB" if offset >= max
9643     // Fall through to "offsetMBB" otherwise
9644     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9645       .addMBB(overflowMBB);
9646   }
9647
9648   // In offsetMBB, emit code to use the reg_save_area.
9649   if (offsetMBB) {
9650     assert(OffsetReg != 0);
9651
9652     // Read the reg_save_area address.
9653     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9654     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9655       .addOperand(Base)
9656       .addOperand(Scale)
9657       .addOperand(Index)
9658       .addDisp(Disp, 16)
9659       .addOperand(Segment)
9660       .setMemRefs(MMOBegin, MMOEnd);
9661
9662     // Zero-extend the offset
9663     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9664       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9665         .addImm(0)
9666         .addReg(OffsetReg)
9667         .addImm(X86::sub_32bit);
9668
9669     // Add the offset to the reg_save_area to get the final address.
9670     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9671       .addReg(OffsetReg64)
9672       .addReg(RegSaveReg);
9673
9674     // Compute the offset for the next argument
9675     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9676     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9677       .addReg(OffsetReg)
9678       .addImm(UseFPOffset ? 16 : 8);
9679
9680     // Store it back into the va_list.
9681     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9682       .addOperand(Base)
9683       .addOperand(Scale)
9684       .addOperand(Index)
9685       .addDisp(Disp, UseFPOffset ? 4 : 0)
9686       .addOperand(Segment)
9687       .addReg(NextOffsetReg)
9688       .setMemRefs(MMOBegin, MMOEnd);
9689
9690     // Jump to endMBB
9691     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9692       .addMBB(endMBB);
9693   }
9694
9695   //
9696   // Emit code to use overflow area
9697   //
9698
9699   // Load the overflow_area address into a register.
9700   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9701   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9702     .addOperand(Base)
9703     .addOperand(Scale)
9704     .addOperand(Index)
9705     .addDisp(Disp, 8)
9706     .addOperand(Segment)
9707     .setMemRefs(MMOBegin, MMOEnd);
9708
9709   // If we need to align it, do so. Otherwise, just copy the address
9710   // to OverflowDestReg.
9711   if (NeedsAlign) {
9712     // Align the overflow address
9713     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9714     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9715
9716     // aligned_addr = (addr + (align-1)) & ~(align-1)
9717     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9718       .addReg(OverflowAddrReg)
9719       .addImm(Align-1);
9720
9721     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9722       .addReg(TmpReg)
9723       .addImm(~(uint64_t)(Align-1));
9724   } else {
9725     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9726       .addReg(OverflowAddrReg);
9727   }
9728
9729   // Compute the next overflow address after this argument.
9730   // (the overflow address should be kept 8-byte aligned)
9731   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9732   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9733     .addReg(OverflowDestReg)
9734     .addImm(ArgSizeA8);
9735
9736   // Store the new overflow address.
9737   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9738     .addOperand(Base)
9739     .addOperand(Scale)
9740     .addOperand(Index)
9741     .addDisp(Disp, 8)
9742     .addOperand(Segment)
9743     .addReg(NextAddrReg)
9744     .setMemRefs(MMOBegin, MMOEnd);
9745
9746   // If we branched, emit the PHI to the front of endMBB.
9747   if (offsetMBB) {
9748     BuildMI(*endMBB, endMBB->begin(), DL,
9749             TII->get(X86::PHI), DestReg)
9750       .addReg(OffsetDestReg).addMBB(offsetMBB)
9751       .addReg(OverflowDestReg).addMBB(overflowMBB);
9752   }
9753
9754   // Erase the pseudo instruction
9755   MI->eraseFromParent();
9756
9757   return endMBB;
9758 }
9759
9760 MachineBasicBlock *
9761 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9762                                                  MachineInstr *MI,
9763                                                  MachineBasicBlock *MBB) const {
9764   // Emit code to save XMM registers to the stack. The ABI says that the
9765   // number of registers to save is given in %al, so it's theoretically
9766   // possible to do an indirect jump trick to avoid saving all of them,
9767   // however this code takes a simpler approach and just executes all
9768   // of the stores if %al is non-zero. It's less code, and it's probably
9769   // easier on the hardware branch predictor, and stores aren't all that
9770   // expensive anyway.
9771
9772   // Create the new basic blocks. One block contains all the XMM stores,
9773   // and one block is the final destination regardless of whether any
9774   // stores were performed.
9775   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9776   MachineFunction *F = MBB->getParent();
9777   MachineFunction::iterator MBBIter = MBB;
9778   ++MBBIter;
9779   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9780   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9781   F->insert(MBBIter, XMMSaveMBB);
9782   F->insert(MBBIter, EndMBB);
9783
9784   // Transfer the remainder of MBB and its successor edges to EndMBB.
9785   EndMBB->splice(EndMBB->begin(), MBB,
9786                  llvm::next(MachineBasicBlock::iterator(MI)),
9787                  MBB->end());
9788   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9789
9790   // The original block will now fall through to the XMM save block.
9791   MBB->addSuccessor(XMMSaveMBB);
9792   // The XMMSaveMBB will fall through to the end block.
9793   XMMSaveMBB->addSuccessor(EndMBB);
9794
9795   // Now add the instructions.
9796   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9797   DebugLoc DL = MI->getDebugLoc();
9798
9799   unsigned CountReg = MI->getOperand(0).getReg();
9800   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9801   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9802
9803   if (!Subtarget->isTargetWin64()) {
9804     // If %al is 0, branch around the XMM save block.
9805     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9806     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9807     MBB->addSuccessor(EndMBB);
9808   }
9809
9810   // In the XMM save block, save all the XMM argument registers.
9811   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9812     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9813     MachineMemOperand *MMO =
9814       F->getMachineMemOperand(
9815           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9816         MachineMemOperand::MOStore,
9817         /*Size=*/16, /*Align=*/16);
9818     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9819       .addFrameIndex(RegSaveFrameIndex)
9820       .addImm(/*Scale=*/1)
9821       .addReg(/*IndexReg=*/0)
9822       .addImm(/*Disp=*/Offset)
9823       .addReg(/*Segment=*/0)
9824       .addReg(MI->getOperand(i).getReg())
9825       .addMemOperand(MMO);
9826   }
9827
9828   MI->eraseFromParent();   // The pseudo instruction is gone now.
9829
9830   return EndMBB;
9831 }
9832
9833 MachineBasicBlock *
9834 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9835                                      MachineBasicBlock *BB) const {
9836   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9837   DebugLoc DL = MI->getDebugLoc();
9838
9839   // To "insert" a SELECT_CC instruction, we actually have to insert the
9840   // diamond control-flow pattern.  The incoming instruction knows the
9841   // destination vreg to set, the condition code register to branch on, the
9842   // true/false values to select between, and a branch opcode to use.
9843   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9844   MachineFunction::iterator It = BB;
9845   ++It;
9846
9847   //  thisMBB:
9848   //  ...
9849   //   TrueVal = ...
9850   //   cmpTY ccX, r1, r2
9851   //   bCC copy1MBB
9852   //   fallthrough --> copy0MBB
9853   MachineBasicBlock *thisMBB = BB;
9854   MachineFunction *F = BB->getParent();
9855   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9856   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9857   F->insert(It, copy0MBB);
9858   F->insert(It, sinkMBB);
9859
9860   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9861   // live into the sink and copy blocks.
9862   const MachineFunction *MF = BB->getParent();
9863   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9864   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9865
9866   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9867     const MachineOperand &MO = MI->getOperand(I);
9868     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9869     unsigned Reg = MO.getReg();
9870     if (Reg != X86::EFLAGS) continue;
9871     copy0MBB->addLiveIn(Reg);
9872     sinkMBB->addLiveIn(Reg);
9873   }
9874
9875   // Transfer the remainder of BB and its successor edges to sinkMBB.
9876   sinkMBB->splice(sinkMBB->begin(), BB,
9877                   llvm::next(MachineBasicBlock::iterator(MI)),
9878                   BB->end());
9879   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9880
9881   // Add the true and fallthrough blocks as its successors.
9882   BB->addSuccessor(copy0MBB);
9883   BB->addSuccessor(sinkMBB);
9884
9885   // Create the conditional branch instruction.
9886   unsigned Opc =
9887     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9888   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9889
9890   //  copy0MBB:
9891   //   %FalseValue = ...
9892   //   # fallthrough to sinkMBB
9893   copy0MBB->addSuccessor(sinkMBB);
9894
9895   //  sinkMBB:
9896   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9897   //  ...
9898   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9899           TII->get(X86::PHI), MI->getOperand(0).getReg())
9900     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9901     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9902
9903   MI->eraseFromParent();   // The pseudo instruction is gone now.
9904   return sinkMBB;
9905 }
9906
9907 MachineBasicBlock *
9908 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9909                                           MachineBasicBlock *BB) const {
9910   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9911   DebugLoc DL = MI->getDebugLoc();
9912
9913   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9914   // non-trivial part is impdef of ESP.
9915   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9916   // mingw-w64.
9917
9918   const char *StackProbeSymbol =
9919       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9920
9921   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9922     .addExternalSymbol(StackProbeSymbol)
9923     .addReg(X86::EAX, RegState::Implicit)
9924     .addReg(X86::ESP, RegState::Implicit)
9925     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9926     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9927     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9928
9929   MI->eraseFromParent();   // The pseudo instruction is gone now.
9930   return BB;
9931 }
9932
9933 MachineBasicBlock *
9934 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9935                                       MachineBasicBlock *BB) const {
9936   // This is pretty easy.  We're taking the value that we received from
9937   // our load from the relocation, sticking it in either RDI (x86-64)
9938   // or EAX and doing an indirect call.  The return value will then
9939   // be in the normal return register.
9940   const X86InstrInfo *TII
9941     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9942   DebugLoc DL = MI->getDebugLoc();
9943   MachineFunction *F = BB->getParent();
9944
9945   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9946   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9947
9948   if (Subtarget->is64Bit()) {
9949     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9950                                       TII->get(X86::MOV64rm), X86::RDI)
9951     .addReg(X86::RIP)
9952     .addImm(0).addReg(0)
9953     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9954                       MI->getOperand(3).getTargetFlags())
9955     .addReg(0);
9956     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9957     addDirectMem(MIB, X86::RDI);
9958   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9959     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9960                                       TII->get(X86::MOV32rm), X86::EAX)
9961     .addReg(0)
9962     .addImm(0).addReg(0)
9963     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9964                       MI->getOperand(3).getTargetFlags())
9965     .addReg(0);
9966     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9967     addDirectMem(MIB, X86::EAX);
9968   } else {
9969     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9970                                       TII->get(X86::MOV32rm), X86::EAX)
9971     .addReg(TII->getGlobalBaseReg(F))
9972     .addImm(0).addReg(0)
9973     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9974                       MI->getOperand(3).getTargetFlags())
9975     .addReg(0);
9976     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9977     addDirectMem(MIB, X86::EAX);
9978   }
9979
9980   MI->eraseFromParent(); // The pseudo instruction is gone now.
9981   return BB;
9982 }
9983
9984 MachineBasicBlock *
9985 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9986                                                MachineBasicBlock *BB) const {
9987   switch (MI->getOpcode()) {
9988   default: assert(false && "Unexpected instr type to insert");
9989   case X86::WIN_ALLOCA:
9990     return EmitLoweredWinAlloca(MI, BB);
9991   case X86::TLSCall_32:
9992   case X86::TLSCall_64:
9993     return EmitLoweredTLSCall(MI, BB);
9994   case X86::CMOV_GR8:
9995   case X86::CMOV_FR32:
9996   case X86::CMOV_FR64:
9997   case X86::CMOV_V4F32:
9998   case X86::CMOV_V2F64:
9999   case X86::CMOV_V2I64:
10000   case X86::CMOV_GR16:
10001   case X86::CMOV_GR32:
10002   case X86::CMOV_RFP32:
10003   case X86::CMOV_RFP64:
10004   case X86::CMOV_RFP80:
10005     return EmitLoweredSelect(MI, BB);
10006
10007   case X86::FP32_TO_INT16_IN_MEM:
10008   case X86::FP32_TO_INT32_IN_MEM:
10009   case X86::FP32_TO_INT64_IN_MEM:
10010   case X86::FP64_TO_INT16_IN_MEM:
10011   case X86::FP64_TO_INT32_IN_MEM:
10012   case X86::FP64_TO_INT64_IN_MEM:
10013   case X86::FP80_TO_INT16_IN_MEM:
10014   case X86::FP80_TO_INT32_IN_MEM:
10015   case X86::FP80_TO_INT64_IN_MEM: {
10016     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10017     DebugLoc DL = MI->getDebugLoc();
10018
10019     // Change the floating point control register to use "round towards zero"
10020     // mode when truncating to an integer value.
10021     MachineFunction *F = BB->getParent();
10022     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10023     addFrameReference(BuildMI(*BB, MI, DL,
10024                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10025
10026     // Load the old value of the high byte of the control word...
10027     unsigned OldCW =
10028       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10029     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10030                       CWFrameIdx);
10031
10032     // Set the high part to be round to zero...
10033     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10034       .addImm(0xC7F);
10035
10036     // Reload the modified control word now...
10037     addFrameReference(BuildMI(*BB, MI, DL,
10038                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10039
10040     // Restore the memory image of control word to original value
10041     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10042       .addReg(OldCW);
10043
10044     // Get the X86 opcode to use.
10045     unsigned Opc;
10046     switch (MI->getOpcode()) {
10047     default: llvm_unreachable("illegal opcode!");
10048     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10049     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10050     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10051     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10052     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10053     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10054     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10055     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10056     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10057     }
10058
10059     X86AddressMode AM;
10060     MachineOperand &Op = MI->getOperand(0);
10061     if (Op.isReg()) {
10062       AM.BaseType = X86AddressMode::RegBase;
10063       AM.Base.Reg = Op.getReg();
10064     } else {
10065       AM.BaseType = X86AddressMode::FrameIndexBase;
10066       AM.Base.FrameIndex = Op.getIndex();
10067     }
10068     Op = MI->getOperand(1);
10069     if (Op.isImm())
10070       AM.Scale = Op.getImm();
10071     Op = MI->getOperand(2);
10072     if (Op.isImm())
10073       AM.IndexReg = Op.getImm();
10074     Op = MI->getOperand(3);
10075     if (Op.isGlobal()) {
10076       AM.GV = Op.getGlobal();
10077     } else {
10078       AM.Disp = Op.getImm();
10079     }
10080     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10081                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10082
10083     // Reload the original control word now.
10084     addFrameReference(BuildMI(*BB, MI, DL,
10085                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10086
10087     MI->eraseFromParent();   // The pseudo instruction is gone now.
10088     return BB;
10089   }
10090     // String/text processing lowering.
10091   case X86::PCMPISTRM128REG:
10092   case X86::VPCMPISTRM128REG:
10093     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10094   case X86::PCMPISTRM128MEM:
10095   case X86::VPCMPISTRM128MEM:
10096     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10097   case X86::PCMPESTRM128REG:
10098   case X86::VPCMPESTRM128REG:
10099     return EmitPCMP(MI, BB, 5, false /* in mem */);
10100   case X86::PCMPESTRM128MEM:
10101   case X86::VPCMPESTRM128MEM:
10102     return EmitPCMP(MI, BB, 5, true /* in mem */);
10103
10104     // Thread synchronization.
10105   case X86::MONITOR:
10106     return EmitMonitor(MI, BB);  
10107   case X86::MWAIT:
10108     return EmitMwait(MI, BB);
10109
10110     // Atomic Lowering.
10111   case X86::ATOMAND32:
10112     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10113                                                X86::AND32ri, X86::MOV32rm,
10114                                                X86::LCMPXCHG32,
10115                                                X86::NOT32r, X86::EAX,
10116                                                X86::GR32RegisterClass);
10117   case X86::ATOMOR32:
10118     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10119                                                X86::OR32ri, X86::MOV32rm,
10120                                                X86::LCMPXCHG32,
10121                                                X86::NOT32r, X86::EAX,
10122                                                X86::GR32RegisterClass);
10123   case X86::ATOMXOR32:
10124     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10125                                                X86::XOR32ri, X86::MOV32rm,
10126                                                X86::LCMPXCHG32,
10127                                                X86::NOT32r, X86::EAX,
10128                                                X86::GR32RegisterClass);
10129   case X86::ATOMNAND32:
10130     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10131                                                X86::AND32ri, X86::MOV32rm,
10132                                                X86::LCMPXCHG32,
10133                                                X86::NOT32r, X86::EAX,
10134                                                X86::GR32RegisterClass, true);
10135   case X86::ATOMMIN32:
10136     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10137   case X86::ATOMMAX32:
10138     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10139   case X86::ATOMUMIN32:
10140     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10141   case X86::ATOMUMAX32:
10142     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10143
10144   case X86::ATOMAND16:
10145     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10146                                                X86::AND16ri, X86::MOV16rm,
10147                                                X86::LCMPXCHG16,
10148                                                X86::NOT16r, X86::AX,
10149                                                X86::GR16RegisterClass);
10150   case X86::ATOMOR16:
10151     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10152                                                X86::OR16ri, X86::MOV16rm,
10153                                                X86::LCMPXCHG16,
10154                                                X86::NOT16r, X86::AX,
10155                                                X86::GR16RegisterClass);
10156   case X86::ATOMXOR16:
10157     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10158                                                X86::XOR16ri, X86::MOV16rm,
10159                                                X86::LCMPXCHG16,
10160                                                X86::NOT16r, X86::AX,
10161                                                X86::GR16RegisterClass);
10162   case X86::ATOMNAND16:
10163     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10164                                                X86::AND16ri, X86::MOV16rm,
10165                                                X86::LCMPXCHG16,
10166                                                X86::NOT16r, X86::AX,
10167                                                X86::GR16RegisterClass, true);
10168   case X86::ATOMMIN16:
10169     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10170   case X86::ATOMMAX16:
10171     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10172   case X86::ATOMUMIN16:
10173     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10174   case X86::ATOMUMAX16:
10175     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10176
10177   case X86::ATOMAND8:
10178     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10179                                                X86::AND8ri, X86::MOV8rm,
10180                                                X86::LCMPXCHG8,
10181                                                X86::NOT8r, X86::AL,
10182                                                X86::GR8RegisterClass);
10183   case X86::ATOMOR8:
10184     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10185                                                X86::OR8ri, X86::MOV8rm,
10186                                                X86::LCMPXCHG8,
10187                                                X86::NOT8r, X86::AL,
10188                                                X86::GR8RegisterClass);
10189   case X86::ATOMXOR8:
10190     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10191                                                X86::XOR8ri, X86::MOV8rm,
10192                                                X86::LCMPXCHG8,
10193                                                X86::NOT8r, X86::AL,
10194                                                X86::GR8RegisterClass);
10195   case X86::ATOMNAND8:
10196     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10197                                                X86::AND8ri, X86::MOV8rm,
10198                                                X86::LCMPXCHG8,
10199                                                X86::NOT8r, X86::AL,
10200                                                X86::GR8RegisterClass, true);
10201   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10202   // This group is for 64-bit host.
10203   case X86::ATOMAND64:
10204     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10205                                                X86::AND64ri32, X86::MOV64rm,
10206                                                X86::LCMPXCHG64,
10207                                                X86::NOT64r, X86::RAX,
10208                                                X86::GR64RegisterClass);
10209   case X86::ATOMOR64:
10210     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10211                                                X86::OR64ri32, X86::MOV64rm,
10212                                                X86::LCMPXCHG64,
10213                                                X86::NOT64r, X86::RAX,
10214                                                X86::GR64RegisterClass);
10215   case X86::ATOMXOR64:
10216     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10217                                                X86::XOR64ri32, X86::MOV64rm,
10218                                                X86::LCMPXCHG64,
10219                                                X86::NOT64r, X86::RAX,
10220                                                X86::GR64RegisterClass);
10221   case X86::ATOMNAND64:
10222     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10223                                                X86::AND64ri32, X86::MOV64rm,
10224                                                X86::LCMPXCHG64,
10225                                                X86::NOT64r, X86::RAX,
10226                                                X86::GR64RegisterClass, true);
10227   case X86::ATOMMIN64:
10228     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10229   case X86::ATOMMAX64:
10230     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10231   case X86::ATOMUMIN64:
10232     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10233   case X86::ATOMUMAX64:
10234     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10235
10236   // This group does 64-bit operations on a 32-bit host.
10237   case X86::ATOMAND6432:
10238     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10239                                                X86::AND32rr, X86::AND32rr,
10240                                                X86::AND32ri, X86::AND32ri,
10241                                                false);
10242   case X86::ATOMOR6432:
10243     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10244                                                X86::OR32rr, X86::OR32rr,
10245                                                X86::OR32ri, X86::OR32ri,
10246                                                false);
10247   case X86::ATOMXOR6432:
10248     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10249                                                X86::XOR32rr, X86::XOR32rr,
10250                                                X86::XOR32ri, X86::XOR32ri,
10251                                                false);
10252   case X86::ATOMNAND6432:
10253     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10254                                                X86::AND32rr, X86::AND32rr,
10255                                                X86::AND32ri, X86::AND32ri,
10256                                                true);
10257   case X86::ATOMADD6432:
10258     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10259                                                X86::ADD32rr, X86::ADC32rr,
10260                                                X86::ADD32ri, X86::ADC32ri,
10261                                                false);
10262   case X86::ATOMSUB6432:
10263     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10264                                                X86::SUB32rr, X86::SBB32rr,
10265                                                X86::SUB32ri, X86::SBB32ri,
10266                                                false);
10267   case X86::ATOMSWAP6432:
10268     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10269                                                X86::MOV32rr, X86::MOV32rr,
10270                                                X86::MOV32ri, X86::MOV32ri,
10271                                                false);
10272   case X86::VASTART_SAVE_XMM_REGS:
10273     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10274
10275   case X86::VAARG_64:
10276     return EmitVAARG64WithCustomInserter(MI, BB);
10277   }
10278 }
10279
10280 //===----------------------------------------------------------------------===//
10281 //                           X86 Optimization Hooks
10282 //===----------------------------------------------------------------------===//
10283
10284 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10285                                                        const APInt &Mask,
10286                                                        APInt &KnownZero,
10287                                                        APInt &KnownOne,
10288                                                        const SelectionDAG &DAG,
10289                                                        unsigned Depth) const {
10290   unsigned Opc = Op.getOpcode();
10291   assert((Opc >= ISD::BUILTIN_OP_END ||
10292           Opc == ISD::INTRINSIC_WO_CHAIN ||
10293           Opc == ISD::INTRINSIC_W_CHAIN ||
10294           Opc == ISD::INTRINSIC_VOID) &&
10295          "Should use MaskedValueIsZero if you don't know whether Op"
10296          " is a target node!");
10297
10298   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10299   switch (Opc) {
10300   default: break;
10301   case X86ISD::ADD:
10302   case X86ISD::SUB:
10303   case X86ISD::SMUL:
10304   case X86ISD::UMUL:
10305   case X86ISD::INC:
10306   case X86ISD::DEC:
10307   case X86ISD::OR:
10308   case X86ISD::XOR:
10309   case X86ISD::AND:
10310     // These nodes' second result is a boolean.
10311     if (Op.getResNo() == 0)
10312       break;
10313     // Fallthrough
10314   case X86ISD::SETCC:
10315     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10316                                        Mask.getBitWidth() - 1);
10317     break;
10318   }
10319 }
10320
10321 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10322                                                          unsigned Depth) const {
10323   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10324   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10325     return Op.getValueType().getScalarType().getSizeInBits();
10326
10327   // Fallback case.
10328   return 1;
10329 }
10330
10331 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10332 /// node is a GlobalAddress + offset.
10333 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10334                                        const GlobalValue* &GA,
10335                                        int64_t &Offset) const {
10336   if (N->getOpcode() == X86ISD::Wrapper) {
10337     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10338       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10339       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10340       return true;
10341     }
10342   }
10343   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10344 }
10345
10346 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10347 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10348 /// if the load addresses are consecutive, non-overlapping, and in the right
10349 /// order.
10350 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10351                                      const TargetLowering &TLI) {
10352   DebugLoc dl = N->getDebugLoc();
10353   EVT VT = N->getValueType(0);
10354
10355   if (VT.getSizeInBits() != 128)
10356     return SDValue();
10357
10358   SmallVector<SDValue, 16> Elts;
10359   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10360     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10361
10362   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10363 }
10364
10365 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10366 /// generation and convert it from being a bunch of shuffles and extracts
10367 /// to a simple store and scalar loads to extract the elements.
10368 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10369                                                 const TargetLowering &TLI) {
10370   SDValue InputVector = N->getOperand(0);
10371
10372   // Only operate on vectors of 4 elements, where the alternative shuffling
10373   // gets to be more expensive.
10374   if (InputVector.getValueType() != MVT::v4i32)
10375     return SDValue();
10376
10377   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10378   // single use which is a sign-extend or zero-extend, and all elements are
10379   // used.
10380   SmallVector<SDNode *, 4> Uses;
10381   unsigned ExtractedElements = 0;
10382   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10383        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10384     if (UI.getUse().getResNo() != InputVector.getResNo())
10385       return SDValue();
10386
10387     SDNode *Extract = *UI;
10388     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10389       return SDValue();
10390
10391     if (Extract->getValueType(0) != MVT::i32)
10392       return SDValue();
10393     if (!Extract->hasOneUse())
10394       return SDValue();
10395     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10396         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10397       return SDValue();
10398     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10399       return SDValue();
10400
10401     // Record which element was extracted.
10402     ExtractedElements |=
10403       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10404
10405     Uses.push_back(Extract);
10406   }
10407
10408   // If not all the elements were used, this may not be worthwhile.
10409   if (ExtractedElements != 15)
10410     return SDValue();
10411
10412   // Ok, we've now decided to do the transformation.
10413   DebugLoc dl = InputVector.getDebugLoc();
10414
10415   // Store the value to a temporary stack slot.
10416   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10417   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10418                             MachinePointerInfo(), false, false, 0);
10419
10420   // Replace each use (extract) with a load of the appropriate element.
10421   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10422        UE = Uses.end(); UI != UE; ++UI) {
10423     SDNode *Extract = *UI;
10424
10425     // Compute the element's address.
10426     SDValue Idx = Extract->getOperand(1);
10427     unsigned EltSize =
10428         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10429     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10430     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10431
10432     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10433                                      StackPtr, OffsetVal);
10434
10435     // Load the scalar.
10436     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10437                                      ScalarAddr, MachinePointerInfo(),
10438                                      false, false, 0);
10439
10440     // Replace the exact with the load.
10441     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10442   }
10443
10444   // The replacement was made in place; don't return anything.
10445   return SDValue();
10446 }
10447
10448 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10449 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10450                                     const X86Subtarget *Subtarget) {
10451   DebugLoc DL = N->getDebugLoc();
10452   SDValue Cond = N->getOperand(0);
10453   // Get the LHS/RHS of the select.
10454   SDValue LHS = N->getOperand(1);
10455   SDValue RHS = N->getOperand(2);
10456
10457   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10458   // instructions match the semantics of the common C idiom x<y?x:y but not
10459   // x<=y?x:y, because of how they handle negative zero (which can be
10460   // ignored in unsafe-math mode).
10461   if (Subtarget->hasSSE2() &&
10462       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10463       Cond.getOpcode() == ISD::SETCC) {
10464     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10465
10466     unsigned Opcode = 0;
10467     // Check for x CC y ? x : y.
10468     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10469         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10470       switch (CC) {
10471       default: break;
10472       case ISD::SETULT:
10473         // Converting this to a min would handle NaNs incorrectly, and swapping
10474         // the operands would cause it to handle comparisons between positive
10475         // and negative zero incorrectly.
10476         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10477           if (!UnsafeFPMath &&
10478               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10479             break;
10480           std::swap(LHS, RHS);
10481         }
10482         Opcode = X86ISD::FMIN;
10483         break;
10484       case ISD::SETOLE:
10485         // Converting this to a min would handle comparisons between positive
10486         // and negative zero incorrectly.
10487         if (!UnsafeFPMath &&
10488             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10489           break;
10490         Opcode = X86ISD::FMIN;
10491         break;
10492       case ISD::SETULE:
10493         // Converting this to a min would handle both negative zeros and NaNs
10494         // incorrectly, but we can swap the operands to fix both.
10495         std::swap(LHS, RHS);
10496       case ISD::SETOLT:
10497       case ISD::SETLT:
10498       case ISD::SETLE:
10499         Opcode = X86ISD::FMIN;
10500         break;
10501
10502       case ISD::SETOGE:
10503         // Converting this to a max would handle comparisons between positive
10504         // and negative zero incorrectly.
10505         if (!UnsafeFPMath &&
10506             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10507           break;
10508         Opcode = X86ISD::FMAX;
10509         break;
10510       case ISD::SETUGT:
10511         // Converting this to a max would handle NaNs incorrectly, and swapping
10512         // the operands would cause it to handle comparisons between positive
10513         // and negative zero incorrectly.
10514         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10515           if (!UnsafeFPMath &&
10516               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10517             break;
10518           std::swap(LHS, RHS);
10519         }
10520         Opcode = X86ISD::FMAX;
10521         break;
10522       case ISD::SETUGE:
10523         // Converting this to a max would handle both negative zeros and NaNs
10524         // incorrectly, but we can swap the operands to fix both.
10525         std::swap(LHS, RHS);
10526       case ISD::SETOGT:
10527       case ISD::SETGT:
10528       case ISD::SETGE:
10529         Opcode = X86ISD::FMAX;
10530         break;
10531       }
10532     // Check for x CC y ? y : x -- a min/max with reversed arms.
10533     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10534                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10535       switch (CC) {
10536       default: break;
10537       case ISD::SETOGE:
10538         // Converting this to a min would handle comparisons between positive
10539         // and negative zero incorrectly, and swapping the operands would
10540         // cause it to handle NaNs incorrectly.
10541         if (!UnsafeFPMath &&
10542             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10543           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10544             break;
10545           std::swap(LHS, RHS);
10546         }
10547         Opcode = X86ISD::FMIN;
10548         break;
10549       case ISD::SETUGT:
10550         // Converting this to a min would handle NaNs incorrectly.
10551         if (!UnsafeFPMath &&
10552             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10553           break;
10554         Opcode = X86ISD::FMIN;
10555         break;
10556       case ISD::SETUGE:
10557         // Converting this to a min would handle both negative zeros and NaNs
10558         // incorrectly, but we can swap the operands to fix both.
10559         std::swap(LHS, RHS);
10560       case ISD::SETOGT:
10561       case ISD::SETGT:
10562       case ISD::SETGE:
10563         Opcode = X86ISD::FMIN;
10564         break;
10565
10566       case ISD::SETULT:
10567         // Converting this to a max would handle NaNs incorrectly.
10568         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10569           break;
10570         Opcode = X86ISD::FMAX;
10571         break;
10572       case ISD::SETOLE:
10573         // Converting this to a max would handle comparisons between positive
10574         // and negative zero incorrectly, and swapping the operands would
10575         // cause it to handle NaNs incorrectly.
10576         if (!UnsafeFPMath &&
10577             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10578           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10579             break;
10580           std::swap(LHS, RHS);
10581         }
10582         Opcode = X86ISD::FMAX;
10583         break;
10584       case ISD::SETULE:
10585         // Converting this to a max would handle both negative zeros and NaNs
10586         // incorrectly, but we can swap the operands to fix both.
10587         std::swap(LHS, RHS);
10588       case ISD::SETOLT:
10589       case ISD::SETLT:
10590       case ISD::SETLE:
10591         Opcode = X86ISD::FMAX;
10592         break;
10593       }
10594     }
10595
10596     if (Opcode)
10597       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10598   }
10599
10600   // If this is a select between two integer constants, try to do some
10601   // optimizations.
10602   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10603     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10604       // Don't do this for crazy integer types.
10605       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10606         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10607         // so that TrueC (the true value) is larger than FalseC.
10608         bool NeedsCondInvert = false;
10609
10610         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10611             // Efficiently invertible.
10612             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10613              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10614               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10615           NeedsCondInvert = true;
10616           std::swap(TrueC, FalseC);
10617         }
10618
10619         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10620         if (FalseC->getAPIntValue() == 0 &&
10621             TrueC->getAPIntValue().isPowerOf2()) {
10622           if (NeedsCondInvert) // Invert the condition if needed.
10623             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10624                                DAG.getConstant(1, Cond.getValueType()));
10625
10626           // Zero extend the condition if needed.
10627           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10628
10629           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10630           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10631                              DAG.getConstant(ShAmt, MVT::i8));
10632         }
10633
10634         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10635         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10636           if (NeedsCondInvert) // Invert the condition if needed.
10637             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10638                                DAG.getConstant(1, Cond.getValueType()));
10639
10640           // Zero extend the condition if needed.
10641           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10642                              FalseC->getValueType(0), Cond);
10643           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10644                              SDValue(FalseC, 0));
10645         }
10646
10647         // Optimize cases that will turn into an LEA instruction.  This requires
10648         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10649         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10650           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10651           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10652
10653           bool isFastMultiplier = false;
10654           if (Diff < 10) {
10655             switch ((unsigned char)Diff) {
10656               default: break;
10657               case 1:  // result = add base, cond
10658               case 2:  // result = lea base(    , cond*2)
10659               case 3:  // result = lea base(cond, cond*2)
10660               case 4:  // result = lea base(    , cond*4)
10661               case 5:  // result = lea base(cond, cond*4)
10662               case 8:  // result = lea base(    , cond*8)
10663               case 9:  // result = lea base(cond, cond*8)
10664                 isFastMultiplier = true;
10665                 break;
10666             }
10667           }
10668
10669           if (isFastMultiplier) {
10670             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10671             if (NeedsCondInvert) // Invert the condition if needed.
10672               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10673                                  DAG.getConstant(1, Cond.getValueType()));
10674
10675             // Zero extend the condition if needed.
10676             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10677                                Cond);
10678             // Scale the condition by the difference.
10679             if (Diff != 1)
10680               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10681                                  DAG.getConstant(Diff, Cond.getValueType()));
10682
10683             // Add the base if non-zero.
10684             if (FalseC->getAPIntValue() != 0)
10685               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10686                                  SDValue(FalseC, 0));
10687             return Cond;
10688           }
10689         }
10690       }
10691   }
10692
10693   return SDValue();
10694 }
10695
10696 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10697 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10698                                   TargetLowering::DAGCombinerInfo &DCI) {
10699   DebugLoc DL = N->getDebugLoc();
10700
10701   // If the flag operand isn't dead, don't touch this CMOV.
10702   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10703     return SDValue();
10704
10705   // If this is a select between two integer constants, try to do some
10706   // optimizations.  Note that the operands are ordered the opposite of SELECT
10707   // operands.
10708   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10709     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10710       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10711       // larger than FalseC (the false value).
10712       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10713
10714       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10715         CC = X86::GetOppositeBranchCondition(CC);
10716         std::swap(TrueC, FalseC);
10717       }
10718
10719       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10720       // This is efficient for any integer data type (including i8/i16) and
10721       // shift amount.
10722       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10723         SDValue Cond = N->getOperand(3);
10724         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10725                            DAG.getConstant(CC, MVT::i8), Cond);
10726
10727         // Zero extend the condition if needed.
10728         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10729
10730         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10731         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10732                            DAG.getConstant(ShAmt, MVT::i8));
10733         if (N->getNumValues() == 2)  // Dead flag value?
10734           return DCI.CombineTo(N, Cond, SDValue());
10735         return Cond;
10736       }
10737
10738       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10739       // for any integer data type, including i8/i16.
10740       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10741         SDValue Cond = N->getOperand(3);
10742         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10743                            DAG.getConstant(CC, MVT::i8), Cond);
10744
10745         // Zero extend the condition if needed.
10746         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10747                            FalseC->getValueType(0), Cond);
10748         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10749                            SDValue(FalseC, 0));
10750
10751         if (N->getNumValues() == 2)  // Dead flag value?
10752           return DCI.CombineTo(N, Cond, SDValue());
10753         return Cond;
10754       }
10755
10756       // Optimize cases that will turn into an LEA instruction.  This requires
10757       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10758       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10759         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10760         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10761
10762         bool isFastMultiplier = false;
10763         if (Diff < 10) {
10764           switch ((unsigned char)Diff) {
10765           default: break;
10766           case 1:  // result = add base, cond
10767           case 2:  // result = lea base(    , cond*2)
10768           case 3:  // result = lea base(cond, cond*2)
10769           case 4:  // result = lea base(    , cond*4)
10770           case 5:  // result = lea base(cond, cond*4)
10771           case 8:  // result = lea base(    , cond*8)
10772           case 9:  // result = lea base(cond, cond*8)
10773             isFastMultiplier = true;
10774             break;
10775           }
10776         }
10777
10778         if (isFastMultiplier) {
10779           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10780           SDValue Cond = N->getOperand(3);
10781           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10782                              DAG.getConstant(CC, MVT::i8), Cond);
10783           // Zero extend the condition if needed.
10784           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10785                              Cond);
10786           // Scale the condition by the difference.
10787           if (Diff != 1)
10788             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10789                                DAG.getConstant(Diff, Cond.getValueType()));
10790
10791           // Add the base if non-zero.
10792           if (FalseC->getAPIntValue() != 0)
10793             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10794                                SDValue(FalseC, 0));
10795           if (N->getNumValues() == 2)  // Dead flag value?
10796             return DCI.CombineTo(N, Cond, SDValue());
10797           return Cond;
10798         }
10799       }
10800     }
10801   }
10802   return SDValue();
10803 }
10804
10805
10806 /// PerformMulCombine - Optimize a single multiply with constant into two
10807 /// in order to implement it with two cheaper instructions, e.g.
10808 /// LEA + SHL, LEA + LEA.
10809 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10810                                  TargetLowering::DAGCombinerInfo &DCI) {
10811   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10812     return SDValue();
10813
10814   EVT VT = N->getValueType(0);
10815   if (VT != MVT::i64)
10816     return SDValue();
10817
10818   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10819   if (!C)
10820     return SDValue();
10821   uint64_t MulAmt = C->getZExtValue();
10822   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10823     return SDValue();
10824
10825   uint64_t MulAmt1 = 0;
10826   uint64_t MulAmt2 = 0;
10827   if ((MulAmt % 9) == 0) {
10828     MulAmt1 = 9;
10829     MulAmt2 = MulAmt / 9;
10830   } else if ((MulAmt % 5) == 0) {
10831     MulAmt1 = 5;
10832     MulAmt2 = MulAmt / 5;
10833   } else if ((MulAmt % 3) == 0) {
10834     MulAmt1 = 3;
10835     MulAmt2 = MulAmt / 3;
10836   }
10837   if (MulAmt2 &&
10838       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10839     DebugLoc DL = N->getDebugLoc();
10840
10841     if (isPowerOf2_64(MulAmt2) &&
10842         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10843       // If second multiplifer is pow2, issue it first. We want the multiply by
10844       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10845       // is an add.
10846       std::swap(MulAmt1, MulAmt2);
10847
10848     SDValue NewMul;
10849     if (isPowerOf2_64(MulAmt1))
10850       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10851                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10852     else
10853       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10854                            DAG.getConstant(MulAmt1, VT));
10855
10856     if (isPowerOf2_64(MulAmt2))
10857       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10858                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10859     else
10860       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10861                            DAG.getConstant(MulAmt2, VT));
10862
10863     // Do not add new nodes to DAG combiner worklist.
10864     DCI.CombineTo(N, NewMul, false);
10865   }
10866   return SDValue();
10867 }
10868
10869 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10870   SDValue N0 = N->getOperand(0);
10871   SDValue N1 = N->getOperand(1);
10872   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10873   EVT VT = N0.getValueType();
10874
10875   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10876   // since the result of setcc_c is all zero's or all ones.
10877   if (N1C && N0.getOpcode() == ISD::AND &&
10878       N0.getOperand(1).getOpcode() == ISD::Constant) {
10879     SDValue N00 = N0.getOperand(0);
10880     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10881         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10882           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10883          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10884       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10885       APInt ShAmt = N1C->getAPIntValue();
10886       Mask = Mask.shl(ShAmt);
10887       if (Mask != 0)
10888         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10889                            N00, DAG.getConstant(Mask, VT));
10890     }
10891   }
10892
10893   return SDValue();
10894 }
10895
10896 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10897 ///                       when possible.
10898 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10899                                    const X86Subtarget *Subtarget) {
10900   EVT VT = N->getValueType(0);
10901   if (!VT.isVector() && VT.isInteger() &&
10902       N->getOpcode() == ISD::SHL)
10903     return PerformSHLCombine(N, DAG);
10904
10905   // On X86 with SSE2 support, we can transform this to a vector shift if
10906   // all elements are shifted by the same amount.  We can't do this in legalize
10907   // because the a constant vector is typically transformed to a constant pool
10908   // so we have no knowledge of the shift amount.
10909   if (!Subtarget->hasSSE2())
10910     return SDValue();
10911
10912   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10913     return SDValue();
10914
10915   SDValue ShAmtOp = N->getOperand(1);
10916   EVT EltVT = VT.getVectorElementType();
10917   DebugLoc DL = N->getDebugLoc();
10918   SDValue BaseShAmt = SDValue();
10919   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10920     unsigned NumElts = VT.getVectorNumElements();
10921     unsigned i = 0;
10922     for (; i != NumElts; ++i) {
10923       SDValue Arg = ShAmtOp.getOperand(i);
10924       if (Arg.getOpcode() == ISD::UNDEF) continue;
10925       BaseShAmt = Arg;
10926       break;
10927     }
10928     for (; i != NumElts; ++i) {
10929       SDValue Arg = ShAmtOp.getOperand(i);
10930       if (Arg.getOpcode() == ISD::UNDEF) continue;
10931       if (Arg != BaseShAmt) {
10932         return SDValue();
10933       }
10934     }
10935   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10936              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10937     SDValue InVec = ShAmtOp.getOperand(0);
10938     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10939       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10940       unsigned i = 0;
10941       for (; i != NumElts; ++i) {
10942         SDValue Arg = InVec.getOperand(i);
10943         if (Arg.getOpcode() == ISD::UNDEF) continue;
10944         BaseShAmt = Arg;
10945         break;
10946       }
10947     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10948        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10949          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10950          if (C->getZExtValue() == SplatIdx)
10951            BaseShAmt = InVec.getOperand(1);
10952        }
10953     }
10954     if (BaseShAmt.getNode() == 0)
10955       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10956                               DAG.getIntPtrConstant(0));
10957   } else
10958     return SDValue();
10959
10960   // The shift amount is an i32.
10961   if (EltVT.bitsGT(MVT::i32))
10962     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10963   else if (EltVT.bitsLT(MVT::i32))
10964     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10965
10966   // The shift amount is identical so we can do a vector shift.
10967   SDValue  ValOp = N->getOperand(0);
10968   switch (N->getOpcode()) {
10969   default:
10970     llvm_unreachable("Unknown shift opcode!");
10971     break;
10972   case ISD::SHL:
10973     if (VT == MVT::v2i64)
10974       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10975                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10976                          ValOp, BaseShAmt);
10977     if (VT == MVT::v4i32)
10978       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10979                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10980                          ValOp, BaseShAmt);
10981     if (VT == MVT::v8i16)
10982       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10983                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10984                          ValOp, BaseShAmt);
10985     break;
10986   case ISD::SRA:
10987     if (VT == MVT::v4i32)
10988       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10989                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10990                          ValOp, BaseShAmt);
10991     if (VT == MVT::v8i16)
10992       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10993                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10994                          ValOp, BaseShAmt);
10995     break;
10996   case ISD::SRL:
10997     if (VT == MVT::v2i64)
10998       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10999                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11000                          ValOp, BaseShAmt);
11001     if (VT == MVT::v4i32)
11002       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11003                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11004                          ValOp, BaseShAmt);
11005     if (VT ==  MVT::v8i16)
11006       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11007                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11008                          ValOp, BaseShAmt);
11009     break;
11010   }
11011   return SDValue();
11012 }
11013
11014 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11015                                 TargetLowering::DAGCombinerInfo &DCI,
11016                                 const X86Subtarget *Subtarget) {
11017   if (DCI.isBeforeLegalizeOps())
11018     return SDValue();
11019
11020   EVT VT = N->getValueType(0);
11021   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
11022     return SDValue();
11023
11024   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11025   SDValue N0 = N->getOperand(0);
11026   SDValue N1 = N->getOperand(1);
11027   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11028     std::swap(N0, N1);
11029   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11030     return SDValue();
11031   if (!N0.hasOneUse() || !N1.hasOneUse())
11032     return SDValue();
11033
11034   SDValue ShAmt0 = N0.getOperand(1);
11035   if (ShAmt0.getValueType() != MVT::i8)
11036     return SDValue();
11037   SDValue ShAmt1 = N1.getOperand(1);
11038   if (ShAmt1.getValueType() != MVT::i8)
11039     return SDValue();
11040   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11041     ShAmt0 = ShAmt0.getOperand(0);
11042   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11043     ShAmt1 = ShAmt1.getOperand(0);
11044
11045   DebugLoc DL = N->getDebugLoc();
11046   unsigned Opc = X86ISD::SHLD;
11047   SDValue Op0 = N0.getOperand(0);
11048   SDValue Op1 = N1.getOperand(0);
11049   if (ShAmt0.getOpcode() == ISD::SUB) {
11050     Opc = X86ISD::SHRD;
11051     std::swap(Op0, Op1);
11052     std::swap(ShAmt0, ShAmt1);
11053   }
11054
11055   unsigned Bits = VT.getSizeInBits();
11056   if (ShAmt1.getOpcode() == ISD::SUB) {
11057     SDValue Sum = ShAmt1.getOperand(0);
11058     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11059       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11060       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11061         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11062       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11063         return DAG.getNode(Opc, DL, VT,
11064                            Op0, Op1,
11065                            DAG.getNode(ISD::TRUNCATE, DL,
11066                                        MVT::i8, ShAmt0));
11067     }
11068   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11069     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11070     if (ShAmt0C &&
11071         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11072       return DAG.getNode(Opc, DL, VT,
11073                          N0.getOperand(0), N1.getOperand(0),
11074                          DAG.getNode(ISD::TRUNCATE, DL,
11075                                        MVT::i8, ShAmt0));
11076   }
11077
11078   return SDValue();
11079 }
11080
11081 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11082 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11083                                    const X86Subtarget *Subtarget) {
11084   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11085   // the FP state in cases where an emms may be missing.
11086   // A preferable solution to the general problem is to figure out the right
11087   // places to insert EMMS.  This qualifies as a quick hack.
11088
11089   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11090   StoreSDNode *St = cast<StoreSDNode>(N);
11091   EVT VT = St->getValue().getValueType();
11092   if (VT.getSizeInBits() != 64)
11093     return SDValue();
11094
11095   const Function *F = DAG.getMachineFunction().getFunction();
11096   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11097   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11098     && Subtarget->hasSSE2();
11099   if ((VT.isVector() ||
11100        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11101       isa<LoadSDNode>(St->getValue()) &&
11102       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11103       St->getChain().hasOneUse() && !St->isVolatile()) {
11104     SDNode* LdVal = St->getValue().getNode();
11105     LoadSDNode *Ld = 0;
11106     int TokenFactorIndex = -1;
11107     SmallVector<SDValue, 8> Ops;
11108     SDNode* ChainVal = St->getChain().getNode();
11109     // Must be a store of a load.  We currently handle two cases:  the load
11110     // is a direct child, and it's under an intervening TokenFactor.  It is
11111     // possible to dig deeper under nested TokenFactors.
11112     if (ChainVal == LdVal)
11113       Ld = cast<LoadSDNode>(St->getChain());
11114     else if (St->getValue().hasOneUse() &&
11115              ChainVal->getOpcode() == ISD::TokenFactor) {
11116       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11117         if (ChainVal->getOperand(i).getNode() == LdVal) {
11118           TokenFactorIndex = i;
11119           Ld = cast<LoadSDNode>(St->getValue());
11120         } else
11121           Ops.push_back(ChainVal->getOperand(i));
11122       }
11123     }
11124
11125     if (!Ld || !ISD::isNormalLoad(Ld))
11126       return SDValue();
11127
11128     // If this is not the MMX case, i.e. we are just turning i64 load/store
11129     // into f64 load/store, avoid the transformation if there are multiple
11130     // uses of the loaded value.
11131     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11132       return SDValue();
11133
11134     DebugLoc LdDL = Ld->getDebugLoc();
11135     DebugLoc StDL = N->getDebugLoc();
11136     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11137     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11138     // pair instead.
11139     if (Subtarget->is64Bit() || F64IsLegal) {
11140       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11141       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11142                                   Ld->getPointerInfo(), Ld->isVolatile(),
11143                                   Ld->isNonTemporal(), Ld->getAlignment());
11144       SDValue NewChain = NewLd.getValue(1);
11145       if (TokenFactorIndex != -1) {
11146         Ops.push_back(NewChain);
11147         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11148                                Ops.size());
11149       }
11150       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11151                           St->getPointerInfo(),
11152                           St->isVolatile(), St->isNonTemporal(),
11153                           St->getAlignment());
11154     }
11155
11156     // Otherwise, lower to two pairs of 32-bit loads / stores.
11157     SDValue LoAddr = Ld->getBasePtr();
11158     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11159                                  DAG.getConstant(4, MVT::i32));
11160
11161     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11162                                Ld->getPointerInfo(),
11163                                Ld->isVolatile(), Ld->isNonTemporal(),
11164                                Ld->getAlignment());
11165     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11166                                Ld->getPointerInfo().getWithOffset(4),
11167                                Ld->isVolatile(), Ld->isNonTemporal(),
11168                                MinAlign(Ld->getAlignment(), 4));
11169
11170     SDValue NewChain = LoLd.getValue(1);
11171     if (TokenFactorIndex != -1) {
11172       Ops.push_back(LoLd);
11173       Ops.push_back(HiLd);
11174       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11175                              Ops.size());
11176     }
11177
11178     LoAddr = St->getBasePtr();
11179     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11180                          DAG.getConstant(4, MVT::i32));
11181
11182     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11183                                 St->getPointerInfo(),
11184                                 St->isVolatile(), St->isNonTemporal(),
11185                                 St->getAlignment());
11186     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11187                                 St->getPointerInfo().getWithOffset(4),
11188                                 St->isVolatile(),
11189                                 St->isNonTemporal(),
11190                                 MinAlign(St->getAlignment(), 4));
11191     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11192   }
11193   return SDValue();
11194 }
11195
11196 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11197 /// X86ISD::FXOR nodes.
11198 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11199   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11200   // F[X]OR(0.0, x) -> x
11201   // F[X]OR(x, 0.0) -> x
11202   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11203     if (C->getValueAPF().isPosZero())
11204       return N->getOperand(1);
11205   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11206     if (C->getValueAPF().isPosZero())
11207       return N->getOperand(0);
11208   return SDValue();
11209 }
11210
11211 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11212 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11213   // FAND(0.0, x) -> 0.0
11214   // FAND(x, 0.0) -> 0.0
11215   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11216     if (C->getValueAPF().isPosZero())
11217       return N->getOperand(0);
11218   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11219     if (C->getValueAPF().isPosZero())
11220       return N->getOperand(1);
11221   return SDValue();
11222 }
11223
11224 static SDValue PerformBTCombine(SDNode *N,
11225                                 SelectionDAG &DAG,
11226                                 TargetLowering::DAGCombinerInfo &DCI) {
11227   // BT ignores high bits in the bit index operand.
11228   SDValue Op1 = N->getOperand(1);
11229   if (Op1.hasOneUse()) {
11230     unsigned BitWidth = Op1.getValueSizeInBits();
11231     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11232     APInt KnownZero, KnownOne;
11233     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11234                                           !DCI.isBeforeLegalizeOps());
11235     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11236     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11237         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11238       DCI.CommitTargetLoweringOpt(TLO);
11239   }
11240   return SDValue();
11241 }
11242
11243 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11244   SDValue Op = N->getOperand(0);
11245   if (Op.getOpcode() == ISD::BITCAST)
11246     Op = Op.getOperand(0);
11247   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11248   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11249       VT.getVectorElementType().getSizeInBits() ==
11250       OpVT.getVectorElementType().getSizeInBits()) {
11251     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11252   }
11253   return SDValue();
11254 }
11255
11256 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11257   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11258   //           (and (i32 x86isd::setcc_carry), 1)
11259   // This eliminates the zext. This transformation is necessary because
11260   // ISD::SETCC is always legalized to i8.
11261   DebugLoc dl = N->getDebugLoc();
11262   SDValue N0 = N->getOperand(0);
11263   EVT VT = N->getValueType(0);
11264   if (N0.getOpcode() == ISD::AND &&
11265       N0.hasOneUse() &&
11266       N0.getOperand(0).hasOneUse()) {
11267     SDValue N00 = N0.getOperand(0);
11268     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11269       return SDValue();
11270     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11271     if (!C || C->getZExtValue() != 1)
11272       return SDValue();
11273     return DAG.getNode(ISD::AND, dl, VT,
11274                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11275                                    N00.getOperand(0), N00.getOperand(1)),
11276                        DAG.getConstant(1, VT));
11277   }
11278
11279   return SDValue();
11280 }
11281
11282 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11283                                              DAGCombinerInfo &DCI) const {
11284   SelectionDAG &DAG = DCI.DAG;
11285   switch (N->getOpcode()) {
11286   default: break;
11287   case ISD::EXTRACT_VECTOR_ELT:
11288                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11289   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11290   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11291   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11292   case ISD::SHL:
11293   case ISD::SRA:
11294   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11295   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11296   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11297   case X86ISD::FXOR:
11298   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11299   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11300   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11301   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11302   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11303   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11304   case X86ISD::SHUFPD:
11305   case X86ISD::PALIGN:
11306   case X86ISD::PUNPCKHBW:
11307   case X86ISD::PUNPCKHWD:
11308   case X86ISD::PUNPCKHDQ:
11309   case X86ISD::PUNPCKHQDQ:
11310   case X86ISD::UNPCKHPS:
11311   case X86ISD::UNPCKHPD:
11312   case X86ISD::PUNPCKLBW:
11313   case X86ISD::PUNPCKLWD:
11314   case X86ISD::PUNPCKLDQ:
11315   case X86ISD::PUNPCKLQDQ:
11316   case X86ISD::UNPCKLPS:
11317   case X86ISD::UNPCKLPD:
11318   case X86ISD::MOVHLPS:
11319   case X86ISD::MOVLHPS:
11320   case X86ISD::PSHUFD:
11321   case X86ISD::PSHUFHW:
11322   case X86ISD::PSHUFLW:
11323   case X86ISD::MOVSS:
11324   case X86ISD::MOVSD:
11325   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11326   }
11327
11328   return SDValue();
11329 }
11330
11331 /// isTypeDesirableForOp - Return true if the target has native support for
11332 /// the specified value type and it is 'desirable' to use the type for the
11333 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11334 /// instruction encodings are longer and some i16 instructions are slow.
11335 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11336   if (!isTypeLegal(VT))
11337     return false;
11338   if (VT != MVT::i16)
11339     return true;
11340
11341   switch (Opc) {
11342   default:
11343     return true;
11344   case ISD::LOAD:
11345   case ISD::SIGN_EXTEND:
11346   case ISD::ZERO_EXTEND:
11347   case ISD::ANY_EXTEND:
11348   case ISD::SHL:
11349   case ISD::SRL:
11350   case ISD::SUB:
11351   case ISD::ADD:
11352   case ISD::MUL:
11353   case ISD::AND:
11354   case ISD::OR:
11355   case ISD::XOR:
11356     return false;
11357   }
11358 }
11359
11360 /// IsDesirableToPromoteOp - This method query the target whether it is
11361 /// beneficial for dag combiner to promote the specified node. If true, it
11362 /// should return the desired promotion type by reference.
11363 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11364   EVT VT = Op.getValueType();
11365   if (VT != MVT::i16)
11366     return false;
11367
11368   bool Promote = false;
11369   bool Commute = false;
11370   switch (Op.getOpcode()) {
11371   default: break;
11372   case ISD::LOAD: {
11373     LoadSDNode *LD = cast<LoadSDNode>(Op);
11374     // If the non-extending load has a single use and it's not live out, then it
11375     // might be folded.
11376     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11377                                                      Op.hasOneUse()*/) {
11378       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11379              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11380         // The only case where we'd want to promote LOAD (rather then it being
11381         // promoted as an operand is when it's only use is liveout.
11382         if (UI->getOpcode() != ISD::CopyToReg)
11383           return false;
11384       }
11385     }
11386     Promote = true;
11387     break;
11388   }
11389   case ISD::SIGN_EXTEND:
11390   case ISD::ZERO_EXTEND:
11391   case ISD::ANY_EXTEND:
11392     Promote = true;
11393     break;
11394   case ISD::SHL:
11395   case ISD::SRL: {
11396     SDValue N0 = Op.getOperand(0);
11397     // Look out for (store (shl (load), x)).
11398     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11399       return false;
11400     Promote = true;
11401     break;
11402   }
11403   case ISD::ADD:
11404   case ISD::MUL:
11405   case ISD::AND:
11406   case ISD::OR:
11407   case ISD::XOR:
11408     Commute = true;
11409     // fallthrough
11410   case ISD::SUB: {
11411     SDValue N0 = Op.getOperand(0);
11412     SDValue N1 = Op.getOperand(1);
11413     if (!Commute && MayFoldLoad(N1))
11414       return false;
11415     // Avoid disabling potential load folding opportunities.
11416     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11417       return false;
11418     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11419       return false;
11420     Promote = true;
11421   }
11422   }
11423
11424   PVT = MVT::i32;
11425   return Promote;
11426 }
11427
11428 //===----------------------------------------------------------------------===//
11429 //                           X86 Inline Assembly Support
11430 //===----------------------------------------------------------------------===//
11431
11432 static bool LowerToBSwap(CallInst *CI) {
11433   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11434   // we will turn this bswap into something that will be lowered to logical ops
11435   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11436   // so don't worry about this.
11437
11438   // Verify this is a simple bswap.
11439   if (CI->getNumArgOperands() != 1 ||
11440       CI->getType() != CI->getArgOperand(0)->getType() ||
11441       !CI->getType()->isIntegerTy())
11442     return false;
11443
11444   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11445   if (!Ty || Ty->getBitWidth() % 16 != 0)
11446     return false;
11447
11448   // Okay, we can do this xform, do so now.
11449   const Type *Tys[] = { Ty };
11450   Module *M = CI->getParent()->getParent()->getParent();
11451   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11452
11453   Value *Op = CI->getArgOperand(0);
11454   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11455
11456   CI->replaceAllUsesWith(Op);
11457   CI->eraseFromParent();
11458   return true;
11459 }
11460
11461 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11462   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11463   InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11464
11465   std::string AsmStr = IA->getAsmString();
11466
11467   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11468   SmallVector<StringRef, 4> AsmPieces;
11469   SplitString(AsmStr, AsmPieces, ";\n");
11470
11471   switch (AsmPieces.size()) {
11472   default: return false;
11473   case 1:
11474     AsmStr = AsmPieces[0];
11475     AsmPieces.clear();
11476     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11477
11478     // bswap $0
11479     if (AsmPieces.size() == 2 &&
11480         (AsmPieces[0] == "bswap" ||
11481          AsmPieces[0] == "bswapq" ||
11482          AsmPieces[0] == "bswapl") &&
11483         (AsmPieces[1] == "$0" ||
11484          AsmPieces[1] == "${0:q}")) {
11485       // No need to check constraints, nothing other than the equivalent of
11486       // "=r,0" would be valid here.
11487       return LowerToBSwap(CI);
11488     }
11489     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11490     if (CI->getType()->isIntegerTy(16) &&
11491         AsmPieces.size() == 3 &&
11492         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11493         AsmPieces[1] == "$$8," &&
11494         AsmPieces[2] == "${0:w}" &&
11495         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11496       AsmPieces.clear();
11497       const std::string &Constraints = IA->getConstraintString();
11498       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11499       std::sort(AsmPieces.begin(), AsmPieces.end());
11500       if (AsmPieces.size() == 4 &&
11501           AsmPieces[0] == "~{cc}" &&
11502           AsmPieces[1] == "~{dirflag}" &&
11503           AsmPieces[2] == "~{flags}" &&
11504           AsmPieces[3] == "~{fpsr}") {
11505         return LowerToBSwap(CI);
11506       }
11507     }
11508     break;
11509   case 3:
11510     if (CI->getType()->isIntegerTy(32) &&
11511         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11512       SmallVector<StringRef, 4> Words;
11513       SplitString(AsmPieces[0], Words, " \t,");
11514       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11515           Words[2] == "${0:w}") {
11516         Words.clear();
11517         SplitString(AsmPieces[1], Words, " \t,");
11518         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11519             Words[2] == "$0") {
11520           Words.clear();
11521           SplitString(AsmPieces[2], Words, " \t,");
11522           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11523               Words[2] == "${0:w}") {
11524             AsmPieces.clear();
11525             const std::string &Constraints = IA->getConstraintString();
11526             SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11527             std::sort(AsmPieces.begin(), AsmPieces.end());
11528             if (AsmPieces.size() == 4 &&
11529                 AsmPieces[0] == "~{cc}" &&
11530                 AsmPieces[1] == "~{dirflag}" &&
11531                 AsmPieces[2] == "~{flags}" &&
11532                 AsmPieces[3] == "~{fpsr}") {
11533               return LowerToBSwap(CI);
11534             }
11535           }
11536         }
11537       }
11538     }
11539     if (CI->getType()->isIntegerTy(64) &&
11540         Constraints.size() >= 2 &&
11541         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11542         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11543       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11544       SmallVector<StringRef, 4> Words;
11545       SplitString(AsmPieces[0], Words, " \t");
11546       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11547         Words.clear();
11548         SplitString(AsmPieces[1], Words, " \t");
11549         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11550           Words.clear();
11551           SplitString(AsmPieces[2], Words, " \t,");
11552           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11553               Words[2] == "%edx") {
11554             return LowerToBSwap(CI);
11555           }
11556         }
11557       }
11558     }
11559     break;
11560   }
11561   return false;
11562 }
11563
11564
11565
11566 /// getConstraintType - Given a constraint letter, return the type of
11567 /// constraint it is for this target.
11568 X86TargetLowering::ConstraintType
11569 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11570   if (Constraint.size() == 1) {
11571     switch (Constraint[0]) {
11572     case 'R':
11573     case 'q':
11574     case 'Q':
11575     case 'f':
11576     case 't':
11577     case 'u':
11578     case 'y':
11579     case 'x':
11580     case 'Y':
11581       return C_RegisterClass;
11582     case 'a':
11583     case 'b':
11584     case 'c':
11585     case 'd':
11586     case 'S':
11587     case 'D':
11588     case 'A':
11589       return C_Register;
11590     case 'I':
11591     case 'J':
11592     case 'K':
11593     case 'L':
11594     case 'M':
11595     case 'N':
11596     case 'G':
11597     case 'C':
11598     case 'e':
11599     case 'Z':
11600       return C_Other;
11601     default:
11602       break;
11603     }
11604   }
11605   return TargetLowering::getConstraintType(Constraint);
11606 }
11607
11608 /// Examine constraint type and operand type and determine a weight value.
11609 /// This object must already have been set up with the operand type
11610 /// and the current alternative constraint selected.
11611 TargetLowering::ConstraintWeight
11612   X86TargetLowering::getSingleConstraintMatchWeight(
11613     AsmOperandInfo &info, const char *constraint) const {
11614   ConstraintWeight weight = CW_Invalid;
11615   Value *CallOperandVal = info.CallOperandVal;
11616     // If we don't have a value, we can't do a match,
11617     // but allow it at the lowest weight.
11618   if (CallOperandVal == NULL)
11619     return CW_Default;
11620   const Type *type = CallOperandVal->getType();
11621   // Look at the constraint type.
11622   switch (*constraint) {
11623   default:
11624     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11625   case 'R':
11626   case 'q':
11627   case 'Q':
11628   case 'a':
11629   case 'b':
11630   case 'c':
11631   case 'd':
11632   case 'S':
11633   case 'D':
11634   case 'A':
11635     if (CallOperandVal->getType()->isIntegerTy())
11636       weight = CW_SpecificReg;
11637     break;
11638   case 'f':
11639   case 't':
11640   case 'u':
11641       if (type->isFloatingPointTy())
11642         weight = CW_SpecificReg;
11643       break;
11644   case 'y':
11645       if (type->isX86_MMXTy() && !DisableMMX && Subtarget->hasMMX())
11646         weight = CW_SpecificReg;
11647       break;
11648   case 'x':
11649   case 'Y':
11650     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1())
11651       weight = CW_Register;
11652     break;
11653   case 'I':
11654     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11655       if (C->getZExtValue() <= 31)
11656         weight = CW_Constant;
11657     }
11658     break;
11659   case 'J':
11660     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11661       if (C->getZExtValue() <= 63)
11662         weight = CW_Constant;
11663     }
11664     break;
11665   case 'K':
11666     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11667       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11668         weight = CW_Constant;
11669     }
11670     break;
11671   case 'L':
11672     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11673       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11674         weight = CW_Constant;
11675     }
11676     break;
11677   case 'M':
11678     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11679       if (C->getZExtValue() <= 3)
11680         weight = CW_Constant;
11681     }
11682     break;
11683   case 'N':
11684     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11685       if (C->getZExtValue() <= 0xff)
11686         weight = CW_Constant;
11687     }
11688     break;
11689   case 'G':
11690   case 'C':
11691     if (dyn_cast<ConstantFP>(CallOperandVal)) {
11692       weight = CW_Constant;
11693     }
11694     break;
11695   case 'e':
11696     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11697       if ((C->getSExtValue() >= -0x80000000LL) &&
11698           (C->getSExtValue() <= 0x7fffffffLL))
11699         weight = CW_Constant;
11700     }
11701     break;
11702   case 'Z':
11703     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11704       if (C->getZExtValue() <= 0xffffffff)
11705         weight = CW_Constant;
11706     }
11707     break;
11708   }
11709   return weight;
11710 }
11711
11712 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11713 /// with another that has more specific requirements based on the type of the
11714 /// corresponding operand.
11715 const char *X86TargetLowering::
11716 LowerXConstraint(EVT ConstraintVT) const {
11717   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11718   // 'f' like normal targets.
11719   if (ConstraintVT.isFloatingPoint()) {
11720     if (Subtarget->hasSSE2())
11721       return "Y";
11722     if (Subtarget->hasSSE1())
11723       return "x";
11724   }
11725
11726   return TargetLowering::LowerXConstraint(ConstraintVT);
11727 }
11728
11729 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11730 /// vector.  If it is invalid, don't add anything to Ops.
11731 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11732                                                      char Constraint,
11733                                                      std::vector<SDValue>&Ops,
11734                                                      SelectionDAG &DAG) const {
11735   SDValue Result(0, 0);
11736
11737   switch (Constraint) {
11738   default: break;
11739   case 'I':
11740     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11741       if (C->getZExtValue() <= 31) {
11742         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11743         break;
11744       }
11745     }
11746     return;
11747   case 'J':
11748     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11749       if (C->getZExtValue() <= 63) {
11750         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11751         break;
11752       }
11753     }
11754     return;
11755   case 'K':
11756     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11757       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11758         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11759         break;
11760       }
11761     }
11762     return;
11763   case 'N':
11764     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11765       if (C->getZExtValue() <= 255) {
11766         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11767         break;
11768       }
11769     }
11770     return;
11771   case 'e': {
11772     // 32-bit signed value
11773     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11774       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11775                                            C->getSExtValue())) {
11776         // Widen to 64 bits here to get it sign extended.
11777         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11778         break;
11779       }
11780     // FIXME gcc accepts some relocatable values here too, but only in certain
11781     // memory models; it's complicated.
11782     }
11783     return;
11784   }
11785   case 'Z': {
11786     // 32-bit unsigned value
11787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11788       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11789                                            C->getZExtValue())) {
11790         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11791         break;
11792       }
11793     }
11794     // FIXME gcc accepts some relocatable values here too, but only in certain
11795     // memory models; it's complicated.
11796     return;
11797   }
11798   case 'i': {
11799     // Literal immediates are always ok.
11800     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11801       // Widen to 64 bits here to get it sign extended.
11802       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11803       break;
11804     }
11805
11806     // In any sort of PIC mode addresses need to be computed at runtime by
11807     // adding in a register or some sort of table lookup.  These can't
11808     // be used as immediates.
11809     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11810       return;
11811
11812     // If we are in non-pic codegen mode, we allow the address of a global (with
11813     // an optional displacement) to be used with 'i'.
11814     GlobalAddressSDNode *GA = 0;
11815     int64_t Offset = 0;
11816
11817     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11818     while (1) {
11819       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11820         Offset += GA->getOffset();
11821         break;
11822       } else if (Op.getOpcode() == ISD::ADD) {
11823         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11824           Offset += C->getZExtValue();
11825           Op = Op.getOperand(0);
11826           continue;
11827         }
11828       } else if (Op.getOpcode() == ISD::SUB) {
11829         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11830           Offset += -C->getZExtValue();
11831           Op = Op.getOperand(0);
11832           continue;
11833         }
11834       }
11835
11836       // Otherwise, this isn't something we can handle, reject it.
11837       return;
11838     }
11839
11840     const GlobalValue *GV = GA->getGlobal();
11841     // If we require an extra load to get this address, as in PIC mode, we
11842     // can't accept it.
11843     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11844                                                         getTargetMachine())))
11845       return;
11846
11847     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11848                                         GA->getValueType(0), Offset);
11849     break;
11850   }
11851   }
11852
11853   if (Result.getNode()) {
11854     Ops.push_back(Result);
11855     return;
11856   }
11857   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11858 }
11859
11860 std::vector<unsigned> X86TargetLowering::
11861 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11862                                   EVT VT) const {
11863   if (Constraint.size() == 1) {
11864     // FIXME: not handling fp-stack yet!
11865     switch (Constraint[0]) {      // GCC X86 Constraint Letters
11866     default: break;  // Unknown constraint letter
11867     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11868       if (Subtarget->is64Bit()) {
11869         if (VT == MVT::i32)
11870           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11871                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11872                                        X86::R10D,X86::R11D,X86::R12D,
11873                                        X86::R13D,X86::R14D,X86::R15D,
11874                                        X86::EBP, X86::ESP, 0);
11875         else if (VT == MVT::i16)
11876           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
11877                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
11878                                        X86::R10W,X86::R11W,X86::R12W,
11879                                        X86::R13W,X86::R14W,X86::R15W,
11880                                        X86::BP,  X86::SP, 0);
11881         else if (VT == MVT::i8)
11882           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
11883                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11884                                        X86::R10B,X86::R11B,X86::R12B,
11885                                        X86::R13B,X86::R14B,X86::R15B,
11886                                        X86::BPL, X86::SPL, 0);
11887
11888         else if (VT == MVT::i64)
11889           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11890                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
11891                                        X86::R10, X86::R11, X86::R12,
11892                                        X86::R13, X86::R14, X86::R15,
11893                                        X86::RBP, X86::RSP, 0);
11894
11895         break;
11896       }
11897       // 32-bit fallthrough
11898     case 'Q':   // Q_REGS
11899       if (VT == MVT::i32)
11900         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11901       else if (VT == MVT::i16)
11902         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11903       else if (VT == MVT::i8)
11904         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11905       else if (VT == MVT::i64)
11906         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11907       break;
11908     }
11909   }
11910
11911   return std::vector<unsigned>();
11912 }
11913
11914 std::pair<unsigned, const TargetRegisterClass*>
11915 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11916                                                 EVT VT) const {
11917   // First, see if this is a constraint that directly corresponds to an LLVM
11918   // register class.
11919   if (Constraint.size() == 1) {
11920     // GCC Constraint Letters
11921     switch (Constraint[0]) {
11922     default: break;
11923     case 'r':   // GENERAL_REGS
11924     case 'l':   // INDEX_REGS
11925       if (VT == MVT::i8)
11926         return std::make_pair(0U, X86::GR8RegisterClass);
11927       if (VT == MVT::i16)
11928         return std::make_pair(0U, X86::GR16RegisterClass);
11929       if (VT == MVT::i32 || !Subtarget->is64Bit())
11930         return std::make_pair(0U, X86::GR32RegisterClass);
11931       return std::make_pair(0U, X86::GR64RegisterClass);
11932     case 'R':   // LEGACY_REGS
11933       if (VT == MVT::i8)
11934         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11935       if (VT == MVT::i16)
11936         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11937       if (VT == MVT::i32 || !Subtarget->is64Bit())
11938         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11939       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11940     case 'f':  // FP Stack registers.
11941       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11942       // value to the correct fpstack register class.
11943       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11944         return std::make_pair(0U, X86::RFP32RegisterClass);
11945       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11946         return std::make_pair(0U, X86::RFP64RegisterClass);
11947       return std::make_pair(0U, X86::RFP80RegisterClass);
11948     case 'y':   // MMX_REGS if MMX allowed.
11949       if (!Subtarget->hasMMX()) break;
11950       return std::make_pair(0U, X86::VR64RegisterClass);
11951     case 'Y':   // SSE_REGS if SSE2 allowed
11952       if (!Subtarget->hasSSE2()) break;
11953       // FALL THROUGH.
11954     case 'x':   // SSE_REGS if SSE1 allowed
11955       if (!Subtarget->hasSSE1()) break;
11956
11957       switch (VT.getSimpleVT().SimpleTy) {
11958       default: break;
11959       // Scalar SSE types.
11960       case MVT::f32:
11961       case MVT::i32:
11962         return std::make_pair(0U, X86::FR32RegisterClass);
11963       case MVT::f64:
11964       case MVT::i64:
11965         return std::make_pair(0U, X86::FR64RegisterClass);
11966       // Vector types.
11967       case MVT::v16i8:
11968       case MVT::v8i16:
11969       case MVT::v4i32:
11970       case MVT::v2i64:
11971       case MVT::v4f32:
11972       case MVT::v2f64:
11973         return std::make_pair(0U, X86::VR128RegisterClass);
11974       }
11975       break;
11976     }
11977   }
11978
11979   // Use the default implementation in TargetLowering to convert the register
11980   // constraint into a member of a register class.
11981   std::pair<unsigned, const TargetRegisterClass*> Res;
11982   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11983
11984   // Not found as a standard register?
11985   if (Res.second == 0) {
11986     // Map st(0) -> st(7) -> ST0
11987     if (Constraint.size() == 7 && Constraint[0] == '{' &&
11988         tolower(Constraint[1]) == 's' &&
11989         tolower(Constraint[2]) == 't' &&
11990         Constraint[3] == '(' &&
11991         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11992         Constraint[5] == ')' &&
11993         Constraint[6] == '}') {
11994
11995       Res.first = X86::ST0+Constraint[4]-'0';
11996       Res.second = X86::RFP80RegisterClass;
11997       return Res;
11998     }
11999
12000     // GCC allows "st(0)" to be called just plain "st".
12001     if (StringRef("{st}").equals_lower(Constraint)) {
12002       Res.first = X86::ST0;
12003       Res.second = X86::RFP80RegisterClass;
12004       return Res;
12005     }
12006
12007     // flags -> EFLAGS
12008     if (StringRef("{flags}").equals_lower(Constraint)) {
12009       Res.first = X86::EFLAGS;
12010       Res.second = X86::CCRRegisterClass;
12011       return Res;
12012     }
12013
12014     // 'A' means EAX + EDX.
12015     if (Constraint == "A") {
12016       Res.first = X86::EAX;
12017       Res.second = X86::GR32_ADRegisterClass;
12018       return Res;
12019     }
12020     return Res;
12021   }
12022
12023   // Otherwise, check to see if this is a register class of the wrong value
12024   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12025   // turn into {ax},{dx}.
12026   if (Res.second->hasType(VT))
12027     return Res;   // Correct type already, nothing to do.
12028
12029   // All of the single-register GCC register classes map their values onto
12030   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12031   // really want an 8-bit or 32-bit register, map to the appropriate register
12032   // class and return the appropriate register.
12033   if (Res.second == X86::GR16RegisterClass) {
12034     if (VT == MVT::i8) {
12035       unsigned DestReg = 0;
12036       switch (Res.first) {
12037       default: break;
12038       case X86::AX: DestReg = X86::AL; break;
12039       case X86::DX: DestReg = X86::DL; break;
12040       case X86::CX: DestReg = X86::CL; break;
12041       case X86::BX: DestReg = X86::BL; break;
12042       }
12043       if (DestReg) {
12044         Res.first = DestReg;
12045         Res.second = X86::GR8RegisterClass;
12046       }
12047     } else if (VT == MVT::i32) {
12048       unsigned DestReg = 0;
12049       switch (Res.first) {
12050       default: break;
12051       case X86::AX: DestReg = X86::EAX; break;
12052       case X86::DX: DestReg = X86::EDX; break;
12053       case X86::CX: DestReg = X86::ECX; break;
12054       case X86::BX: DestReg = X86::EBX; break;
12055       case X86::SI: DestReg = X86::ESI; break;
12056       case X86::DI: DestReg = X86::EDI; break;
12057       case X86::BP: DestReg = X86::EBP; break;
12058       case X86::SP: DestReg = X86::ESP; break;
12059       }
12060       if (DestReg) {
12061         Res.first = DestReg;
12062         Res.second = X86::GR32RegisterClass;
12063       }
12064     } else if (VT == MVT::i64) {
12065       unsigned DestReg = 0;
12066       switch (Res.first) {
12067       default: break;
12068       case X86::AX: DestReg = X86::RAX; break;
12069       case X86::DX: DestReg = X86::RDX; break;
12070       case X86::CX: DestReg = X86::RCX; break;
12071       case X86::BX: DestReg = X86::RBX; break;
12072       case X86::SI: DestReg = X86::RSI; break;
12073       case X86::DI: DestReg = X86::RDI; break;
12074       case X86::BP: DestReg = X86::RBP; break;
12075       case X86::SP: DestReg = X86::RSP; break;
12076       }
12077       if (DestReg) {
12078         Res.first = DestReg;
12079         Res.second = X86::GR64RegisterClass;
12080       }
12081     }
12082   } else if (Res.second == X86::FR32RegisterClass ||
12083              Res.second == X86::FR64RegisterClass ||
12084              Res.second == X86::VR128RegisterClass) {
12085     // Handle references to XMM physical registers that got mapped into the
12086     // wrong class.  This can happen with constraints like {xmm0} where the
12087     // target independent register mapper will just pick the first match it can
12088     // find, ignoring the required type.
12089     if (VT == MVT::f32)
12090       Res.second = X86::FR32RegisterClass;
12091     else if (VT == MVT::f64)
12092       Res.second = X86::FR64RegisterClass;
12093     else if (X86::VR128RegisterClass->hasType(VT))
12094       Res.second = X86::VR128RegisterClass;
12095   }
12096
12097   return Res;
12098 }