Add support for matching psign & plendvb to the x86 target
[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->hasXMMInt();
85   X86ScalarSSEf32 = Subtarget->hasXMM();
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::CTTZ             , MVT::i8   , Custom);
289   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
290   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
291   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
292   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
293   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
294   if (Subtarget->is64Bit()) {
295     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
296     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
297   }
298
299   if (Subtarget->hasPOPCNT()) {
300     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
301   } else {
302     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
303     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
304     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
305     if (Subtarget->is64Bit())
306       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
307   }
308
309   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
310   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
311
312   // These should be promoted to a larger select which is supported.
313   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
314   // X86 wants to expand cmov itself.
315   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
316   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
317   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
318   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
319   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
320   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
321   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
322   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
323   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
324   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
325   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
326   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
327   if (Subtarget->is64Bit()) {
328     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
329     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
330   }
331   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
332
333   // Darwin ABI issue.
334   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
335   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
336   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
337   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
338   if (Subtarget->is64Bit())
339     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
340   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
341   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
342   if (Subtarget->is64Bit()) {
343     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
344     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
345     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
346     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
347     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
348   }
349   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
350   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
351   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
352   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
353   if (Subtarget->is64Bit()) {
354     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
355     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
356     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
357   }
358
359   if (Subtarget->hasXMM())
360     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
361
362   // We may not have a libcall for MEMBARRIER so we should lower this.
363   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
364
365   // On X86 and X86-64, atomic operations are lowered to locked instructions.
366   // Locked instructions, in turn, have implicit fence semantics (all memory
367   // operations are flushed before issuing the locked instruction, and they
368   // are not buffered), so we can fold away the common pattern of
369   // fence-atomic-fence.
370   setShouldFoldAtomicFences(true);
371
372   // Expand certain atomics
373   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
374   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
375   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
376   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
377
378   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
379   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
380   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
381   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
382
383   if (!Subtarget->is64Bit()) {
384     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
385     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
386     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
387     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
388     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
389     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
390     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
391   }
392
393   // FIXME - use subtarget debug flags
394   if (!Subtarget->isTargetDarwin() &&
395       !Subtarget->isTargetELF() &&
396       !Subtarget->isTargetCygMing()) {
397     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
398   }
399
400   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
401   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
402   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
403   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
404   if (Subtarget->is64Bit()) {
405     setExceptionPointerRegister(X86::RAX);
406     setExceptionSelectorRegister(X86::RDX);
407   } else {
408     setExceptionPointerRegister(X86::EAX);
409     setExceptionSelectorRegister(X86::EDX);
410   }
411   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
412   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
413
414   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
415
416   setOperationAction(ISD::TRAP, MVT::Other, Legal);
417
418   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
419   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
420   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
421   if (Subtarget->is64Bit()) {
422     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
423     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
424   } else {
425     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
426     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
427   }
428
429   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
430   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
431   if (Subtarget->is64Bit())
432     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
433   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
434     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
435   else
436     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
437
438   if (!UseSoftFloat && X86ScalarSSEf64) {
439     // f32 and f64 use SSE.
440     // Set up the FP register classes.
441     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
442     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
443
444     // Use ANDPD to simulate FABS.
445     setOperationAction(ISD::FABS , MVT::f64, Custom);
446     setOperationAction(ISD::FABS , MVT::f32, Custom);
447
448     // Use XORP to simulate FNEG.
449     setOperationAction(ISD::FNEG , MVT::f64, Custom);
450     setOperationAction(ISD::FNEG , MVT::f32, Custom);
451
452     // Use ANDPD and ORPD to simulate FCOPYSIGN.
453     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
454     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
455
456     // We don't support sin/cos/fmod
457     setOperationAction(ISD::FSIN , MVT::f64, Expand);
458     setOperationAction(ISD::FCOS , MVT::f64, Expand);
459     setOperationAction(ISD::FSIN , MVT::f32, Expand);
460     setOperationAction(ISD::FCOS , MVT::f32, Expand);
461
462     // Expand FP immediates into loads from the stack, except for the special
463     // cases we handle.
464     addLegalFPImmediate(APFloat(+0.0)); // xorpd
465     addLegalFPImmediate(APFloat(+0.0f)); // xorps
466   } else if (!UseSoftFloat && X86ScalarSSEf32) {
467     // Use SSE for f32, x87 for f64.
468     // Set up the FP register classes.
469     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
470     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
471
472     // Use ANDPS to simulate FABS.
473     setOperationAction(ISD::FABS , MVT::f32, Custom);
474
475     // Use XORP to simulate FNEG.
476     setOperationAction(ISD::FNEG , MVT::f32, Custom);
477
478     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
479
480     // Use ANDPS and ORPS to simulate FCOPYSIGN.
481     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
482     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
483
484     // We don't support sin/cos/fmod
485     setOperationAction(ISD::FSIN , MVT::f32, Expand);
486     setOperationAction(ISD::FCOS , MVT::f32, Expand);
487
488     // Special cases we handle for FP constants.
489     addLegalFPImmediate(APFloat(+0.0f)); // xorps
490     addLegalFPImmediate(APFloat(+0.0)); // FLD0
491     addLegalFPImmediate(APFloat(+1.0)); // FLD1
492     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
493     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
494
495     if (!UnsafeFPMath) {
496       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
497       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
498     }
499   } else if (!UseSoftFloat) {
500     // f32 and f64 in x87.
501     // Set up the FP register classes.
502     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
503     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
504
505     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
506     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
507     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
508     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
509
510     if (!UnsafeFPMath) {
511       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
512       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
513     }
514     addLegalFPImmediate(APFloat(+0.0)); // FLD0
515     addLegalFPImmediate(APFloat(+1.0)); // FLD1
516     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
517     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
518     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
519     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
520     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
521     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
522   }
523
524   // Long double always uses X87.
525   if (!UseSoftFloat) {
526     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
527     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
528     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
529     {
530       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
531       addLegalFPImmediate(TmpFlt);  // FLD0
532       TmpFlt.changeSign();
533       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
534
535       bool ignored;
536       APFloat TmpFlt2(+1.0);
537       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
538                       &ignored);
539       addLegalFPImmediate(TmpFlt2);  // FLD1
540       TmpFlt2.changeSign();
541       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
542     }
543
544     if (!UnsafeFPMath) {
545       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
546       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
547     }
548   }
549
550   // Always use a library call for pow.
551   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
552   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
553   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
554
555   setOperationAction(ISD::FLOG, MVT::f80, Expand);
556   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
557   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
558   setOperationAction(ISD::FEXP, MVT::f80, Expand);
559   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
560
561   // First set operation action for all vector types to either promote
562   // (for widening) or expand (for scalarization). Then we will selectively
563   // turn on ones that can be effectively codegen'd.
564   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
565        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
566     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
581     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
582     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
610     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
614     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
615     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
616     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
617     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
618     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
619     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
620          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
621       setTruncStoreAction((MVT::SimpleValueType)VT,
622                           (MVT::SimpleValueType)InnerVT, Expand);
623     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
624     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
625     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
626   }
627
628   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
629   // with -msoft-float, disable use of MMX as well.
630   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
631     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
632     // No operations on x86mmx supported, everything uses intrinsics.
633   }
634
635   // MMX-sized vectors (other than x86mmx) are expected to be expanded
636   // into smaller operations.
637   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
638   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
639   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
640   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
641   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
642   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
643   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
644   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
645   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
646   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
647   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
648   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
649   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
650   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
651   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
652   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
653   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
654   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
655   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
656   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
657   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
658   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
659   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
660   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
661   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
662   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
663   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
664   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
665   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
666
667   if (!UseSoftFloat && Subtarget->hasXMM()) {
668     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
669
670     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
671     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
672     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
673     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
674     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
675     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
676     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
677     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
679     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
680     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
681     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
682   }
683
684   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
685     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
686
687     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
688     // registers cannot be used even for integer operations.
689     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
690     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
691     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
692     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
693
694     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
695     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
696     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
697     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
698     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
699     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
700     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
701     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
702     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
703     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
704     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
705     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
706     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
707     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
708     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
709     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
710
711     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
712     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
713     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
714     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
715
716     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
717     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
718     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
719     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
720     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
721
722     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
723     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
724     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
725     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
726     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
727
728     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
729     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
730       EVT VT = (MVT::SimpleValueType)i;
731       // Do not attempt to custom lower non-power-of-2 vectors
732       if (!isPowerOf2_32(VT.getVectorNumElements()))
733         continue;
734       // Do not attempt to custom lower non-128-bit vectors
735       if (!VT.is128BitVector())
736         continue;
737       setOperationAction(ISD::BUILD_VECTOR,
738                          VT.getSimpleVT().SimpleTy, Custom);
739       setOperationAction(ISD::VECTOR_SHUFFLE,
740                          VT.getSimpleVT().SimpleTy, Custom);
741       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
742                          VT.getSimpleVT().SimpleTy, Custom);
743     }
744
745     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
746     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
747     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
748     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
749     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
750     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
751
752     if (Subtarget->is64Bit()) {
753       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
754       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
755     }
756
757     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
758     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
759       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
760       EVT VT = SVT;
761
762       // Do not attempt to promote non-128-bit vectors
763       if (!VT.is128BitVector())
764         continue;
765
766       setOperationAction(ISD::AND,    SVT, Promote);
767       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
768       setOperationAction(ISD::OR,     SVT, Promote);
769       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
770       setOperationAction(ISD::XOR,    SVT, Promote);
771       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
772       setOperationAction(ISD::LOAD,   SVT, Promote);
773       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
774       setOperationAction(ISD::SELECT, SVT, Promote);
775       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
776     }
777
778     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
779
780     // Custom lower v2i64 and v2f64 selects.
781     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
782     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
783     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
784     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
785
786     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
787     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
788   }
789
790   if (Subtarget->hasSSE41()) {
791     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
792     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
793     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
794     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
795     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
796     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
797     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
798     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
799     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
800     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
801
802     // FIXME: Do we need to handle scalar-to-vector here?
803     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
804
805     // Can turn SHL into an integer multiply.
806     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
807     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
808
809     // i8 and i16 vectors are custom , because the source register and source
810     // source memory operand types are not the same width.  f32 vectors are
811     // custom since the immediate controlling the insert encodes additional
812     // information.
813     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
814     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
815     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
816     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
817
818     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
819     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
820     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
822
823     if (Subtarget->is64Bit()) {
824       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
825       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
826     }
827   }
828
829   if (Subtarget->hasSSE42()) {
830     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
831   }
832
833   if (!UseSoftFloat && Subtarget->hasAVX()) {
834     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
835     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
836     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
837     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
838     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
839
840     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
841     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
842     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
843     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
844     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
845     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
846     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
847     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
848     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
849     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
850     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
851     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
852     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
853     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
854     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
855
856     // Operations to consider commented out -v16i16 v32i8
857     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
858     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
859     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
860     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
861     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
862     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
863     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
864     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
865     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
866     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
867     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
868     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
869     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
870     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
871
872     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
873     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
874     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
875     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
876
877     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
878     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
879     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
880     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
882
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
889
890 #if 0
891     // Not sure we want to do this since there are no 256-bit integer
892     // operations in AVX
893
894     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895     // This includes 256-bit vectors
896     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
897       EVT VT = (MVT::SimpleValueType)i;
898
899       // Do not attempt to custom lower non-power-of-2 vectors
900       if (!isPowerOf2_32(VT.getVectorNumElements()))
901         continue;
902
903       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
904       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
906     }
907
908     if (Subtarget->is64Bit()) {
909       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
911     }
912 #endif
913
914 #if 0
915     // Not sure we want to do this since there are no 256-bit integer
916     // operations in AVX
917
918     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
919     // Including 256-bit vectors
920     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
921       EVT VT = (MVT::SimpleValueType)i;
922
923       if (!VT.is256BitVector()) {
924         continue;
925       }
926       setOperationAction(ISD::AND,    VT, Promote);
927       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
928       setOperationAction(ISD::OR,     VT, Promote);
929       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
930       setOperationAction(ISD::XOR,    VT, Promote);
931       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
932       setOperationAction(ISD::LOAD,   VT, Promote);
933       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
934       setOperationAction(ISD::SELECT, VT, Promote);
935       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
936     }
937
938     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
939 #endif
940   }
941
942   // We want to custom lower some of our intrinsics.
943   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
944
945   // Add/Sub/Mul with overflow operations are custom lowered.
946   setOperationAction(ISD::SADDO, MVT::i32, Custom);
947   setOperationAction(ISD::UADDO, MVT::i32, Custom);
948   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
949   setOperationAction(ISD::USUBO, MVT::i32, Custom);
950   setOperationAction(ISD::SMULO, MVT::i32, Custom);
951   setOperationAction(ISD::UMULO, MVT::i32, Custom);
952
953   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
954   // handle type legalization for these operations here.
955   //
956   // FIXME: We really should do custom legalization for addition and
957   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
958   // than generic legalization for 64-bit multiplication-with-overflow, though.
959   if (Subtarget->is64Bit()) {
960     setOperationAction(ISD::SADDO, MVT::i64, Custom);
961     setOperationAction(ISD::UADDO, MVT::i64, Custom);
962     setOperationAction(ISD::SSUBO, MVT::i64, Custom);
963     setOperationAction(ISD::USUBO, MVT::i64, Custom);
964     setOperationAction(ISD::SMULO, MVT::i64, Custom);
965     setOperationAction(ISD::UMULO, MVT::i64, Custom);
966   }
967
968   if (!Subtarget->is64Bit()) {
969     // These libcalls are not available in 32-bit.
970     setLibcallName(RTLIB::SHL_I128, 0);
971     setLibcallName(RTLIB::SRL_I128, 0);
972     setLibcallName(RTLIB::SRA_I128, 0);
973   }
974
975   // We have target-specific dag combine patterns for the following nodes:
976   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
977   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
978   setTargetDAGCombine(ISD::BUILD_VECTOR);
979   setTargetDAGCombine(ISD::SELECT);
980   setTargetDAGCombine(ISD::SHL);
981   setTargetDAGCombine(ISD::SRA);
982   setTargetDAGCombine(ISD::SRL);
983   setTargetDAGCombine(ISD::OR);
984   setTargetDAGCombine(ISD::AND);
985   setTargetDAGCombine(ISD::STORE);
986   setTargetDAGCombine(ISD::ZERO_EXTEND);
987   if (Subtarget->is64Bit())
988     setTargetDAGCombine(ISD::MUL);
989
990   computeRegisterProperties();
991
992   // FIXME: These should be based on subtarget info. Plus, the values should
993   // be smaller when we are in optimizing for size mode.
994   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
995   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
996   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
997   setPrefLoopAlignment(16);
998   benefitFromCodePlacementOpt = true;
999 }
1000
1001
1002 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1003   return MVT::i8;
1004 }
1005
1006
1007 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1008 /// the desired ByVal argument alignment.
1009 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1010   if (MaxAlign == 16)
1011     return;
1012   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1013     if (VTy->getBitWidth() == 128)
1014       MaxAlign = 16;
1015   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1016     unsigned EltAlign = 0;
1017     getMaxByValAlign(ATy->getElementType(), EltAlign);
1018     if (EltAlign > MaxAlign)
1019       MaxAlign = EltAlign;
1020   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1021     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1022       unsigned EltAlign = 0;
1023       getMaxByValAlign(STy->getElementType(i), EltAlign);
1024       if (EltAlign > MaxAlign)
1025         MaxAlign = EltAlign;
1026       if (MaxAlign == 16)
1027         break;
1028     }
1029   }
1030   return;
1031 }
1032
1033 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1034 /// function arguments in the caller parameter area. For X86, aggregates
1035 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1036 /// are at 4-byte boundaries.
1037 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1038   if (Subtarget->is64Bit()) {
1039     // Max of 8 and alignment of type.
1040     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1041     if (TyAlign > 8)
1042       return TyAlign;
1043     return 8;
1044   }
1045
1046   unsigned Align = 4;
1047   if (Subtarget->hasXMM())
1048     getMaxByValAlign(Ty, Align);
1049   return Align;
1050 }
1051
1052 /// getOptimalMemOpType - Returns the target specific optimal type for load
1053 /// and store operations as a result of memset, memcpy, and memmove
1054 /// lowering. If DstAlign is zero that means it's safe to destination
1055 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1056 /// means there isn't a need to check it against alignment requirement,
1057 /// probably because the source does not need to be loaded. If
1058 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1059 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1060 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1061 /// constant so it does not need to be loaded.
1062 /// It returns EVT::Other if the type should be determined using generic
1063 /// target-independent logic.
1064 EVT
1065 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1066                                        unsigned DstAlign, unsigned SrcAlign,
1067                                        bool NonScalarIntSafe,
1068                                        bool MemcpyStrSrc,
1069                                        MachineFunction &MF) const {
1070   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1071   // linux.  This is because the stack realignment code can't handle certain
1072   // cases like PR2962.  This should be removed when PR2962 is fixed.
1073   const Function *F = MF.getFunction();
1074   if (NonScalarIntSafe &&
1075       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1076     if (Size >= 16 &&
1077         (Subtarget->isUnalignedMemAccessFast() ||
1078          ((DstAlign == 0 || DstAlign >= 16) &&
1079           (SrcAlign == 0 || SrcAlign >= 16))) &&
1080         Subtarget->getStackAlignment() >= 16) {
1081       if (Subtarget->hasSSE2())
1082         return MVT::v4i32;
1083       if (Subtarget->hasSSE1())
1084         return MVT::v4f32;
1085     } else if (!MemcpyStrSrc && Size >= 8 &&
1086                !Subtarget->is64Bit() &&
1087                Subtarget->getStackAlignment() >= 8 &&
1088                Subtarget->hasXMMInt()) {
1089       // Do not use f64 to lower memcpy if source is string constant. It's
1090       // better to use i32 to avoid the loads.
1091       return MVT::f64;
1092     }
1093   }
1094   if (Subtarget->is64Bit() && Size >= 8)
1095     return MVT::i64;
1096   return MVT::i32;
1097 }
1098
1099 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1100 /// current function.  The returned value is a member of the
1101 /// MachineJumpTableInfo::JTEntryKind enum.
1102 unsigned X86TargetLowering::getJumpTableEncoding() const {
1103   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1104   // symbol.
1105   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1106       Subtarget->isPICStyleGOT())
1107     return MachineJumpTableInfo::EK_Custom32;
1108
1109   // Otherwise, use the normal jump table encoding heuristics.
1110   return TargetLowering::getJumpTableEncoding();
1111 }
1112
1113 const MCExpr *
1114 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1115                                              const MachineBasicBlock *MBB,
1116                                              unsigned uid,MCContext &Ctx) const{
1117   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1118          Subtarget->isPICStyleGOT());
1119   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1120   // entries.
1121   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1122                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1123 }
1124
1125 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1126 /// jumptable.
1127 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1128                                                     SelectionDAG &DAG) const {
1129   if (!Subtarget->is64Bit())
1130     // This doesn't have DebugLoc associated with it, but is not really the
1131     // same as a Register.
1132     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1133   return Table;
1134 }
1135
1136 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1137 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1138 /// MCExpr.
1139 const MCExpr *X86TargetLowering::
1140 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1141                              MCContext &Ctx) const {
1142   // X86-64 uses RIP relative addressing based on the jump table label.
1143   if (Subtarget->isPICStyleRIPRel())
1144     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1145
1146   // Otherwise, the reference is relative to the PIC base.
1147   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1148 }
1149
1150 /// getFunctionAlignment - Return the Log2 alignment of this function.
1151 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1152   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1153 }
1154
1155 std::pair<const TargetRegisterClass*, uint8_t>
1156 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1157   const TargetRegisterClass *RRC = 0;
1158   uint8_t Cost = 1;
1159   switch (VT.getSimpleVT().SimpleTy) {
1160   default:
1161     return TargetLowering::findRepresentativeClass(VT);
1162   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1163     RRC = (Subtarget->is64Bit()
1164            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1165     break;
1166   case MVT::x86mmx:
1167     RRC = X86::VR64RegisterClass;
1168     break;
1169   case MVT::f32: case MVT::f64:
1170   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1171   case MVT::v4f32: case MVT::v2f64:
1172   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1173   case MVT::v4f64:
1174     RRC = X86::VR128RegisterClass;
1175     break;
1176   }
1177   return std::make_pair(RRC, Cost);
1178 }
1179
1180 unsigned
1181 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1182                                        MachineFunction &MF) const {
1183   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1184
1185   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1186   switch (RC->getID()) {
1187   default:
1188     return 0;
1189   case X86::GR32RegClassID:
1190     return 4 - FPDiff;
1191   case X86::GR64RegClassID:
1192     return 8 - FPDiff;
1193   case X86::VR128RegClassID:
1194     return Subtarget->is64Bit() ? 10 : 4;
1195   case X86::VR64RegClassID:
1196     return 4;
1197   }
1198 }
1199
1200 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1201                                                unsigned &Offset) const {
1202   if (!Subtarget->isTargetLinux())
1203     return false;
1204
1205   if (Subtarget->is64Bit()) {
1206     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1207     Offset = 0x28;
1208     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1209       AddressSpace = 256;
1210     else
1211       AddressSpace = 257;
1212   } else {
1213     // %gs:0x14 on i386
1214     Offset = 0x14;
1215     AddressSpace = 256;
1216   }
1217   return true;
1218 }
1219
1220
1221 //===----------------------------------------------------------------------===//
1222 //               Return Value Calling Convention Implementation
1223 //===----------------------------------------------------------------------===//
1224
1225 #include "X86GenCallingConv.inc"
1226
1227 bool
1228 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1229                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1230                         LLVMContext &Context) const {
1231   SmallVector<CCValAssign, 16> RVLocs;
1232   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1233                  RVLocs, Context);
1234   return CCInfo.CheckReturn(Outs, RetCC_X86);
1235 }
1236
1237 SDValue
1238 X86TargetLowering::LowerReturn(SDValue Chain,
1239                                CallingConv::ID CallConv, bool isVarArg,
1240                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1241                                const SmallVectorImpl<SDValue> &OutVals,
1242                                DebugLoc dl, SelectionDAG &DAG) const {
1243   MachineFunction &MF = DAG.getMachineFunction();
1244   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1245
1246   SmallVector<CCValAssign, 16> RVLocs;
1247   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1248                  RVLocs, *DAG.getContext());
1249   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1250
1251   // Add the regs to the liveout set for the function.
1252   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1253   for (unsigned i = 0; i != RVLocs.size(); ++i)
1254     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1255       MRI.addLiveOut(RVLocs[i].getLocReg());
1256
1257   SDValue Flag;
1258
1259   SmallVector<SDValue, 6> RetOps;
1260   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1261   // Operand #1 = Bytes To Pop
1262   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1263                    MVT::i16));
1264
1265   // Copy the result values into the output registers.
1266   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1267     CCValAssign &VA = RVLocs[i];
1268     assert(VA.isRegLoc() && "Can only return in registers!");
1269     SDValue ValToCopy = OutVals[i];
1270     EVT ValVT = ValToCopy.getValueType();
1271
1272     // If this is x86-64, and we disabled SSE, we can't return FP values,
1273     // or SSE or MMX vectors.
1274     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1275          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1276           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1277       report_fatal_error("SSE register return with SSE disabled");
1278     }
1279     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1280     // llvm-gcc has never done it right and no one has noticed, so this
1281     // should be OK for now.
1282     if (ValVT == MVT::f64 &&
1283         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1284       report_fatal_error("SSE2 register return with SSE2 disabled");
1285
1286     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1287     // the RET instruction and handled by the FP Stackifier.
1288     if (VA.getLocReg() == X86::ST0 ||
1289         VA.getLocReg() == X86::ST1) {
1290       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1291       // change the value to the FP stack register class.
1292       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1293         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1294       RetOps.push_back(ValToCopy);
1295       // Don't emit a copytoreg.
1296       continue;
1297     }
1298
1299     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1300     // which is returned in RAX / RDX.
1301     if (Subtarget->is64Bit()) {
1302       if (ValVT == MVT::x86mmx) {
1303         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1304           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1305           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1306                                   ValToCopy);
1307           // If we don't have SSE2 available, convert to v4f32 so the generated
1308           // register is legal.
1309           if (!Subtarget->hasSSE2())
1310             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1311         }
1312       }
1313     }
1314
1315     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1316     Flag = Chain.getValue(1);
1317   }
1318
1319   // The x86-64 ABI for returning structs by value requires that we copy
1320   // the sret argument into %rax for the return. We saved the argument into
1321   // a virtual register in the entry block, so now we copy the value out
1322   // and into %rax.
1323   if (Subtarget->is64Bit() &&
1324       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1325     MachineFunction &MF = DAG.getMachineFunction();
1326     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1327     unsigned Reg = FuncInfo->getSRetReturnReg();
1328     assert(Reg &&
1329            "SRetReturnReg should have been set in LowerFormalArguments().");
1330     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1331
1332     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1333     Flag = Chain.getValue(1);
1334
1335     // RAX now acts like a return value.
1336     MRI.addLiveOut(X86::RAX);
1337   }
1338
1339   RetOps[0] = Chain;  // Update chain.
1340
1341   // Add the flag if we have it.
1342   if (Flag.getNode())
1343     RetOps.push_back(Flag);
1344
1345   return DAG.getNode(X86ISD::RET_FLAG, dl,
1346                      MVT::Other, &RetOps[0], RetOps.size());
1347 }
1348
1349 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1350   if (N->getNumValues() != 1)
1351     return false;
1352   if (!N->hasNUsesOfValue(1, 0))
1353     return false;
1354
1355   SDNode *Copy = *N->use_begin();
1356   if (Copy->getOpcode() != ISD::CopyToReg &&
1357       Copy->getOpcode() != ISD::FP_EXTEND)
1358     return false;
1359
1360   bool HasRet = false;
1361   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1362        UI != UE; ++UI) {
1363     if (UI->getOpcode() != X86ISD::RET_FLAG)
1364       return false;
1365     HasRet = true;
1366   }
1367
1368   return HasRet;
1369 }
1370
1371 /// LowerCallResult - Lower the result values of a call into the
1372 /// appropriate copies out of appropriate physical registers.
1373 ///
1374 SDValue
1375 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1376                                    CallingConv::ID CallConv, bool isVarArg,
1377                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1378                                    DebugLoc dl, SelectionDAG &DAG,
1379                                    SmallVectorImpl<SDValue> &InVals) const {
1380
1381   // Assign locations to each value returned by this call.
1382   SmallVector<CCValAssign, 16> RVLocs;
1383   bool Is64Bit = Subtarget->is64Bit();
1384   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1385                  RVLocs, *DAG.getContext());
1386   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1387
1388   // Copy all of the result registers out of their specified physreg.
1389   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1390     CCValAssign &VA = RVLocs[i];
1391     EVT CopyVT = VA.getValVT();
1392
1393     // If this is x86-64, and we disabled SSE, we can't return FP values
1394     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1395         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1396       report_fatal_error("SSE register return with SSE disabled");
1397     }
1398
1399     SDValue Val;
1400
1401     // If this is a call to a function that returns an fp value on the floating
1402     // point stack, we must guarantee the the value is popped from the stack, so
1403     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1404     // if the return value is not used. We use the FpGET_ST0 instructions
1405     // instead.
1406     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1407       // If we prefer to use the value in xmm registers, copy it out as f80 and
1408       // use a truncate to move it from fp stack reg to xmm reg.
1409       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1410       bool isST0 = VA.getLocReg() == X86::ST0;
1411       unsigned Opc = 0;
1412       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1413       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1414       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1415       SDValue Ops[] = { Chain, InFlag };
1416       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1417                                          Ops, 2), 1);
1418       Val = Chain.getValue(0);
1419
1420       // Round the f80 to the right size, which also moves it to the appropriate
1421       // xmm register.
1422       if (CopyVT != VA.getValVT())
1423         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1424                           // This truncation won't change the value.
1425                           DAG.getIntPtrConstant(1));
1426     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1427       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1428       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1429         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1430                                    MVT::v2i64, InFlag).getValue(1);
1431         Val = Chain.getValue(0);
1432         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1433                           Val, DAG.getConstant(0, MVT::i64));
1434       } else {
1435         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1436                                    MVT::i64, InFlag).getValue(1);
1437         Val = Chain.getValue(0);
1438       }
1439       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1440     } else {
1441       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1442                                  CopyVT, InFlag).getValue(1);
1443       Val = Chain.getValue(0);
1444     }
1445     InFlag = Chain.getValue(2);
1446     InVals.push_back(Val);
1447   }
1448
1449   return Chain;
1450 }
1451
1452
1453 //===----------------------------------------------------------------------===//
1454 //                C & StdCall & Fast Calling Convention implementation
1455 //===----------------------------------------------------------------------===//
1456 //  StdCall calling convention seems to be standard for many Windows' API
1457 //  routines and around. It differs from C calling convention just a little:
1458 //  callee should clean up the stack, not caller. Symbols should be also
1459 //  decorated in some fancy way :) It doesn't support any vector arguments.
1460 //  For info on fast calling convention see Fast Calling Convention (tail call)
1461 //  implementation LowerX86_32FastCCCallTo.
1462
1463 /// CallIsStructReturn - Determines whether a call uses struct return
1464 /// semantics.
1465 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1466   if (Outs.empty())
1467     return false;
1468
1469   return Outs[0].Flags.isSRet();
1470 }
1471
1472 /// ArgsAreStructReturn - Determines whether a function uses struct
1473 /// return semantics.
1474 static bool
1475 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1476   if (Ins.empty())
1477     return false;
1478
1479   return Ins[0].Flags.isSRet();
1480 }
1481
1482 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1483 /// by "Src" to address "Dst" with size and alignment information specified by
1484 /// the specific parameter attribute. The copy will be passed as a byval
1485 /// function parameter.
1486 static SDValue
1487 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1488                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1489                           DebugLoc dl) {
1490   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1491
1492   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1493                        /*isVolatile*/false, /*AlwaysInline=*/true,
1494                        MachinePointerInfo(), MachinePointerInfo());
1495 }
1496
1497 /// IsTailCallConvention - Return true if the calling convention is one that
1498 /// supports tail call optimization.
1499 static bool IsTailCallConvention(CallingConv::ID CC) {
1500   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1501 }
1502
1503 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1504 /// a tailcall target by changing its ABI.
1505 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1506   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1507 }
1508
1509 SDValue
1510 X86TargetLowering::LowerMemArgument(SDValue Chain,
1511                                     CallingConv::ID CallConv,
1512                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1513                                     DebugLoc dl, SelectionDAG &DAG,
1514                                     const CCValAssign &VA,
1515                                     MachineFrameInfo *MFI,
1516                                     unsigned i) const {
1517   // Create the nodes corresponding to a load from this parameter slot.
1518   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1519   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1520   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1521   EVT ValVT;
1522
1523   // If value is passed by pointer we have address passed instead of the value
1524   // itself.
1525   if (VA.getLocInfo() == CCValAssign::Indirect)
1526     ValVT = VA.getLocVT();
1527   else
1528     ValVT = VA.getValVT();
1529
1530   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1531   // changed with more analysis.
1532   // In case of tail call optimization mark all arguments mutable. Since they
1533   // could be overwritten by lowering of arguments in case of a tail call.
1534   if (Flags.isByVal()) {
1535     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1536                                     VA.getLocMemOffset(), isImmutable);
1537     return DAG.getFrameIndex(FI, getPointerTy());
1538   } else {
1539     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1540                                     VA.getLocMemOffset(), isImmutable);
1541     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1542     return DAG.getLoad(ValVT, dl, Chain, FIN,
1543                        MachinePointerInfo::getFixedStack(FI),
1544                        false, false, 0);
1545   }
1546 }
1547
1548 SDValue
1549 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1550                                         CallingConv::ID CallConv,
1551                                         bool isVarArg,
1552                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1553                                         DebugLoc dl,
1554                                         SelectionDAG &DAG,
1555                                         SmallVectorImpl<SDValue> &InVals)
1556                                           const {
1557   MachineFunction &MF = DAG.getMachineFunction();
1558   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1559
1560   const Function* Fn = MF.getFunction();
1561   if (Fn->hasExternalLinkage() &&
1562       Subtarget->isTargetCygMing() &&
1563       Fn->getName() == "main")
1564     FuncInfo->setForceFramePointer(true);
1565
1566   MachineFrameInfo *MFI = MF.getFrameInfo();
1567   bool Is64Bit = Subtarget->is64Bit();
1568   bool IsWin64 = Subtarget->isTargetWin64();
1569
1570   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1571          "Var args not supported with calling convention fastcc or ghc");
1572
1573   // Assign locations to all of the incoming arguments.
1574   SmallVector<CCValAssign, 16> ArgLocs;
1575   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1576                  ArgLocs, *DAG.getContext());
1577   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1578
1579   unsigned LastVal = ~0U;
1580   SDValue ArgValue;
1581   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1582     CCValAssign &VA = ArgLocs[i];
1583     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1584     // places.
1585     assert(VA.getValNo() != LastVal &&
1586            "Don't support value assigned to multiple locs yet");
1587     LastVal = VA.getValNo();
1588
1589     if (VA.isRegLoc()) {
1590       EVT RegVT = VA.getLocVT();
1591       TargetRegisterClass *RC = NULL;
1592       if (RegVT == MVT::i32)
1593         RC = X86::GR32RegisterClass;
1594       else if (Is64Bit && RegVT == MVT::i64)
1595         RC = X86::GR64RegisterClass;
1596       else if (RegVT == MVT::f32)
1597         RC = X86::FR32RegisterClass;
1598       else if (RegVT == MVT::f64)
1599         RC = X86::FR64RegisterClass;
1600       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1601         RC = X86::VR256RegisterClass;
1602       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1603         RC = X86::VR128RegisterClass;
1604       else if (RegVT == MVT::x86mmx)
1605         RC = X86::VR64RegisterClass;
1606       else
1607         llvm_unreachable("Unknown argument type!");
1608
1609       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1610       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1611
1612       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1613       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1614       // right size.
1615       if (VA.getLocInfo() == CCValAssign::SExt)
1616         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1617                                DAG.getValueType(VA.getValVT()));
1618       else if (VA.getLocInfo() == CCValAssign::ZExt)
1619         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1620                                DAG.getValueType(VA.getValVT()));
1621       else if (VA.getLocInfo() == CCValAssign::BCvt)
1622         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1623
1624       if (VA.isExtInLoc()) {
1625         // Handle MMX values passed in XMM regs.
1626         if (RegVT.isVector()) {
1627           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1628                                  ArgValue);
1629         } else
1630           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1631       }
1632     } else {
1633       assert(VA.isMemLoc());
1634       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1635     }
1636
1637     // If value is passed via pointer - do a load.
1638     if (VA.getLocInfo() == CCValAssign::Indirect)
1639       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1640                              MachinePointerInfo(), false, false, 0);
1641
1642     InVals.push_back(ArgValue);
1643   }
1644
1645   // The x86-64 ABI for returning structs by value requires that we copy
1646   // the sret argument into %rax for the return. Save the argument into
1647   // a virtual register so that we can access it from the return points.
1648   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1649     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1650     unsigned Reg = FuncInfo->getSRetReturnReg();
1651     if (!Reg) {
1652       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1653       FuncInfo->setSRetReturnReg(Reg);
1654     }
1655     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1656     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1657   }
1658
1659   unsigned StackSize = CCInfo.getNextStackOffset();
1660   // Align stack specially for tail calls.
1661   if (FuncIsMadeTailCallSafe(CallConv))
1662     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1663
1664   // If the function takes variable number of arguments, make a frame index for
1665   // the start of the first vararg value... for expansion of llvm.va_start.
1666   if (isVarArg) {
1667     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1668                     CallConv != CallingConv::X86_ThisCall))) {
1669       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1670     }
1671     if (Is64Bit) {
1672       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1673
1674       // FIXME: We should really autogenerate these arrays
1675       static const unsigned GPR64ArgRegsWin64[] = {
1676         X86::RCX, X86::RDX, X86::R8,  X86::R9
1677       };
1678       static const unsigned GPR64ArgRegs64Bit[] = {
1679         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1680       };
1681       static const unsigned XMMArgRegs64Bit[] = {
1682         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1683         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1684       };
1685       const unsigned *GPR64ArgRegs;
1686       unsigned NumXMMRegs = 0;
1687
1688       if (IsWin64) {
1689         // The XMM registers which might contain var arg parameters are shadowed
1690         // in their paired GPR.  So we only need to save the GPR to their home
1691         // slots.
1692         TotalNumIntRegs = 4;
1693         GPR64ArgRegs = GPR64ArgRegsWin64;
1694       } else {
1695         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1696         GPR64ArgRegs = GPR64ArgRegs64Bit;
1697
1698         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1699       }
1700       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1701                                                        TotalNumIntRegs);
1702
1703       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1704       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1705              "SSE register cannot be used when SSE is disabled!");
1706       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1707              "SSE register cannot be used when SSE is disabled!");
1708       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1709         // Kernel mode asks for SSE to be disabled, so don't push them
1710         // on the stack.
1711         TotalNumXMMRegs = 0;
1712
1713       if (IsWin64) {
1714         const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1715         // Get to the caller-allocated home save location.  Add 8 to account
1716         // for the return address.
1717         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1718         FuncInfo->setRegSaveFrameIndex(
1719           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1720         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1721       } else {
1722         // For X86-64, if there are vararg parameters that are passed via
1723         // registers, then we must store them to their spots on the stack so they
1724         // may be loaded by deferencing the result of va_next.
1725         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1726         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1727         FuncInfo->setRegSaveFrameIndex(
1728           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1729                                false));
1730       }
1731
1732       // Store the integer parameter registers.
1733       SmallVector<SDValue, 8> MemOps;
1734       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1735                                         getPointerTy());
1736       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1737       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1738         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1739                                   DAG.getIntPtrConstant(Offset));
1740         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1741                                      X86::GR64RegisterClass);
1742         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1743         SDValue Store =
1744           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1745                        MachinePointerInfo::getFixedStack(
1746                          FuncInfo->getRegSaveFrameIndex(), Offset),
1747                        false, false, 0);
1748         MemOps.push_back(Store);
1749         Offset += 8;
1750       }
1751
1752       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1753         // Now store the XMM (fp + vector) parameter registers.
1754         SmallVector<SDValue, 11> SaveXMMOps;
1755         SaveXMMOps.push_back(Chain);
1756
1757         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1758         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1759         SaveXMMOps.push_back(ALVal);
1760
1761         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1762                                FuncInfo->getRegSaveFrameIndex()));
1763         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1764                                FuncInfo->getVarArgsFPOffset()));
1765
1766         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1767           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1768                                        X86::VR128RegisterClass);
1769           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1770           SaveXMMOps.push_back(Val);
1771         }
1772         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1773                                      MVT::Other,
1774                                      &SaveXMMOps[0], SaveXMMOps.size()));
1775       }
1776
1777       if (!MemOps.empty())
1778         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1779                             &MemOps[0], MemOps.size());
1780     }
1781   }
1782
1783   // Some CCs need callee pop.
1784   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1785     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1786   } else {
1787     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1788     // If this is an sret function, the return should pop the hidden pointer.
1789     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1790       FuncInfo->setBytesToPopOnReturn(4);
1791   }
1792
1793   if (!Is64Bit) {
1794     // RegSaveFrameIndex is X86-64 only.
1795     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1796     if (CallConv == CallingConv::X86_FastCall ||
1797         CallConv == CallingConv::X86_ThisCall)
1798       // fastcc functions can't have varargs.
1799       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1800   }
1801
1802   return Chain;
1803 }
1804
1805 SDValue
1806 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1807                                     SDValue StackPtr, SDValue Arg,
1808                                     DebugLoc dl, SelectionDAG &DAG,
1809                                     const CCValAssign &VA,
1810                                     ISD::ArgFlagsTy Flags) const {
1811   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1812   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1813   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1814   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1815   if (Flags.isByVal())
1816     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1817
1818   return DAG.getStore(Chain, dl, Arg, PtrOff,
1819                       MachinePointerInfo::getStack(LocMemOffset),
1820                       false, false, 0);
1821 }
1822
1823 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1824 /// optimization is performed and it is required.
1825 SDValue
1826 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1827                                            SDValue &OutRetAddr, SDValue Chain,
1828                                            bool IsTailCall, bool Is64Bit,
1829                                            int FPDiff, DebugLoc dl) const {
1830   // Adjust the Return address stack slot.
1831   EVT VT = getPointerTy();
1832   OutRetAddr = getReturnAddressFrameIndex(DAG);
1833
1834   // Load the "old" Return address.
1835   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1836                            false, false, 0);
1837   return SDValue(OutRetAddr.getNode(), 1);
1838 }
1839
1840 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1841 /// optimization is performed and it is required (FPDiff!=0).
1842 static SDValue
1843 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1844                          SDValue Chain, SDValue RetAddrFrIdx,
1845                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1846   // Store the return address to the appropriate stack slot.
1847   if (!FPDiff) return Chain;
1848   // Calculate the new stack slot for the return address.
1849   int SlotSize = Is64Bit ? 8 : 4;
1850   int NewReturnAddrFI =
1851     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1852   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1853   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1854   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1855                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1856                        false, false, 0);
1857   return Chain;
1858 }
1859
1860 SDValue
1861 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1862                              CallingConv::ID CallConv, bool isVarArg,
1863                              bool &isTailCall,
1864                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1865                              const SmallVectorImpl<SDValue> &OutVals,
1866                              const SmallVectorImpl<ISD::InputArg> &Ins,
1867                              DebugLoc dl, SelectionDAG &DAG,
1868                              SmallVectorImpl<SDValue> &InVals) const {
1869   MachineFunction &MF = DAG.getMachineFunction();
1870   bool Is64Bit        = Subtarget->is64Bit();
1871   bool IsStructRet    = CallIsStructReturn(Outs);
1872   bool IsSibcall      = false;
1873
1874   if (isTailCall) {
1875     // Check if it's really possible to do a tail call.
1876     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1877                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1878                                                    Outs, OutVals, Ins, DAG);
1879
1880     // Sibcalls are automatically detected tailcalls which do not require
1881     // ABI changes.
1882     if (!GuaranteedTailCallOpt && isTailCall)
1883       IsSibcall = true;
1884
1885     if (isTailCall)
1886       ++NumTailCalls;
1887   }
1888
1889   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1890          "Var args not supported with calling convention fastcc or ghc");
1891
1892   // Analyze operands of the call, assigning locations to each operand.
1893   SmallVector<CCValAssign, 16> ArgLocs;
1894   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1895                  ArgLocs, *DAG.getContext());
1896   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1897
1898   // Get a count of how many bytes are to be pushed on the stack.
1899   unsigned NumBytes = CCInfo.getNextStackOffset();
1900   if (IsSibcall)
1901     // This is a sibcall. The memory operands are available in caller's
1902     // own caller's stack.
1903     NumBytes = 0;
1904   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1905     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1906
1907   int FPDiff = 0;
1908   if (isTailCall && !IsSibcall) {
1909     // Lower arguments at fp - stackoffset + fpdiff.
1910     unsigned NumBytesCallerPushed =
1911       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1912     FPDiff = NumBytesCallerPushed - NumBytes;
1913
1914     // Set the delta of movement of the returnaddr stackslot.
1915     // But only set if delta is greater than previous delta.
1916     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1917       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1918   }
1919
1920   if (!IsSibcall)
1921     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1922
1923   SDValue RetAddrFrIdx;
1924   // Load return adress for tail calls.
1925   if (isTailCall && FPDiff)
1926     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1927                                     Is64Bit, FPDiff, dl);
1928
1929   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1930   SmallVector<SDValue, 8> MemOpChains;
1931   SDValue StackPtr;
1932
1933   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1934   // of tail call optimization arguments are handle later.
1935   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1936     CCValAssign &VA = ArgLocs[i];
1937     EVT RegVT = VA.getLocVT();
1938     SDValue Arg = OutVals[i];
1939     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1940     bool isByVal = Flags.isByVal();
1941
1942     // Promote the value if needed.
1943     switch (VA.getLocInfo()) {
1944     default: llvm_unreachable("Unknown loc info!");
1945     case CCValAssign::Full: break;
1946     case CCValAssign::SExt:
1947       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1948       break;
1949     case CCValAssign::ZExt:
1950       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1951       break;
1952     case CCValAssign::AExt:
1953       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1954         // Special case: passing MMX values in XMM registers.
1955         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1956         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1957         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1958       } else
1959         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1960       break;
1961     case CCValAssign::BCvt:
1962       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1963       break;
1964     case CCValAssign::Indirect: {
1965       // Store the argument.
1966       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1967       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1968       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1969                            MachinePointerInfo::getFixedStack(FI),
1970                            false, false, 0);
1971       Arg = SpillSlot;
1972       break;
1973     }
1974     }
1975
1976     if (VA.isRegLoc()) {
1977       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1978       if (isVarArg && Subtarget->isTargetWin64()) {
1979         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1980         // shadow reg if callee is a varargs function.
1981         unsigned ShadowReg = 0;
1982         switch (VA.getLocReg()) {
1983         case X86::XMM0: ShadowReg = X86::RCX; break;
1984         case X86::XMM1: ShadowReg = X86::RDX; break;
1985         case X86::XMM2: ShadowReg = X86::R8; break;
1986         case X86::XMM3: ShadowReg = X86::R9; break;
1987         }
1988         if (ShadowReg)
1989           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1990       }
1991     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1992       assert(VA.isMemLoc());
1993       if (StackPtr.getNode() == 0)
1994         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1995       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1996                                              dl, DAG, VA, Flags));
1997     }
1998   }
1999
2000   if (!MemOpChains.empty())
2001     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2002                         &MemOpChains[0], MemOpChains.size());
2003
2004   // Build a sequence of copy-to-reg nodes chained together with token chain
2005   // and flag operands which copy the outgoing args into registers.
2006   SDValue InFlag;
2007   // Tail call byval lowering might overwrite argument registers so in case of
2008   // tail call optimization the copies to registers are lowered later.
2009   if (!isTailCall)
2010     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2011       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2012                                RegsToPass[i].second, InFlag);
2013       InFlag = Chain.getValue(1);
2014     }
2015
2016   if (Subtarget->isPICStyleGOT()) {
2017     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2018     // GOT pointer.
2019     if (!isTailCall) {
2020       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2021                                DAG.getNode(X86ISD::GlobalBaseReg,
2022                                            DebugLoc(), getPointerTy()),
2023                                InFlag);
2024       InFlag = Chain.getValue(1);
2025     } else {
2026       // If we are tail calling and generating PIC/GOT style code load the
2027       // address of the callee into ECX. The value in ecx is used as target of
2028       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2029       // for tail calls on PIC/GOT architectures. Normally we would just put the
2030       // address of GOT into ebx and then call target@PLT. But for tail calls
2031       // ebx would be restored (since ebx is callee saved) before jumping to the
2032       // target@PLT.
2033
2034       // Note: The actual moving to ECX is done further down.
2035       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2036       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2037           !G->getGlobal()->hasProtectedVisibility())
2038         Callee = LowerGlobalAddress(Callee, DAG);
2039       else if (isa<ExternalSymbolSDNode>(Callee))
2040         Callee = LowerExternalSymbol(Callee, DAG);
2041     }
2042   }
2043
2044   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2045     // From AMD64 ABI document:
2046     // For calls that may call functions that use varargs or stdargs
2047     // (prototype-less calls or calls to functions containing ellipsis (...) in
2048     // the declaration) %al is used as hidden argument to specify the number
2049     // of SSE registers used. The contents of %al do not need to match exactly
2050     // the number of registers, but must be an ubound on the number of SSE
2051     // registers used and is in the range 0 - 8 inclusive.
2052
2053     // Count the number of XMM registers allocated.
2054     static const unsigned XMMArgRegs[] = {
2055       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2056       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2057     };
2058     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2059     assert((Subtarget->hasXMM() || !NumXMMRegs)
2060            && "SSE registers cannot be used when SSE is disabled");
2061
2062     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2063                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2064     InFlag = Chain.getValue(1);
2065   }
2066
2067
2068   // For tail calls lower the arguments to the 'real' stack slot.
2069   if (isTailCall) {
2070     // Force all the incoming stack arguments to be loaded from the stack
2071     // before any new outgoing arguments are stored to the stack, because the
2072     // outgoing stack slots may alias the incoming argument stack slots, and
2073     // the alias isn't otherwise explicit. This is slightly more conservative
2074     // than necessary, because it means that each store effectively depends
2075     // on every argument instead of just those arguments it would clobber.
2076     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2077
2078     SmallVector<SDValue, 8> MemOpChains2;
2079     SDValue FIN;
2080     int FI = 0;
2081     // Do not flag preceeding copytoreg stuff together with the following stuff.
2082     InFlag = SDValue();
2083     if (GuaranteedTailCallOpt) {
2084       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2085         CCValAssign &VA = ArgLocs[i];
2086         if (VA.isRegLoc())
2087           continue;
2088         assert(VA.isMemLoc());
2089         SDValue Arg = OutVals[i];
2090         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2091         // Create frame index.
2092         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2093         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2094         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2095         FIN = DAG.getFrameIndex(FI, getPointerTy());
2096
2097         if (Flags.isByVal()) {
2098           // Copy relative to framepointer.
2099           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2100           if (StackPtr.getNode() == 0)
2101             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2102                                           getPointerTy());
2103           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2104
2105           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2106                                                            ArgChain,
2107                                                            Flags, DAG, dl));
2108         } else {
2109           // Store relative to framepointer.
2110           MemOpChains2.push_back(
2111             DAG.getStore(ArgChain, dl, Arg, FIN,
2112                          MachinePointerInfo::getFixedStack(FI),
2113                          false, false, 0));
2114         }
2115       }
2116     }
2117
2118     if (!MemOpChains2.empty())
2119       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2120                           &MemOpChains2[0], MemOpChains2.size());
2121
2122     // Copy arguments to their registers.
2123     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2124       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2125                                RegsToPass[i].second, InFlag);
2126       InFlag = Chain.getValue(1);
2127     }
2128     InFlag =SDValue();
2129
2130     // Store the return address to the appropriate stack slot.
2131     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2132                                      FPDiff, dl);
2133   }
2134
2135   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2136     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2137     // In the 64-bit large code model, we have to make all calls
2138     // through a register, since the call instruction's 32-bit
2139     // pc-relative offset may not be large enough to hold the whole
2140     // address.
2141   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2142     // If the callee is a GlobalAddress node (quite common, every direct call
2143     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2144     // it.
2145
2146     // We should use extra load for direct calls to dllimported functions in
2147     // non-JIT mode.
2148     const GlobalValue *GV = G->getGlobal();
2149     if (!GV->hasDLLImportLinkage()) {
2150       unsigned char OpFlags = 0;
2151
2152       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2153       // external symbols most go through the PLT in PIC mode.  If the symbol
2154       // has hidden or protected visibility, or if it is static or local, then
2155       // we don't need to use the PLT - we can directly call it.
2156       if (Subtarget->isTargetELF() &&
2157           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2158           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2159         OpFlags = X86II::MO_PLT;
2160       } else if (Subtarget->isPICStyleStubAny() &&
2161                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2162                  Subtarget->getDarwinVers() < 9) {
2163         // PC-relative references to external symbols should go through $stub,
2164         // unless we're building with the leopard linker or later, which
2165         // automatically synthesizes these stubs.
2166         OpFlags = X86II::MO_DARWIN_STUB;
2167       }
2168
2169       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2170                                           G->getOffset(), OpFlags);
2171     }
2172   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2173     unsigned char OpFlags = 0;
2174
2175     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2176     // external symbols should go through the PLT.
2177     if (Subtarget->isTargetELF() &&
2178         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2179       OpFlags = X86II::MO_PLT;
2180     } else if (Subtarget->isPICStyleStubAny() &&
2181                Subtarget->getDarwinVers() < 9) {
2182       // PC-relative references to external symbols should go through $stub,
2183       // unless we're building with the leopard linker or later, which
2184       // automatically synthesizes these stubs.
2185       OpFlags = X86II::MO_DARWIN_STUB;
2186     }
2187
2188     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2189                                          OpFlags);
2190   }
2191
2192   // Returns a chain & a flag for retval copy to use.
2193   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2194   SmallVector<SDValue, 8> Ops;
2195
2196   if (!IsSibcall && isTailCall) {
2197     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2198                            DAG.getIntPtrConstant(0, true), InFlag);
2199     InFlag = Chain.getValue(1);
2200   }
2201
2202   Ops.push_back(Chain);
2203   Ops.push_back(Callee);
2204
2205   if (isTailCall)
2206     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2207
2208   // Add argument registers to the end of the list so that they are known live
2209   // into the call.
2210   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2211     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2212                                   RegsToPass[i].second.getValueType()));
2213
2214   // Add an implicit use GOT pointer in EBX.
2215   if (!isTailCall && Subtarget->isPICStyleGOT())
2216     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2217
2218   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2219   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2220     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2221
2222   if (InFlag.getNode())
2223     Ops.push_back(InFlag);
2224
2225   if (isTailCall) {
2226     // We used to do:
2227     //// If this is the first return lowered for this function, add the regs
2228     //// to the liveout set for the function.
2229     // This isn't right, although it's probably harmless on x86; liveouts
2230     // should be computed from returns not tail calls.  Consider a void
2231     // function making a tail call to a function returning int.
2232     return DAG.getNode(X86ISD::TC_RETURN, dl,
2233                        NodeTys, &Ops[0], Ops.size());
2234   }
2235
2236   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2237   InFlag = Chain.getValue(1);
2238
2239   // Create the CALLSEQ_END node.
2240   unsigned NumBytesForCalleeToPush;
2241   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2242     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2243   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2244     // If this is a call to a struct-return function, the callee
2245     // pops the hidden struct pointer, so we have to push it back.
2246     // This is common for Darwin/X86, Linux & Mingw32 targets.
2247     NumBytesForCalleeToPush = 4;
2248   else
2249     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2250
2251   // Returns a flag for retval copy to use.
2252   if (!IsSibcall) {
2253     Chain = DAG.getCALLSEQ_END(Chain,
2254                                DAG.getIntPtrConstant(NumBytes, true),
2255                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2256                                                      true),
2257                                InFlag);
2258     InFlag = Chain.getValue(1);
2259   }
2260
2261   // Handle result values, copying them out of physregs into vregs that we
2262   // return.
2263   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2264                          Ins, dl, DAG, InVals);
2265 }
2266
2267
2268 //===----------------------------------------------------------------------===//
2269 //                Fast Calling Convention (tail call) implementation
2270 //===----------------------------------------------------------------------===//
2271
2272 //  Like std call, callee cleans arguments, convention except that ECX is
2273 //  reserved for storing the tail called function address. Only 2 registers are
2274 //  free for argument passing (inreg). Tail call optimization is performed
2275 //  provided:
2276 //                * tailcallopt is enabled
2277 //                * caller/callee are fastcc
2278 //  On X86_64 architecture with GOT-style position independent code only local
2279 //  (within module) calls are supported at the moment.
2280 //  To keep the stack aligned according to platform abi the function
2281 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2282 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2283 //  If a tail called function callee has more arguments than the caller the
2284 //  caller needs to make sure that there is room to move the RETADDR to. This is
2285 //  achieved by reserving an area the size of the argument delta right after the
2286 //  original REtADDR, but before the saved framepointer or the spilled registers
2287 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2288 //  stack layout:
2289 //    arg1
2290 //    arg2
2291 //    RETADDR
2292 //    [ new RETADDR
2293 //      move area ]
2294 //    (possible EBP)
2295 //    ESI
2296 //    EDI
2297 //    local1 ..
2298
2299 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2300 /// for a 16 byte align requirement.
2301 unsigned
2302 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2303                                                SelectionDAG& DAG) const {
2304   MachineFunction &MF = DAG.getMachineFunction();
2305   const TargetMachine &TM = MF.getTarget();
2306   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2307   unsigned StackAlignment = TFI.getStackAlignment();
2308   uint64_t AlignMask = StackAlignment - 1;
2309   int64_t Offset = StackSize;
2310   uint64_t SlotSize = TD->getPointerSize();
2311   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2312     // Number smaller than 12 so just add the difference.
2313     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2314   } else {
2315     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2316     Offset = ((~AlignMask) & Offset) + StackAlignment +
2317       (StackAlignment-SlotSize);
2318   }
2319   return Offset;
2320 }
2321
2322 /// MatchingStackOffset - Return true if the given stack call argument is
2323 /// already available in the same position (relatively) of the caller's
2324 /// incoming argument stack.
2325 static
2326 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2327                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2328                          const X86InstrInfo *TII) {
2329   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2330   int FI = INT_MAX;
2331   if (Arg.getOpcode() == ISD::CopyFromReg) {
2332     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2333     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2334       return false;
2335     MachineInstr *Def = MRI->getVRegDef(VR);
2336     if (!Def)
2337       return false;
2338     if (!Flags.isByVal()) {
2339       if (!TII->isLoadFromStackSlot(Def, FI))
2340         return false;
2341     } else {
2342       unsigned Opcode = Def->getOpcode();
2343       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2344           Def->getOperand(1).isFI()) {
2345         FI = Def->getOperand(1).getIndex();
2346         Bytes = Flags.getByValSize();
2347       } else
2348         return false;
2349     }
2350   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2351     if (Flags.isByVal())
2352       // ByVal argument is passed in as a pointer but it's now being
2353       // dereferenced. e.g.
2354       // define @foo(%struct.X* %A) {
2355       //   tail call @bar(%struct.X* byval %A)
2356       // }
2357       return false;
2358     SDValue Ptr = Ld->getBasePtr();
2359     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2360     if (!FINode)
2361       return false;
2362     FI = FINode->getIndex();
2363   } else
2364     return false;
2365
2366   assert(FI != INT_MAX);
2367   if (!MFI->isFixedObjectIndex(FI))
2368     return false;
2369   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2370 }
2371
2372 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2373 /// for tail call optimization. Targets which want to do tail call
2374 /// optimization should implement this function.
2375 bool
2376 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2377                                                      CallingConv::ID CalleeCC,
2378                                                      bool isVarArg,
2379                                                      bool isCalleeStructRet,
2380                                                      bool isCallerStructRet,
2381                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2382                                     const SmallVectorImpl<SDValue> &OutVals,
2383                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2384                                                      SelectionDAG& DAG) const {
2385   if (!IsTailCallConvention(CalleeCC) &&
2386       CalleeCC != CallingConv::C)
2387     return false;
2388
2389   // If -tailcallopt is specified, make fastcc functions tail-callable.
2390   const MachineFunction &MF = DAG.getMachineFunction();
2391   const Function *CallerF = DAG.getMachineFunction().getFunction();
2392   CallingConv::ID CallerCC = CallerF->getCallingConv();
2393   bool CCMatch = CallerCC == CalleeCC;
2394
2395   if (GuaranteedTailCallOpt) {
2396     if (IsTailCallConvention(CalleeCC) && CCMatch)
2397       return true;
2398     return false;
2399   }
2400
2401   // Look for obvious safe cases to perform tail call optimization that do not
2402   // require ABI changes. This is what gcc calls sibcall.
2403
2404   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2405   // emit a special epilogue.
2406   if (RegInfo->needsStackRealignment(MF))
2407     return false;
2408
2409   // Do not sibcall optimize vararg calls unless the call site is not passing
2410   // any arguments.
2411   if (isVarArg && !Outs.empty())
2412     return false;
2413
2414   // Also avoid sibcall optimization if either caller or callee uses struct
2415   // return semantics.
2416   if (isCalleeStructRet || isCallerStructRet)
2417     return false;
2418
2419   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2420   // Therefore if it's not used by the call it is not safe to optimize this into
2421   // a sibcall.
2422   bool Unused = false;
2423   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2424     if (!Ins[i].Used) {
2425       Unused = true;
2426       break;
2427     }
2428   }
2429   if (Unused) {
2430     SmallVector<CCValAssign, 16> RVLocs;
2431     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2432                    RVLocs, *DAG.getContext());
2433     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2434     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2435       CCValAssign &VA = RVLocs[i];
2436       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2437         return false;
2438     }
2439   }
2440
2441   // If the calling conventions do not match, then we'd better make sure the
2442   // results are returned in the same way as what the caller expects.
2443   if (!CCMatch) {
2444     SmallVector<CCValAssign, 16> RVLocs1;
2445     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2446                     RVLocs1, *DAG.getContext());
2447     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2448
2449     SmallVector<CCValAssign, 16> RVLocs2;
2450     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2451                     RVLocs2, *DAG.getContext());
2452     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2453
2454     if (RVLocs1.size() != RVLocs2.size())
2455       return false;
2456     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2457       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2458         return false;
2459       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2460         return false;
2461       if (RVLocs1[i].isRegLoc()) {
2462         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2463           return false;
2464       } else {
2465         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2466           return false;
2467       }
2468     }
2469   }
2470
2471   // If the callee takes no arguments then go on to check the results of the
2472   // call.
2473   if (!Outs.empty()) {
2474     // Check if stack adjustment is needed. For now, do not do this if any
2475     // argument is passed on the stack.
2476     SmallVector<CCValAssign, 16> ArgLocs;
2477     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2478                    ArgLocs, *DAG.getContext());
2479     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2480     if (CCInfo.getNextStackOffset()) {
2481       MachineFunction &MF = DAG.getMachineFunction();
2482       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2483         return false;
2484       if (Subtarget->isTargetWin64())
2485         // Win64 ABI has additional complications.
2486         return false;
2487
2488       // Check if the arguments are already laid out in the right way as
2489       // the caller's fixed stack objects.
2490       MachineFrameInfo *MFI = MF.getFrameInfo();
2491       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2492       const X86InstrInfo *TII =
2493         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2494       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2495         CCValAssign &VA = ArgLocs[i];
2496         SDValue Arg = OutVals[i];
2497         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2498         if (VA.getLocInfo() == CCValAssign::Indirect)
2499           return false;
2500         if (!VA.isRegLoc()) {
2501           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2502                                    MFI, MRI, TII))
2503             return false;
2504         }
2505       }
2506     }
2507
2508     // If the tailcall address may be in a register, then make sure it's
2509     // possible to register allocate for it. In 32-bit, the call address can
2510     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2511     // callee-saved registers are restored. These happen to be the same
2512     // registers used to pass 'inreg' arguments so watch out for those.
2513     if (!Subtarget->is64Bit() &&
2514         !isa<GlobalAddressSDNode>(Callee) &&
2515         !isa<ExternalSymbolSDNode>(Callee)) {
2516       unsigned NumInRegs = 0;
2517       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2518         CCValAssign &VA = ArgLocs[i];
2519         if (!VA.isRegLoc())
2520           continue;
2521         unsigned Reg = VA.getLocReg();
2522         switch (Reg) {
2523         default: break;
2524         case X86::EAX: case X86::EDX: case X86::ECX:
2525           if (++NumInRegs == 3)
2526             return false;
2527           break;
2528         }
2529       }
2530     }
2531   }
2532
2533   // An stdcall caller is expected to clean up its arguments; the callee
2534   // isn't going to do that.
2535   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2536     return false;
2537
2538   return true;
2539 }
2540
2541 FastISel *
2542 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2543   return X86::createFastISel(funcInfo);
2544 }
2545
2546
2547 //===----------------------------------------------------------------------===//
2548 //                           Other Lowering Hooks
2549 //===----------------------------------------------------------------------===//
2550
2551 static bool MayFoldLoad(SDValue Op) {
2552   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2553 }
2554
2555 static bool MayFoldIntoStore(SDValue Op) {
2556   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2557 }
2558
2559 static bool isTargetShuffle(unsigned Opcode) {
2560   switch(Opcode) {
2561   default: return false;
2562   case X86ISD::PSHUFD:
2563   case X86ISD::PSHUFHW:
2564   case X86ISD::PSHUFLW:
2565   case X86ISD::SHUFPD:
2566   case X86ISD::PALIGN:
2567   case X86ISD::SHUFPS:
2568   case X86ISD::MOVLHPS:
2569   case X86ISD::MOVLHPD:
2570   case X86ISD::MOVHLPS:
2571   case X86ISD::MOVLPS:
2572   case X86ISD::MOVLPD:
2573   case X86ISD::MOVSHDUP:
2574   case X86ISD::MOVSLDUP:
2575   case X86ISD::MOVDDUP:
2576   case X86ISD::MOVSS:
2577   case X86ISD::MOVSD:
2578   case X86ISD::UNPCKLPS:
2579   case X86ISD::UNPCKLPD:
2580   case X86ISD::PUNPCKLWD:
2581   case X86ISD::PUNPCKLBW:
2582   case X86ISD::PUNPCKLDQ:
2583   case X86ISD::PUNPCKLQDQ:
2584   case X86ISD::UNPCKHPS:
2585   case X86ISD::UNPCKHPD:
2586   case X86ISD::PUNPCKHWD:
2587   case X86ISD::PUNPCKHBW:
2588   case X86ISD::PUNPCKHDQ:
2589   case X86ISD::PUNPCKHQDQ:
2590     return true;
2591   }
2592   return false;
2593 }
2594
2595 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2596                                                SDValue V1, SelectionDAG &DAG) {
2597   switch(Opc) {
2598   default: llvm_unreachable("Unknown x86 shuffle node");
2599   case X86ISD::MOVSHDUP:
2600   case X86ISD::MOVSLDUP:
2601   case X86ISD::MOVDDUP:
2602     return DAG.getNode(Opc, dl, VT, V1);
2603   }
2604
2605   return SDValue();
2606 }
2607
2608 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2609                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2610   switch(Opc) {
2611   default: llvm_unreachable("Unknown x86 shuffle node");
2612   case X86ISD::PSHUFD:
2613   case X86ISD::PSHUFHW:
2614   case X86ISD::PSHUFLW:
2615     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2616   }
2617
2618   return SDValue();
2619 }
2620
2621 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2622                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2623   switch(Opc) {
2624   default: llvm_unreachable("Unknown x86 shuffle node");
2625   case X86ISD::PALIGN:
2626   case X86ISD::SHUFPD:
2627   case X86ISD::SHUFPS:
2628     return DAG.getNode(Opc, dl, VT, V1, V2,
2629                        DAG.getConstant(TargetMask, MVT::i8));
2630   }
2631   return SDValue();
2632 }
2633
2634 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2635                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2636   switch(Opc) {
2637   default: llvm_unreachable("Unknown x86 shuffle node");
2638   case X86ISD::MOVLHPS:
2639   case X86ISD::MOVLHPD:
2640   case X86ISD::MOVHLPS:
2641   case X86ISD::MOVLPS:
2642   case X86ISD::MOVLPD:
2643   case X86ISD::MOVSS:
2644   case X86ISD::MOVSD:
2645   case X86ISD::UNPCKLPS:
2646   case X86ISD::UNPCKLPD:
2647   case X86ISD::PUNPCKLWD:
2648   case X86ISD::PUNPCKLBW:
2649   case X86ISD::PUNPCKLDQ:
2650   case X86ISD::PUNPCKLQDQ:
2651   case X86ISD::UNPCKHPS:
2652   case X86ISD::UNPCKHPD:
2653   case X86ISD::PUNPCKHWD:
2654   case X86ISD::PUNPCKHBW:
2655   case X86ISD::PUNPCKHDQ:
2656   case X86ISD::PUNPCKHQDQ:
2657     return DAG.getNode(Opc, dl, VT, V1, V2);
2658   }
2659   return SDValue();
2660 }
2661
2662 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2663   MachineFunction &MF = DAG.getMachineFunction();
2664   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2665   int ReturnAddrIndex = FuncInfo->getRAIndex();
2666
2667   if (ReturnAddrIndex == 0) {
2668     // Set up a frame object for the return address.
2669     uint64_t SlotSize = TD->getPointerSize();
2670     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2671                                                            false);
2672     FuncInfo->setRAIndex(ReturnAddrIndex);
2673   }
2674
2675   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2676 }
2677
2678
2679 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2680                                        bool hasSymbolicDisplacement) {
2681   // Offset should fit into 32 bit immediate field.
2682   if (!isInt<32>(Offset))
2683     return false;
2684
2685   // If we don't have a symbolic displacement - we don't have any extra
2686   // restrictions.
2687   if (!hasSymbolicDisplacement)
2688     return true;
2689
2690   // FIXME: Some tweaks might be needed for medium code model.
2691   if (M != CodeModel::Small && M != CodeModel::Kernel)
2692     return false;
2693
2694   // For small code model we assume that latest object is 16MB before end of 31
2695   // bits boundary. We may also accept pretty large negative constants knowing
2696   // that all objects are in the positive half of address space.
2697   if (M == CodeModel::Small && Offset < 16*1024*1024)
2698     return true;
2699
2700   // For kernel code model we know that all object resist in the negative half
2701   // of 32bits address space. We may not accept negative offsets, since they may
2702   // be just off and we may accept pretty large positive ones.
2703   if (M == CodeModel::Kernel && Offset > 0)
2704     return true;
2705
2706   return false;
2707 }
2708
2709 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2710 /// specific condition code, returning the condition code and the LHS/RHS of the
2711 /// comparison to make.
2712 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2713                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2714   if (!isFP) {
2715     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2716       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2717         // X > -1   -> X == 0, jump !sign.
2718         RHS = DAG.getConstant(0, RHS.getValueType());
2719         return X86::COND_NS;
2720       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2721         // X < 0   -> X == 0, jump on sign.
2722         return X86::COND_S;
2723       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2724         // X < 1   -> X <= 0
2725         RHS = DAG.getConstant(0, RHS.getValueType());
2726         return X86::COND_LE;
2727       }
2728     }
2729
2730     switch (SetCCOpcode) {
2731     default: llvm_unreachable("Invalid integer condition!");
2732     case ISD::SETEQ:  return X86::COND_E;
2733     case ISD::SETGT:  return X86::COND_G;
2734     case ISD::SETGE:  return X86::COND_GE;
2735     case ISD::SETLT:  return X86::COND_L;
2736     case ISD::SETLE:  return X86::COND_LE;
2737     case ISD::SETNE:  return X86::COND_NE;
2738     case ISD::SETULT: return X86::COND_B;
2739     case ISD::SETUGT: return X86::COND_A;
2740     case ISD::SETULE: return X86::COND_BE;
2741     case ISD::SETUGE: return X86::COND_AE;
2742     }
2743   }
2744
2745   // First determine if it is required or is profitable to flip the operands.
2746
2747   // If LHS is a foldable load, but RHS is not, flip the condition.
2748   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2749       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2750     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2751     std::swap(LHS, RHS);
2752   }
2753
2754   switch (SetCCOpcode) {
2755   default: break;
2756   case ISD::SETOLT:
2757   case ISD::SETOLE:
2758   case ISD::SETUGT:
2759   case ISD::SETUGE:
2760     std::swap(LHS, RHS);
2761     break;
2762   }
2763
2764   // On a floating point condition, the flags are set as follows:
2765   // ZF  PF  CF   op
2766   //  0 | 0 | 0 | X > Y
2767   //  0 | 0 | 1 | X < Y
2768   //  1 | 0 | 0 | X == Y
2769   //  1 | 1 | 1 | unordered
2770   switch (SetCCOpcode) {
2771   default: llvm_unreachable("Condcode should be pre-legalized away");
2772   case ISD::SETUEQ:
2773   case ISD::SETEQ:   return X86::COND_E;
2774   case ISD::SETOLT:              // flipped
2775   case ISD::SETOGT:
2776   case ISD::SETGT:   return X86::COND_A;
2777   case ISD::SETOLE:              // flipped
2778   case ISD::SETOGE:
2779   case ISD::SETGE:   return X86::COND_AE;
2780   case ISD::SETUGT:              // flipped
2781   case ISD::SETULT:
2782   case ISD::SETLT:   return X86::COND_B;
2783   case ISD::SETUGE:              // flipped
2784   case ISD::SETULE:
2785   case ISD::SETLE:   return X86::COND_BE;
2786   case ISD::SETONE:
2787   case ISD::SETNE:   return X86::COND_NE;
2788   case ISD::SETUO:   return X86::COND_P;
2789   case ISD::SETO:    return X86::COND_NP;
2790   case ISD::SETOEQ:
2791   case ISD::SETUNE:  return X86::COND_INVALID;
2792   }
2793 }
2794
2795 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2796 /// code. Current x86 isa includes the following FP cmov instructions:
2797 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2798 static bool hasFPCMov(unsigned X86CC) {
2799   switch (X86CC) {
2800   default:
2801     return false;
2802   case X86::COND_B:
2803   case X86::COND_BE:
2804   case X86::COND_E:
2805   case X86::COND_P:
2806   case X86::COND_A:
2807   case X86::COND_AE:
2808   case X86::COND_NE:
2809   case X86::COND_NP:
2810     return true;
2811   }
2812 }
2813
2814 /// isFPImmLegal - Returns true if the target can instruction select the
2815 /// specified FP immediate natively. If false, the legalizer will
2816 /// materialize the FP immediate as a load from a constant pool.
2817 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2818   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2819     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2820       return true;
2821   }
2822   return false;
2823 }
2824
2825 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2826 /// the specified range (L, H].
2827 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2828   return (Val < 0) || (Val >= Low && Val < Hi);
2829 }
2830
2831 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2832 /// specified value.
2833 static bool isUndefOrEqual(int Val, int CmpVal) {
2834   if (Val < 0 || Val == CmpVal)
2835     return true;
2836   return false;
2837 }
2838
2839 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2840 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2841 /// the second operand.
2842 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2843   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2844     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2845   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2846     return (Mask[0] < 2 && Mask[1] < 2);
2847   return false;
2848 }
2849
2850 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2851   SmallVector<int, 8> M;
2852   N->getMask(M);
2853   return ::isPSHUFDMask(M, N->getValueType(0));
2854 }
2855
2856 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2857 /// is suitable for input to PSHUFHW.
2858 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2859   if (VT != MVT::v8i16)
2860     return false;
2861
2862   // Lower quadword copied in order or undef.
2863   for (int i = 0; i != 4; ++i)
2864     if (Mask[i] >= 0 && Mask[i] != i)
2865       return false;
2866
2867   // Upper quadword shuffled.
2868   for (int i = 4; i != 8; ++i)
2869     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2870       return false;
2871
2872   return true;
2873 }
2874
2875 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2876   SmallVector<int, 8> M;
2877   N->getMask(M);
2878   return ::isPSHUFHWMask(M, N->getValueType(0));
2879 }
2880
2881 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2882 /// is suitable for input to PSHUFLW.
2883 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2884   if (VT != MVT::v8i16)
2885     return false;
2886
2887   // Upper quadword copied in order.
2888   for (int i = 4; i != 8; ++i)
2889     if (Mask[i] >= 0 && Mask[i] != i)
2890       return false;
2891
2892   // Lower quadword shuffled.
2893   for (int i = 0; i != 4; ++i)
2894     if (Mask[i] >= 4)
2895       return false;
2896
2897   return true;
2898 }
2899
2900 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2901   SmallVector<int, 8> M;
2902   N->getMask(M);
2903   return ::isPSHUFLWMask(M, N->getValueType(0));
2904 }
2905
2906 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2907 /// is suitable for input to PALIGNR.
2908 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2909                           bool hasSSSE3) {
2910   int i, e = VT.getVectorNumElements();
2911
2912   // Do not handle v2i64 / v2f64 shuffles with palignr.
2913   if (e < 4 || !hasSSSE3)
2914     return false;
2915
2916   for (i = 0; i != e; ++i)
2917     if (Mask[i] >= 0)
2918       break;
2919
2920   // All undef, not a palignr.
2921   if (i == e)
2922     return false;
2923
2924   // Determine if it's ok to perform a palignr with only the LHS, since we
2925   // don't have access to the actual shuffle elements to see if RHS is undef.
2926   bool Unary = Mask[i] < (int)e;
2927   bool NeedsUnary = false;
2928
2929   int s = Mask[i] - i;
2930
2931   // Check the rest of the elements to see if they are consecutive.
2932   for (++i; i != e; ++i) {
2933     int m = Mask[i];
2934     if (m < 0)
2935       continue;
2936
2937     Unary = Unary && (m < (int)e);
2938     NeedsUnary = NeedsUnary || (m < s);
2939
2940     if (NeedsUnary && !Unary)
2941       return false;
2942     if (Unary && m != ((s+i) & (e-1)))
2943       return false;
2944     if (!Unary && m != (s+i))
2945       return false;
2946   }
2947   return true;
2948 }
2949
2950 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2951   SmallVector<int, 8> M;
2952   N->getMask(M);
2953   return ::isPALIGNRMask(M, N->getValueType(0), true);
2954 }
2955
2956 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2957 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2958 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2959   int NumElems = VT.getVectorNumElements();
2960   if (NumElems != 2 && NumElems != 4)
2961     return false;
2962
2963   int Half = NumElems / 2;
2964   for (int i = 0; i < Half; ++i)
2965     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2966       return false;
2967   for (int i = Half; i < NumElems; ++i)
2968     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2969       return false;
2970
2971   return true;
2972 }
2973
2974 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2975   SmallVector<int, 8> M;
2976   N->getMask(M);
2977   return ::isSHUFPMask(M, N->getValueType(0));
2978 }
2979
2980 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2981 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2982 /// half elements to come from vector 1 (which would equal the dest.) and
2983 /// the upper half to come from vector 2.
2984 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2985   int NumElems = VT.getVectorNumElements();
2986
2987   if (NumElems != 2 && NumElems != 4)
2988     return false;
2989
2990   int Half = NumElems / 2;
2991   for (int i = 0; i < Half; ++i)
2992     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2993       return false;
2994   for (int i = Half; i < NumElems; ++i)
2995     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2996       return false;
2997   return true;
2998 }
2999
3000 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3001   SmallVector<int, 8> M;
3002   N->getMask(M);
3003   return isCommutedSHUFPMask(M, N->getValueType(0));
3004 }
3005
3006 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3007 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3008 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3009   if (N->getValueType(0).getVectorNumElements() != 4)
3010     return false;
3011
3012   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3013   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3014          isUndefOrEqual(N->getMaskElt(1), 7) &&
3015          isUndefOrEqual(N->getMaskElt(2), 2) &&
3016          isUndefOrEqual(N->getMaskElt(3), 3);
3017 }
3018
3019 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3020 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3021 /// <2, 3, 2, 3>
3022 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3023   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3024
3025   if (NumElems != 4)
3026     return false;
3027
3028   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3029   isUndefOrEqual(N->getMaskElt(1), 3) &&
3030   isUndefOrEqual(N->getMaskElt(2), 2) &&
3031   isUndefOrEqual(N->getMaskElt(3), 3);
3032 }
3033
3034 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3035 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3036 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3037   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3038
3039   if (NumElems != 2 && NumElems != 4)
3040     return false;
3041
3042   for (unsigned i = 0; i < NumElems/2; ++i)
3043     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3044       return false;
3045
3046   for (unsigned i = NumElems/2; i < NumElems; ++i)
3047     if (!isUndefOrEqual(N->getMaskElt(i), i))
3048       return false;
3049
3050   return true;
3051 }
3052
3053 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3054 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3055 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3056   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3057
3058   if (NumElems != 2 && NumElems != 4)
3059     return false;
3060
3061   for (unsigned i = 0; i < NumElems/2; ++i)
3062     if (!isUndefOrEqual(N->getMaskElt(i), i))
3063       return false;
3064
3065   for (unsigned i = 0; i < NumElems/2; ++i)
3066     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3067       return false;
3068
3069   return true;
3070 }
3071
3072 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3073 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3074 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3075                          bool V2IsSplat = false) {
3076   int NumElts = VT.getVectorNumElements();
3077   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3078     return false;
3079
3080   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3081     int BitI  = Mask[i];
3082     int BitI1 = Mask[i+1];
3083     if (!isUndefOrEqual(BitI, j))
3084       return false;
3085     if (V2IsSplat) {
3086       if (!isUndefOrEqual(BitI1, NumElts))
3087         return false;
3088     } else {
3089       if (!isUndefOrEqual(BitI1, j + NumElts))
3090         return false;
3091     }
3092   }
3093   return true;
3094 }
3095
3096 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3097   SmallVector<int, 8> M;
3098   N->getMask(M);
3099   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3100 }
3101
3102 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3103 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3104 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3105                          bool V2IsSplat = false) {
3106   int NumElts = VT.getVectorNumElements();
3107   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3108     return false;
3109
3110   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3111     int BitI  = Mask[i];
3112     int BitI1 = Mask[i+1];
3113     if (!isUndefOrEqual(BitI, j + NumElts/2))
3114       return false;
3115     if (V2IsSplat) {
3116       if (isUndefOrEqual(BitI1, NumElts))
3117         return false;
3118     } else {
3119       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3120         return false;
3121     }
3122   }
3123   return true;
3124 }
3125
3126 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3127   SmallVector<int, 8> M;
3128   N->getMask(M);
3129   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3130 }
3131
3132 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3133 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3134 /// <0, 0, 1, 1>
3135 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3136   int NumElems = VT.getVectorNumElements();
3137   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3138     return false;
3139
3140   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3141     int BitI  = Mask[i];
3142     int BitI1 = Mask[i+1];
3143     if (!isUndefOrEqual(BitI, j))
3144       return false;
3145     if (!isUndefOrEqual(BitI1, j))
3146       return false;
3147   }
3148   return true;
3149 }
3150
3151 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3152   SmallVector<int, 8> M;
3153   N->getMask(M);
3154   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3155 }
3156
3157 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3158 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3159 /// <2, 2, 3, 3>
3160 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3161   int NumElems = VT.getVectorNumElements();
3162   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3163     return false;
3164
3165   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3166     int BitI  = Mask[i];
3167     int BitI1 = Mask[i+1];
3168     if (!isUndefOrEqual(BitI, j))
3169       return false;
3170     if (!isUndefOrEqual(BitI1, j))
3171       return false;
3172   }
3173   return true;
3174 }
3175
3176 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3177   SmallVector<int, 8> M;
3178   N->getMask(M);
3179   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3180 }
3181
3182 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3183 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3184 /// MOVSD, and MOVD, i.e. setting the lowest element.
3185 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3186   if (VT.getVectorElementType().getSizeInBits() < 32)
3187     return false;
3188
3189   int NumElts = VT.getVectorNumElements();
3190
3191   if (!isUndefOrEqual(Mask[0], NumElts))
3192     return false;
3193
3194   for (int i = 1; i < NumElts; ++i)
3195     if (!isUndefOrEqual(Mask[i], i))
3196       return false;
3197
3198   return true;
3199 }
3200
3201 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3202   SmallVector<int, 8> M;
3203   N->getMask(M);
3204   return ::isMOVLMask(M, N->getValueType(0));
3205 }
3206
3207 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3208 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3209 /// element of vector 2 and the other elements to come from vector 1 in order.
3210 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3211                                bool V2IsSplat = false, bool V2IsUndef = false) {
3212   int NumOps = VT.getVectorNumElements();
3213   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3214     return false;
3215
3216   if (!isUndefOrEqual(Mask[0], 0))
3217     return false;
3218
3219   for (int i = 1; i < NumOps; ++i)
3220     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3221           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3222           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3223       return false;
3224
3225   return true;
3226 }
3227
3228 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3229                            bool V2IsUndef = false) {
3230   SmallVector<int, 8> M;
3231   N->getMask(M);
3232   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3233 }
3234
3235 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3236 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3237 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3238   if (N->getValueType(0).getVectorNumElements() != 4)
3239     return false;
3240
3241   // Expect 1, 1, 3, 3
3242   for (unsigned i = 0; i < 2; ++i) {
3243     int Elt = N->getMaskElt(i);
3244     if (Elt >= 0 && Elt != 1)
3245       return false;
3246   }
3247
3248   bool HasHi = false;
3249   for (unsigned i = 2; i < 4; ++i) {
3250     int Elt = N->getMaskElt(i);
3251     if (Elt >= 0 && Elt != 3)
3252       return false;
3253     if (Elt == 3)
3254       HasHi = true;
3255   }
3256   // Don't use movshdup if it can be done with a shufps.
3257   // FIXME: verify that matching u, u, 3, 3 is what we want.
3258   return HasHi;
3259 }
3260
3261 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3262 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3263 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3264   if (N->getValueType(0).getVectorNumElements() != 4)
3265     return false;
3266
3267   // Expect 0, 0, 2, 2
3268   for (unsigned i = 0; i < 2; ++i)
3269     if (N->getMaskElt(i) > 0)
3270       return false;
3271
3272   bool HasHi = false;
3273   for (unsigned i = 2; i < 4; ++i) {
3274     int Elt = N->getMaskElt(i);
3275     if (Elt >= 0 && Elt != 2)
3276       return false;
3277     if (Elt == 2)
3278       HasHi = true;
3279   }
3280   // Don't use movsldup if it can be done with a shufps.
3281   return HasHi;
3282 }
3283
3284 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3285 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3286 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3287   int e = N->getValueType(0).getVectorNumElements() / 2;
3288
3289   for (int i = 0; i < e; ++i)
3290     if (!isUndefOrEqual(N->getMaskElt(i), i))
3291       return false;
3292   for (int i = 0; i < e; ++i)
3293     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3294       return false;
3295   return true;
3296 }
3297
3298 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3299 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3300 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3302   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3303
3304   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3305   unsigned Mask = 0;
3306   for (int i = 0; i < NumOperands; ++i) {
3307     int Val = SVOp->getMaskElt(NumOperands-i-1);
3308     if (Val < 0) Val = 0;
3309     if (Val >= NumOperands) Val -= NumOperands;
3310     Mask |= Val;
3311     if (i != NumOperands - 1)
3312       Mask <<= Shift;
3313   }
3314   return Mask;
3315 }
3316
3317 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3318 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3319 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3321   unsigned Mask = 0;
3322   // 8 nodes, but we only care about the last 4.
3323   for (unsigned i = 7; i >= 4; --i) {
3324     int Val = SVOp->getMaskElt(i);
3325     if (Val >= 0)
3326       Mask |= (Val - 4);
3327     if (i != 4)
3328       Mask <<= 2;
3329   }
3330   return Mask;
3331 }
3332
3333 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3334 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3335 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3336   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3337   unsigned Mask = 0;
3338   // 8 nodes, but we only care about the first 4.
3339   for (int i = 3; i >= 0; --i) {
3340     int Val = SVOp->getMaskElt(i);
3341     if (Val >= 0)
3342       Mask |= Val;
3343     if (i != 0)
3344       Mask <<= 2;
3345   }
3346   return Mask;
3347 }
3348
3349 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3350 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3351 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3352   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3353   EVT VVT = N->getValueType(0);
3354   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3355   int Val = 0;
3356
3357   unsigned i, e;
3358   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3359     Val = SVOp->getMaskElt(i);
3360     if (Val >= 0)
3361       break;
3362   }
3363   return (Val - i) * EltSize;
3364 }
3365
3366 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3367 /// constant +0.0.
3368 bool X86::isZeroNode(SDValue Elt) {
3369   return ((isa<ConstantSDNode>(Elt) &&
3370            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3371           (isa<ConstantFPSDNode>(Elt) &&
3372            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3373 }
3374
3375 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3376 /// their permute mask.
3377 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3378                                     SelectionDAG &DAG) {
3379   EVT VT = SVOp->getValueType(0);
3380   unsigned NumElems = VT.getVectorNumElements();
3381   SmallVector<int, 8> MaskVec;
3382
3383   for (unsigned i = 0; i != NumElems; ++i) {
3384     int idx = SVOp->getMaskElt(i);
3385     if (idx < 0)
3386       MaskVec.push_back(idx);
3387     else if (idx < (int)NumElems)
3388       MaskVec.push_back(idx + NumElems);
3389     else
3390       MaskVec.push_back(idx - NumElems);
3391   }
3392   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3393                               SVOp->getOperand(0), &MaskVec[0]);
3394 }
3395
3396 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3397 /// the two vector operands have swapped position.
3398 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3399   unsigned NumElems = VT.getVectorNumElements();
3400   for (unsigned i = 0; i != NumElems; ++i) {
3401     int idx = Mask[i];
3402     if (idx < 0)
3403       continue;
3404     else if (idx < (int)NumElems)
3405       Mask[i] = idx + NumElems;
3406     else
3407       Mask[i] = idx - NumElems;
3408   }
3409 }
3410
3411 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3412 /// match movhlps. The lower half elements should come from upper half of
3413 /// V1 (and in order), and the upper half elements should come from the upper
3414 /// half of V2 (and in order).
3415 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3416   if (Op->getValueType(0).getVectorNumElements() != 4)
3417     return false;
3418   for (unsigned i = 0, e = 2; i != e; ++i)
3419     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3420       return false;
3421   for (unsigned i = 2; i != 4; ++i)
3422     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3423       return false;
3424   return true;
3425 }
3426
3427 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3428 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3429 /// required.
3430 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3431   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3432     return false;
3433   N = N->getOperand(0).getNode();
3434   if (!ISD::isNON_EXTLoad(N))
3435     return false;
3436   if (LD)
3437     *LD = cast<LoadSDNode>(N);
3438   return true;
3439 }
3440
3441 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3442 /// match movlp{s|d}. The lower half elements should come from lower half of
3443 /// V1 (and in order), and the upper half elements should come from the upper
3444 /// half of V2 (and in order). And since V1 will become the source of the
3445 /// MOVLP, it must be either a vector load or a scalar load to vector.
3446 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3447                                ShuffleVectorSDNode *Op) {
3448   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3449     return false;
3450   // Is V2 is a vector load, don't do this transformation. We will try to use
3451   // load folding shufps op.
3452   if (ISD::isNON_EXTLoad(V2))
3453     return false;
3454
3455   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3456
3457   if (NumElems != 2 && NumElems != 4)
3458     return false;
3459   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3460     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3461       return false;
3462   for (unsigned i = NumElems/2; i != NumElems; ++i)
3463     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3464       return false;
3465   return true;
3466 }
3467
3468 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3469 /// all the same.
3470 static bool isSplatVector(SDNode *N) {
3471   if (N->getOpcode() != ISD::BUILD_VECTOR)
3472     return false;
3473
3474   SDValue SplatValue = N->getOperand(0);
3475   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3476     if (N->getOperand(i) != SplatValue)
3477       return false;
3478   return true;
3479 }
3480
3481 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3482 /// to an zero vector.
3483 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3484 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3485   SDValue V1 = N->getOperand(0);
3486   SDValue V2 = N->getOperand(1);
3487   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3488   for (unsigned i = 0; i != NumElems; ++i) {
3489     int Idx = N->getMaskElt(i);
3490     if (Idx >= (int)NumElems) {
3491       unsigned Opc = V2.getOpcode();
3492       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3493         continue;
3494       if (Opc != ISD::BUILD_VECTOR ||
3495           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3496         return false;
3497     } else if (Idx >= 0) {
3498       unsigned Opc = V1.getOpcode();
3499       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3500         continue;
3501       if (Opc != ISD::BUILD_VECTOR ||
3502           !X86::isZeroNode(V1.getOperand(Idx)))
3503         return false;
3504     }
3505   }
3506   return true;
3507 }
3508
3509 /// getZeroVector - Returns a vector of specified type with all zero elements.
3510 ///
3511 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3512                              DebugLoc dl) {
3513   assert(VT.isVector() && "Expected a vector type");
3514
3515   // Always build SSE zero vectors as <4 x i32> bitcasted
3516   // to their dest type. This ensures they get CSE'd.
3517   SDValue Vec;
3518   if (VT.getSizeInBits() == 128) {  // SSE
3519     if (HasSSE2) {  // SSE2
3520       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3521       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3522     } else { // SSE1
3523       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3524       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3525     }
3526   } else if (VT.getSizeInBits() == 256) { // AVX
3527     // 256-bit logic and arithmetic instructions in AVX are
3528     // all floating-point, no support for integer ops. Default
3529     // to emitting fp zeroed vectors then.
3530     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3531     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3532     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3533   }
3534   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3535 }
3536
3537 /// getOnesVector - Returns a vector of specified type with all bits set.
3538 ///
3539 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3540   assert(VT.isVector() && "Expected a vector type");
3541
3542   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3543   // type.  This ensures they get CSE'd.
3544   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3545   SDValue Vec;
3546   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3547   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3548 }
3549
3550
3551 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3552 /// that point to V2 points to its first element.
3553 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3554   EVT VT = SVOp->getValueType(0);
3555   unsigned NumElems = VT.getVectorNumElements();
3556
3557   bool Changed = false;
3558   SmallVector<int, 8> MaskVec;
3559   SVOp->getMask(MaskVec);
3560
3561   for (unsigned i = 0; i != NumElems; ++i) {
3562     if (MaskVec[i] > (int)NumElems) {
3563       MaskVec[i] = NumElems;
3564       Changed = true;
3565     }
3566   }
3567   if (Changed)
3568     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3569                                 SVOp->getOperand(1), &MaskVec[0]);
3570   return SDValue(SVOp, 0);
3571 }
3572
3573 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3574 /// operation of specified width.
3575 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3576                        SDValue V2) {
3577   unsigned NumElems = VT.getVectorNumElements();
3578   SmallVector<int, 8> Mask;
3579   Mask.push_back(NumElems);
3580   for (unsigned i = 1; i != NumElems; ++i)
3581     Mask.push_back(i);
3582   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3583 }
3584
3585 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3586 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3587                           SDValue V2) {
3588   unsigned NumElems = VT.getVectorNumElements();
3589   SmallVector<int, 8> Mask;
3590   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3591     Mask.push_back(i);
3592     Mask.push_back(i + NumElems);
3593   }
3594   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3595 }
3596
3597 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3598 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3599                           SDValue V2) {
3600   unsigned NumElems = VT.getVectorNumElements();
3601   unsigned Half = NumElems/2;
3602   SmallVector<int, 8> Mask;
3603   for (unsigned i = 0; i != Half; ++i) {
3604     Mask.push_back(i + Half);
3605     Mask.push_back(i + NumElems + Half);
3606   }
3607   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3608 }
3609
3610 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3611 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3612   EVT PVT = MVT::v4f32;
3613   EVT VT = SV->getValueType(0);
3614   DebugLoc dl = SV->getDebugLoc();
3615   SDValue V1 = SV->getOperand(0);
3616   int NumElems = VT.getVectorNumElements();
3617   int EltNo = SV->getSplatIndex();
3618
3619   // unpack elements to the correct location
3620   while (NumElems > 4) {
3621     if (EltNo < NumElems/2) {
3622       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3623     } else {
3624       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3625       EltNo -= NumElems/2;
3626     }
3627     NumElems >>= 1;
3628   }
3629
3630   // Perform the splat.
3631   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3632   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3633   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3634   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3635 }
3636
3637 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3638 /// vector of zero or undef vector.  This produces a shuffle where the low
3639 /// element of V2 is swizzled into the zero/undef vector, landing at element
3640 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3641 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3642                                              bool isZero, bool HasSSE2,
3643                                              SelectionDAG &DAG) {
3644   EVT VT = V2.getValueType();
3645   SDValue V1 = isZero
3646     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3647   unsigned NumElems = VT.getVectorNumElements();
3648   SmallVector<int, 16> MaskVec;
3649   for (unsigned i = 0; i != NumElems; ++i)
3650     // If this is the insertion idx, put the low elt of V2 here.
3651     MaskVec.push_back(i == Idx ? NumElems : i);
3652   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3653 }
3654
3655 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3656 /// element of the result of the vector shuffle.
3657 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3658                             unsigned Depth) {
3659   if (Depth == 6)
3660     return SDValue();  // Limit search depth.
3661
3662   SDValue V = SDValue(N, 0);
3663   EVT VT = V.getValueType();
3664   unsigned Opcode = V.getOpcode();
3665
3666   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3667   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3668     Index = SV->getMaskElt(Index);
3669
3670     if (Index < 0)
3671       return DAG.getUNDEF(VT.getVectorElementType());
3672
3673     int NumElems = VT.getVectorNumElements();
3674     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3675     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3676   }
3677
3678   // Recurse into target specific vector shuffles to find scalars.
3679   if (isTargetShuffle(Opcode)) {
3680     int NumElems = VT.getVectorNumElements();
3681     SmallVector<unsigned, 16> ShuffleMask;
3682     SDValue ImmN;
3683
3684     switch(Opcode) {
3685     case X86ISD::SHUFPS:
3686     case X86ISD::SHUFPD:
3687       ImmN = N->getOperand(N->getNumOperands()-1);
3688       DecodeSHUFPSMask(NumElems,
3689                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3690                        ShuffleMask);
3691       break;
3692     case X86ISD::PUNPCKHBW:
3693     case X86ISD::PUNPCKHWD:
3694     case X86ISD::PUNPCKHDQ:
3695     case X86ISD::PUNPCKHQDQ:
3696       DecodePUNPCKHMask(NumElems, ShuffleMask);
3697       break;
3698     case X86ISD::UNPCKHPS:
3699     case X86ISD::UNPCKHPD:
3700       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3701       break;
3702     case X86ISD::PUNPCKLBW:
3703     case X86ISD::PUNPCKLWD:
3704     case X86ISD::PUNPCKLDQ:
3705     case X86ISD::PUNPCKLQDQ:
3706       DecodePUNPCKLMask(NumElems, ShuffleMask);
3707       break;
3708     case X86ISD::UNPCKLPS:
3709     case X86ISD::UNPCKLPD:
3710       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3711       break;
3712     case X86ISD::MOVHLPS:
3713       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3714       break;
3715     case X86ISD::MOVLHPS:
3716       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3717       break;
3718     case X86ISD::PSHUFD:
3719       ImmN = N->getOperand(N->getNumOperands()-1);
3720       DecodePSHUFMask(NumElems,
3721                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3722                       ShuffleMask);
3723       break;
3724     case X86ISD::PSHUFHW:
3725       ImmN = N->getOperand(N->getNumOperands()-1);
3726       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3727                         ShuffleMask);
3728       break;
3729     case X86ISD::PSHUFLW:
3730       ImmN = N->getOperand(N->getNumOperands()-1);
3731       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3732                         ShuffleMask);
3733       break;
3734     case X86ISD::MOVSS:
3735     case X86ISD::MOVSD: {
3736       // The index 0 always comes from the first element of the second source,
3737       // this is why MOVSS and MOVSD are used in the first place. The other
3738       // elements come from the other positions of the first source vector.
3739       unsigned OpNum = (Index == 0) ? 1 : 0;
3740       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3741                                  Depth+1);
3742     }
3743     default:
3744       assert("not implemented for target shuffle node");
3745       return SDValue();
3746     }
3747
3748     Index = ShuffleMask[Index];
3749     if (Index < 0)
3750       return DAG.getUNDEF(VT.getVectorElementType());
3751
3752     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3753     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3754                                Depth+1);
3755   }
3756
3757   // Actual nodes that may contain scalar elements
3758   if (Opcode == ISD::BITCAST) {
3759     V = V.getOperand(0);
3760     EVT SrcVT = V.getValueType();
3761     unsigned NumElems = VT.getVectorNumElements();
3762
3763     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3764       return SDValue();
3765   }
3766
3767   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3768     return (Index == 0) ? V.getOperand(0)
3769                           : DAG.getUNDEF(VT.getVectorElementType());
3770
3771   if (V.getOpcode() == ISD::BUILD_VECTOR)
3772     return V.getOperand(Index);
3773
3774   return SDValue();
3775 }
3776
3777 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3778 /// shuffle operation which come from a consecutively from a zero. The
3779 /// search can start in two diferent directions, from left or right.
3780 static
3781 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3782                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3783   int i = 0;
3784
3785   while (i < NumElems) {
3786     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3787     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3788     if (!(Elt.getNode() &&
3789          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3790       break;
3791     ++i;
3792   }
3793
3794   return i;
3795 }
3796
3797 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3798 /// MaskE correspond consecutively to elements from one of the vector operands,
3799 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3800 static
3801 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3802                               int OpIdx, int NumElems, unsigned &OpNum) {
3803   bool SeenV1 = false;
3804   bool SeenV2 = false;
3805
3806   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3807     int Idx = SVOp->getMaskElt(i);
3808     // Ignore undef indicies
3809     if (Idx < 0)
3810       continue;
3811
3812     if (Idx < NumElems)
3813       SeenV1 = true;
3814     else
3815       SeenV2 = true;
3816
3817     // Only accept consecutive elements from the same vector
3818     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3819       return false;
3820   }
3821
3822   OpNum = SeenV1 ? 0 : 1;
3823   return true;
3824 }
3825
3826 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3827 /// logical left shift of a vector.
3828 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3829                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3830   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3831   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3832               false /* check zeros from right */, DAG);
3833   unsigned OpSrc;
3834
3835   if (!NumZeros)
3836     return false;
3837
3838   // Considering the elements in the mask that are not consecutive zeros,
3839   // check if they consecutively come from only one of the source vectors.
3840   //
3841   //               V1 = {X, A, B, C}     0
3842   //                         \  \  \    /
3843   //   vector_shuffle V1, V2 <1, 2, 3, X>
3844   //
3845   if (!isShuffleMaskConsecutive(SVOp,
3846             0,                   // Mask Start Index
3847             NumElems-NumZeros-1, // Mask End Index
3848             NumZeros,            // Where to start looking in the src vector
3849             NumElems,            // Number of elements in vector
3850             OpSrc))              // Which source operand ?
3851     return false;
3852
3853   isLeft = false;
3854   ShAmt = NumZeros;
3855   ShVal = SVOp->getOperand(OpSrc);
3856   return true;
3857 }
3858
3859 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3860 /// logical left shift of a vector.
3861 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3862                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3863   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3864   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3865               true /* check zeros from left */, DAG);
3866   unsigned OpSrc;
3867
3868   if (!NumZeros)
3869     return false;
3870
3871   // Considering the elements in the mask that are not consecutive zeros,
3872   // check if they consecutively come from only one of the source vectors.
3873   //
3874   //                           0    { A, B, X, X } = V2
3875   //                          / \    /  /
3876   //   vector_shuffle V1, V2 <X, X, 4, 5>
3877   //
3878   if (!isShuffleMaskConsecutive(SVOp,
3879             NumZeros,     // Mask Start Index
3880             NumElems-1,   // Mask End Index
3881             0,            // Where to start looking in the src vector
3882             NumElems,     // Number of elements in vector
3883             OpSrc))       // Which source operand ?
3884     return false;
3885
3886   isLeft = true;
3887   ShAmt = NumZeros;
3888   ShVal = SVOp->getOperand(OpSrc);
3889   return true;
3890 }
3891
3892 /// isVectorShift - Returns true if the shuffle can be implemented as a
3893 /// logical left or right shift of a vector.
3894 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3895                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3896   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3897       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3898     return true;
3899
3900   return false;
3901 }
3902
3903 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3904 ///
3905 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3906                                        unsigned NumNonZero, unsigned NumZero,
3907                                        SelectionDAG &DAG,
3908                                        const TargetLowering &TLI) {
3909   if (NumNonZero > 8)
3910     return SDValue();
3911
3912   DebugLoc dl = Op.getDebugLoc();
3913   SDValue V(0, 0);
3914   bool First = true;
3915   for (unsigned i = 0; i < 16; ++i) {
3916     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3917     if (ThisIsNonZero && First) {
3918       if (NumZero)
3919         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3920       else
3921         V = DAG.getUNDEF(MVT::v8i16);
3922       First = false;
3923     }
3924
3925     if ((i & 1) != 0) {
3926       SDValue ThisElt(0, 0), LastElt(0, 0);
3927       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3928       if (LastIsNonZero) {
3929         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3930                               MVT::i16, Op.getOperand(i-1));
3931       }
3932       if (ThisIsNonZero) {
3933         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3934         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3935                               ThisElt, DAG.getConstant(8, MVT::i8));
3936         if (LastIsNonZero)
3937           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3938       } else
3939         ThisElt = LastElt;
3940
3941       if (ThisElt.getNode())
3942         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3943                         DAG.getIntPtrConstant(i/2));
3944     }
3945   }
3946
3947   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3948 }
3949
3950 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3951 ///
3952 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3953                                      unsigned NumNonZero, unsigned NumZero,
3954                                      SelectionDAG &DAG,
3955                                      const TargetLowering &TLI) {
3956   if (NumNonZero > 4)
3957     return SDValue();
3958
3959   DebugLoc dl = Op.getDebugLoc();
3960   SDValue V(0, 0);
3961   bool First = true;
3962   for (unsigned i = 0; i < 8; ++i) {
3963     bool isNonZero = (NonZeros & (1 << i)) != 0;
3964     if (isNonZero) {
3965       if (First) {
3966         if (NumZero)
3967           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3968         else
3969           V = DAG.getUNDEF(MVT::v8i16);
3970         First = false;
3971       }
3972       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3973                       MVT::v8i16, V, Op.getOperand(i),
3974                       DAG.getIntPtrConstant(i));
3975     }
3976   }
3977
3978   return V;
3979 }
3980
3981 /// getVShift - Return a vector logical shift node.
3982 ///
3983 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3984                          unsigned NumBits, SelectionDAG &DAG,
3985                          const TargetLowering &TLI, DebugLoc dl) {
3986   EVT ShVT = MVT::v2i64;
3987   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3988   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3989   return DAG.getNode(ISD::BITCAST, dl, VT,
3990                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3991                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3992 }
3993
3994 SDValue
3995 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3996                                           SelectionDAG &DAG) const {
3997
3998   // Check if the scalar load can be widened into a vector load. And if
3999   // the address is "base + cst" see if the cst can be "absorbed" into
4000   // the shuffle mask.
4001   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4002     SDValue Ptr = LD->getBasePtr();
4003     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4004       return SDValue();
4005     EVT PVT = LD->getValueType(0);
4006     if (PVT != MVT::i32 && PVT != MVT::f32)
4007       return SDValue();
4008
4009     int FI = -1;
4010     int64_t Offset = 0;
4011     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4012       FI = FINode->getIndex();
4013       Offset = 0;
4014     } else if (Ptr.getOpcode() == ISD::ADD &&
4015                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4016                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4017       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4018       Offset = Ptr.getConstantOperandVal(1);
4019       Ptr = Ptr.getOperand(0);
4020     } else {
4021       return SDValue();
4022     }
4023
4024     SDValue Chain = LD->getChain();
4025     // Make sure the stack object alignment is at least 16.
4026     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4027     if (DAG.InferPtrAlignment(Ptr) < 16) {
4028       if (MFI->isFixedObjectIndex(FI)) {
4029         // Can't change the alignment. FIXME: It's possible to compute
4030         // the exact stack offset and reference FI + adjust offset instead.
4031         // If someone *really* cares about this. That's the way to implement it.
4032         return SDValue();
4033       } else {
4034         MFI->setObjectAlignment(FI, 16);
4035       }
4036     }
4037
4038     // (Offset % 16) must be multiple of 4. Then address is then
4039     // Ptr + (Offset & ~15).
4040     if (Offset < 0)
4041       return SDValue();
4042     if ((Offset % 16) & 3)
4043       return SDValue();
4044     int64_t StartOffset = Offset & ~15;
4045     if (StartOffset)
4046       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4047                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4048
4049     int EltNo = (Offset - StartOffset) >> 2;
4050     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4051     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4052     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4053                              LD->getPointerInfo().getWithOffset(StartOffset),
4054                              false, false, 0);
4055     // Canonicalize it to a v4i32 shuffle.
4056     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4057     return DAG.getNode(ISD::BITCAST, dl, VT,
4058                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4059                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4060   }
4061
4062   return SDValue();
4063 }
4064
4065 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4066 /// vector of type 'VT', see if the elements can be replaced by a single large
4067 /// load which has the same value as a build_vector whose operands are 'elts'.
4068 ///
4069 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4070 ///
4071 /// FIXME: we'd also like to handle the case where the last elements are zero
4072 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4073 /// There's even a handy isZeroNode for that purpose.
4074 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4075                                         DebugLoc &DL, SelectionDAG &DAG) {
4076   EVT EltVT = VT.getVectorElementType();
4077   unsigned NumElems = Elts.size();
4078
4079   LoadSDNode *LDBase = NULL;
4080   unsigned LastLoadedElt = -1U;
4081
4082   // For each element in the initializer, see if we've found a load or an undef.
4083   // If we don't find an initial load element, or later load elements are
4084   // non-consecutive, bail out.
4085   for (unsigned i = 0; i < NumElems; ++i) {
4086     SDValue Elt = Elts[i];
4087
4088     if (!Elt.getNode() ||
4089         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4090       return SDValue();
4091     if (!LDBase) {
4092       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4093         return SDValue();
4094       LDBase = cast<LoadSDNode>(Elt.getNode());
4095       LastLoadedElt = i;
4096       continue;
4097     }
4098     if (Elt.getOpcode() == ISD::UNDEF)
4099       continue;
4100
4101     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4102     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4103       return SDValue();
4104     LastLoadedElt = i;
4105   }
4106
4107   // If we have found an entire vector of loads and undefs, then return a large
4108   // load of the entire vector width starting at the base pointer.  If we found
4109   // consecutive loads for the low half, generate a vzext_load node.
4110   if (LastLoadedElt == NumElems - 1) {
4111     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4112       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4113                          LDBase->getPointerInfo(),
4114                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4115     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4116                        LDBase->getPointerInfo(),
4117                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4118                        LDBase->getAlignment());
4119   } else if (NumElems == 4 && LastLoadedElt == 1) {
4120     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4121     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4122     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4123                                               Ops, 2, MVT::i32,
4124                                               LDBase->getMemOperand());
4125     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4126   }
4127   return SDValue();
4128 }
4129
4130 SDValue
4131 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4132   DebugLoc dl = Op.getDebugLoc();
4133   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4134   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4135   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4136   // is present, so AllOnes is ignored.
4137   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4138       (Op.getValueType().getSizeInBits() != 256 &&
4139        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4140     // Canonicalize this to <4 x i32> (SSE) to
4141     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4142     // eliminated on x86-32 hosts.
4143     if (Op.getValueType() == MVT::v4i32)
4144       return Op;
4145
4146     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4147       return getOnesVector(Op.getValueType(), DAG, dl);
4148     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4149   }
4150
4151   EVT VT = Op.getValueType();
4152   EVT ExtVT = VT.getVectorElementType();
4153   unsigned EVTBits = ExtVT.getSizeInBits();
4154
4155   unsigned NumElems = Op.getNumOperands();
4156   unsigned NumZero  = 0;
4157   unsigned NumNonZero = 0;
4158   unsigned NonZeros = 0;
4159   bool IsAllConstants = true;
4160   SmallSet<SDValue, 8> Values;
4161   for (unsigned i = 0; i < NumElems; ++i) {
4162     SDValue Elt = Op.getOperand(i);
4163     if (Elt.getOpcode() == ISD::UNDEF)
4164       continue;
4165     Values.insert(Elt);
4166     if (Elt.getOpcode() != ISD::Constant &&
4167         Elt.getOpcode() != ISD::ConstantFP)
4168       IsAllConstants = false;
4169     if (X86::isZeroNode(Elt))
4170       NumZero++;
4171     else {
4172       NonZeros |= (1 << i);
4173       NumNonZero++;
4174     }
4175   }
4176
4177   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4178   if (NumNonZero == 0)
4179     return DAG.getUNDEF(VT);
4180
4181   // Special case for single non-zero, non-undef, element.
4182   if (NumNonZero == 1) {
4183     unsigned Idx = CountTrailingZeros_32(NonZeros);
4184     SDValue Item = Op.getOperand(Idx);
4185
4186     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4187     // the value are obviously zero, truncate the value to i32 and do the
4188     // insertion that way.  Only do this if the value is non-constant or if the
4189     // value is a constant being inserted into element 0.  It is cheaper to do
4190     // a constant pool load than it is to do a movd + shuffle.
4191     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4192         (!IsAllConstants || Idx == 0)) {
4193       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4194         // Handle SSE only.
4195         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4196         EVT VecVT = MVT::v4i32;
4197         unsigned VecElts = 4;
4198
4199         // Truncate the value (which may itself be a constant) to i32, and
4200         // convert it to a vector with movd (S2V+shuffle to zero extend).
4201         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4202         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4203         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4204                                            Subtarget->hasSSE2(), DAG);
4205
4206         // Now we have our 32-bit value zero extended in the low element of
4207         // a vector.  If Idx != 0, swizzle it into place.
4208         if (Idx != 0) {
4209           SmallVector<int, 4> Mask;
4210           Mask.push_back(Idx);
4211           for (unsigned i = 1; i != VecElts; ++i)
4212             Mask.push_back(i);
4213           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4214                                       DAG.getUNDEF(Item.getValueType()),
4215                                       &Mask[0]);
4216         }
4217         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4218       }
4219     }
4220
4221     // If we have a constant or non-constant insertion into the low element of
4222     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4223     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4224     // depending on what the source datatype is.
4225     if (Idx == 0) {
4226       if (NumZero == 0) {
4227         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4228       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4229           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4230         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4231         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4232         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4233                                            DAG);
4234       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4235         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4236         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4237         EVT MiddleVT = MVT::v4i32;
4238         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4239         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4240                                            Subtarget->hasSSE2(), DAG);
4241         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4242       }
4243     }
4244
4245     // Is it a vector logical left shift?
4246     if (NumElems == 2 && Idx == 1 &&
4247         X86::isZeroNode(Op.getOperand(0)) &&
4248         !X86::isZeroNode(Op.getOperand(1))) {
4249       unsigned NumBits = VT.getSizeInBits();
4250       return getVShift(true, VT,
4251                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4252                                    VT, Op.getOperand(1)),
4253                        NumBits/2, DAG, *this, dl);
4254     }
4255
4256     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4257       return SDValue();
4258
4259     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4260     // is a non-constant being inserted into an element other than the low one,
4261     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4262     // movd/movss) to move this into the low element, then shuffle it into
4263     // place.
4264     if (EVTBits == 32) {
4265       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4266
4267       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4268       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4269                                          Subtarget->hasSSE2(), DAG);
4270       SmallVector<int, 8> MaskVec;
4271       for (unsigned i = 0; i < NumElems; i++)
4272         MaskVec.push_back(i == Idx ? 0 : 1);
4273       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4274     }
4275   }
4276
4277   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4278   if (Values.size() == 1) {
4279     if (EVTBits == 32) {
4280       // Instead of a shuffle like this:
4281       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4282       // Check if it's possible to issue this instead.
4283       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4284       unsigned Idx = CountTrailingZeros_32(NonZeros);
4285       SDValue Item = Op.getOperand(Idx);
4286       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4287         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4288     }
4289     return SDValue();
4290   }
4291
4292   // A vector full of immediates; various special cases are already
4293   // handled, so this is best done with a single constant-pool load.
4294   if (IsAllConstants)
4295     return SDValue();
4296
4297   // Let legalizer expand 2-wide build_vectors.
4298   if (EVTBits == 64) {
4299     if (NumNonZero == 1) {
4300       // One half is zero or undef.
4301       unsigned Idx = CountTrailingZeros_32(NonZeros);
4302       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4303                                  Op.getOperand(Idx));
4304       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4305                                          Subtarget->hasSSE2(), DAG);
4306     }
4307     return SDValue();
4308   }
4309
4310   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4311   if (EVTBits == 8 && NumElems == 16) {
4312     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4313                                         *this);
4314     if (V.getNode()) return V;
4315   }
4316
4317   if (EVTBits == 16 && NumElems == 8) {
4318     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4319                                       *this);
4320     if (V.getNode()) return V;
4321   }
4322
4323   // If element VT is == 32 bits, turn it into a number of shuffles.
4324   SmallVector<SDValue, 8> V;
4325   V.resize(NumElems);
4326   if (NumElems == 4 && NumZero > 0) {
4327     for (unsigned i = 0; i < 4; ++i) {
4328       bool isZero = !(NonZeros & (1 << i));
4329       if (isZero)
4330         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4331       else
4332         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4333     }
4334
4335     for (unsigned i = 0; i < 2; ++i) {
4336       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4337         default: break;
4338         case 0:
4339           V[i] = V[i*2];  // Must be a zero vector.
4340           break;
4341         case 1:
4342           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4343           break;
4344         case 2:
4345           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4346           break;
4347         case 3:
4348           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4349           break;
4350       }
4351     }
4352
4353     SmallVector<int, 8> MaskVec;
4354     bool Reverse = (NonZeros & 0x3) == 2;
4355     for (unsigned i = 0; i < 2; ++i)
4356       MaskVec.push_back(Reverse ? 1-i : i);
4357     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4358     for (unsigned i = 0; i < 2; ++i)
4359       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4360     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4361   }
4362
4363   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4364     // Check for a build vector of consecutive loads.
4365     for (unsigned i = 0; i < NumElems; ++i)
4366       V[i] = Op.getOperand(i);
4367
4368     // Check for elements which are consecutive loads.
4369     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4370     if (LD.getNode())
4371       return LD;
4372
4373     // For SSE 4.1, use insertps to put the high elements into the low element.
4374     if (getSubtarget()->hasSSE41()) {
4375       SDValue Result;
4376       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4377         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4378       else
4379         Result = DAG.getUNDEF(VT);
4380
4381       for (unsigned i = 1; i < NumElems; ++i) {
4382         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4383         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4384                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4385       }
4386       return Result;
4387     }
4388
4389     // Otherwise, expand into a number of unpckl*, start by extending each of
4390     // our (non-undef) elements to the full vector width with the element in the
4391     // bottom slot of the vector (which generates no code for SSE).
4392     for (unsigned i = 0; i < NumElems; ++i) {
4393       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4394         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4395       else
4396         V[i] = DAG.getUNDEF(VT);
4397     }
4398
4399     // Next, we iteratively mix elements, e.g. for v4f32:
4400     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4401     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4402     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4403     unsigned EltStride = NumElems >> 1;
4404     while (EltStride != 0) {
4405       for (unsigned i = 0; i < EltStride; ++i) {
4406         // If V[i+EltStride] is undef and this is the first round of mixing,
4407         // then it is safe to just drop this shuffle: V[i] is already in the
4408         // right place, the one element (since it's the first round) being
4409         // inserted as undef can be dropped.  This isn't safe for successive
4410         // rounds because they will permute elements within both vectors.
4411         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4412             EltStride == NumElems/2)
4413           continue;
4414
4415         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4416       }
4417       EltStride >>= 1;
4418     }
4419     return V[0];
4420   }
4421   return SDValue();
4422 }
4423
4424 SDValue
4425 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4426   // We support concatenate two MMX registers and place them in a MMX
4427   // register.  This is better than doing a stack convert.
4428   DebugLoc dl = Op.getDebugLoc();
4429   EVT ResVT = Op.getValueType();
4430   assert(Op.getNumOperands() == 2);
4431   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4432          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4433   int Mask[2];
4434   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4435   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4436   InVec = Op.getOperand(1);
4437   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4438     unsigned NumElts = ResVT.getVectorNumElements();
4439     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4440     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4441                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4442   } else {
4443     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4444     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4445     Mask[0] = 0; Mask[1] = 2;
4446     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4447   }
4448   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4449 }
4450
4451 // v8i16 shuffles - Prefer shuffles in the following order:
4452 // 1. [all]   pshuflw, pshufhw, optional move
4453 // 2. [ssse3] 1 x pshufb
4454 // 3. [ssse3] 2 x pshufb + 1 x por
4455 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4456 SDValue
4457 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4458                                             SelectionDAG &DAG) const {
4459   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4460   SDValue V1 = SVOp->getOperand(0);
4461   SDValue V2 = SVOp->getOperand(1);
4462   DebugLoc dl = SVOp->getDebugLoc();
4463   SmallVector<int, 8> MaskVals;
4464
4465   // Determine if more than 1 of the words in each of the low and high quadwords
4466   // of the result come from the same quadword of one of the two inputs.  Undef
4467   // mask values count as coming from any quadword, for better codegen.
4468   SmallVector<unsigned, 4> LoQuad(4);
4469   SmallVector<unsigned, 4> HiQuad(4);
4470   BitVector InputQuads(4);
4471   for (unsigned i = 0; i < 8; ++i) {
4472     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4473     int EltIdx = SVOp->getMaskElt(i);
4474     MaskVals.push_back(EltIdx);
4475     if (EltIdx < 0) {
4476       ++Quad[0];
4477       ++Quad[1];
4478       ++Quad[2];
4479       ++Quad[3];
4480       continue;
4481     }
4482     ++Quad[EltIdx / 4];
4483     InputQuads.set(EltIdx / 4);
4484   }
4485
4486   int BestLoQuad = -1;
4487   unsigned MaxQuad = 1;
4488   for (unsigned i = 0; i < 4; ++i) {
4489     if (LoQuad[i] > MaxQuad) {
4490       BestLoQuad = i;
4491       MaxQuad = LoQuad[i];
4492     }
4493   }
4494
4495   int BestHiQuad = -1;
4496   MaxQuad = 1;
4497   for (unsigned i = 0; i < 4; ++i) {
4498     if (HiQuad[i] > MaxQuad) {
4499       BestHiQuad = i;
4500       MaxQuad = HiQuad[i];
4501     }
4502   }
4503
4504   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4505   // of the two input vectors, shuffle them into one input vector so only a
4506   // single pshufb instruction is necessary. If There are more than 2 input
4507   // quads, disable the next transformation since it does not help SSSE3.
4508   bool V1Used = InputQuads[0] || InputQuads[1];
4509   bool V2Used = InputQuads[2] || InputQuads[3];
4510   if (Subtarget->hasSSSE3()) {
4511     if (InputQuads.count() == 2 && V1Used && V2Used) {
4512       BestLoQuad = InputQuads.find_first();
4513       BestHiQuad = InputQuads.find_next(BestLoQuad);
4514     }
4515     if (InputQuads.count() > 2) {
4516       BestLoQuad = -1;
4517       BestHiQuad = -1;
4518     }
4519   }
4520
4521   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4522   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4523   // words from all 4 input quadwords.
4524   SDValue NewV;
4525   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4526     SmallVector<int, 8> MaskV;
4527     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4528     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4529     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4530                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4531                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4532     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4533
4534     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4535     // source words for the shuffle, to aid later transformations.
4536     bool AllWordsInNewV = true;
4537     bool InOrder[2] = { true, true };
4538     for (unsigned i = 0; i != 8; ++i) {
4539       int idx = MaskVals[i];
4540       if (idx != (int)i)
4541         InOrder[i/4] = false;
4542       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4543         continue;
4544       AllWordsInNewV = false;
4545       break;
4546     }
4547
4548     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4549     if (AllWordsInNewV) {
4550       for (int i = 0; i != 8; ++i) {
4551         int idx = MaskVals[i];
4552         if (idx < 0)
4553           continue;
4554         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4555         if ((idx != i) && idx < 4)
4556           pshufhw = false;
4557         if ((idx != i) && idx > 3)
4558           pshuflw = false;
4559       }
4560       V1 = NewV;
4561       V2Used = false;
4562       BestLoQuad = 0;
4563       BestHiQuad = 1;
4564     }
4565
4566     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4567     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4568     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4569       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4570       unsigned TargetMask = 0;
4571       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4572                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4573       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4574                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4575       V1 = NewV.getOperand(0);
4576       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4577     }
4578   }
4579
4580   // If we have SSSE3, and all words of the result are from 1 input vector,
4581   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4582   // is present, fall back to case 4.
4583   if (Subtarget->hasSSSE3()) {
4584     SmallVector<SDValue,16> pshufbMask;
4585
4586     // If we have elements from both input vectors, set the high bit of the
4587     // shuffle mask element to zero out elements that come from V2 in the V1
4588     // mask, and elements that come from V1 in the V2 mask, so that the two
4589     // results can be OR'd together.
4590     bool TwoInputs = V1Used && V2Used;
4591     for (unsigned i = 0; i != 8; ++i) {
4592       int EltIdx = MaskVals[i] * 2;
4593       if (TwoInputs && (EltIdx >= 16)) {
4594         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4595         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4596         continue;
4597       }
4598       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4599       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4600     }
4601     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4602     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4603                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4604                                  MVT::v16i8, &pshufbMask[0], 16));
4605     if (!TwoInputs)
4606       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4607
4608     // Calculate the shuffle mask for the second input, shuffle it, and
4609     // OR it with the first shuffled input.
4610     pshufbMask.clear();
4611     for (unsigned i = 0; i != 8; ++i) {
4612       int EltIdx = MaskVals[i] * 2;
4613       if (EltIdx < 16) {
4614         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4615         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4616         continue;
4617       }
4618       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4619       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4620     }
4621     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4622     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4623                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4624                                  MVT::v16i8, &pshufbMask[0], 16));
4625     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4626     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4627   }
4628
4629   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4630   // and update MaskVals with new element order.
4631   BitVector InOrder(8);
4632   if (BestLoQuad >= 0) {
4633     SmallVector<int, 8> MaskV;
4634     for (int i = 0; i != 4; ++i) {
4635       int idx = MaskVals[i];
4636       if (idx < 0) {
4637         MaskV.push_back(-1);
4638         InOrder.set(i);
4639       } else if ((idx / 4) == BestLoQuad) {
4640         MaskV.push_back(idx & 3);
4641         InOrder.set(i);
4642       } else {
4643         MaskV.push_back(-1);
4644       }
4645     }
4646     for (unsigned i = 4; i != 8; ++i)
4647       MaskV.push_back(i);
4648     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4649                                 &MaskV[0]);
4650
4651     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4652       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4653                                NewV.getOperand(0),
4654                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4655                                DAG);
4656   }
4657
4658   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4659   // and update MaskVals with the new element order.
4660   if (BestHiQuad >= 0) {
4661     SmallVector<int, 8> MaskV;
4662     for (unsigned i = 0; i != 4; ++i)
4663       MaskV.push_back(i);
4664     for (unsigned i = 4; i != 8; ++i) {
4665       int idx = MaskVals[i];
4666       if (idx < 0) {
4667         MaskV.push_back(-1);
4668         InOrder.set(i);
4669       } else if ((idx / 4) == BestHiQuad) {
4670         MaskV.push_back((idx & 3) + 4);
4671         InOrder.set(i);
4672       } else {
4673         MaskV.push_back(-1);
4674       }
4675     }
4676     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4677                                 &MaskV[0]);
4678
4679     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4680       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4681                               NewV.getOperand(0),
4682                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4683                               DAG);
4684   }
4685
4686   // In case BestHi & BestLo were both -1, which means each quadword has a word
4687   // from each of the four input quadwords, calculate the InOrder bitvector now
4688   // before falling through to the insert/extract cleanup.
4689   if (BestLoQuad == -1 && BestHiQuad == -1) {
4690     NewV = V1;
4691     for (int i = 0; i != 8; ++i)
4692       if (MaskVals[i] < 0 || MaskVals[i] == i)
4693         InOrder.set(i);
4694   }
4695
4696   // The other elements are put in the right place using pextrw and pinsrw.
4697   for (unsigned i = 0; i != 8; ++i) {
4698     if (InOrder[i])
4699       continue;
4700     int EltIdx = MaskVals[i];
4701     if (EltIdx < 0)
4702       continue;
4703     SDValue ExtOp = (EltIdx < 8)
4704     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4705                   DAG.getIntPtrConstant(EltIdx))
4706     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4707                   DAG.getIntPtrConstant(EltIdx - 8));
4708     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4709                        DAG.getIntPtrConstant(i));
4710   }
4711   return NewV;
4712 }
4713
4714 // v16i8 shuffles - Prefer shuffles in the following order:
4715 // 1. [ssse3] 1 x pshufb
4716 // 2. [ssse3] 2 x pshufb + 1 x por
4717 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4718 static
4719 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4720                                  SelectionDAG &DAG,
4721                                  const X86TargetLowering &TLI) {
4722   SDValue V1 = SVOp->getOperand(0);
4723   SDValue V2 = SVOp->getOperand(1);
4724   DebugLoc dl = SVOp->getDebugLoc();
4725   SmallVector<int, 16> MaskVals;
4726   SVOp->getMask(MaskVals);
4727
4728   // If we have SSSE3, case 1 is generated when all result bytes come from
4729   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4730   // present, fall back to case 3.
4731   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4732   bool V1Only = true;
4733   bool V2Only = true;
4734   for (unsigned i = 0; i < 16; ++i) {
4735     int EltIdx = MaskVals[i];
4736     if (EltIdx < 0)
4737       continue;
4738     if (EltIdx < 16)
4739       V2Only = false;
4740     else
4741       V1Only = false;
4742   }
4743
4744   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4745   if (TLI.getSubtarget()->hasSSSE3()) {
4746     SmallVector<SDValue,16> pshufbMask;
4747
4748     // If all result elements are from one input vector, then only translate
4749     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4750     //
4751     // Otherwise, we have elements from both input vectors, and must zero out
4752     // elements that come from V2 in the first mask, and V1 in the second mask
4753     // so that we can OR them together.
4754     bool TwoInputs = !(V1Only || V2Only);
4755     for (unsigned i = 0; i != 16; ++i) {
4756       int EltIdx = MaskVals[i];
4757       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4758         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4759         continue;
4760       }
4761       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4762     }
4763     // If all the elements are from V2, assign it to V1 and return after
4764     // building the first pshufb.
4765     if (V2Only)
4766       V1 = V2;
4767     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4768                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4769                                  MVT::v16i8, &pshufbMask[0], 16));
4770     if (!TwoInputs)
4771       return V1;
4772
4773     // Calculate the shuffle mask for the second input, shuffle it, and
4774     // OR it with the first shuffled input.
4775     pshufbMask.clear();
4776     for (unsigned i = 0; i != 16; ++i) {
4777       int EltIdx = MaskVals[i];
4778       if (EltIdx < 16) {
4779         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4780         continue;
4781       }
4782       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4783     }
4784     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4785                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4786                                  MVT::v16i8, &pshufbMask[0], 16));
4787     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4788   }
4789
4790   // No SSSE3 - Calculate in place words and then fix all out of place words
4791   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4792   // the 16 different words that comprise the two doublequadword input vectors.
4793   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4794   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4795   SDValue NewV = V2Only ? V2 : V1;
4796   for (int i = 0; i != 8; ++i) {
4797     int Elt0 = MaskVals[i*2];
4798     int Elt1 = MaskVals[i*2+1];
4799
4800     // This word of the result is all undef, skip it.
4801     if (Elt0 < 0 && Elt1 < 0)
4802       continue;
4803
4804     // This word of the result is already in the correct place, skip it.
4805     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4806       continue;
4807     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4808       continue;
4809
4810     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4811     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4812     SDValue InsElt;
4813
4814     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4815     // using a single extract together, load it and store it.
4816     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4817       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4818                            DAG.getIntPtrConstant(Elt1 / 2));
4819       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4820                         DAG.getIntPtrConstant(i));
4821       continue;
4822     }
4823
4824     // If Elt1 is defined, extract it from the appropriate source.  If the
4825     // source byte is not also odd, shift the extracted word left 8 bits
4826     // otherwise clear the bottom 8 bits if we need to do an or.
4827     if (Elt1 >= 0) {
4828       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4829                            DAG.getIntPtrConstant(Elt1 / 2));
4830       if ((Elt1 & 1) == 0)
4831         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4832                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4833       else if (Elt0 >= 0)
4834         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4835                              DAG.getConstant(0xFF00, MVT::i16));
4836     }
4837     // If Elt0 is defined, extract it from the appropriate source.  If the
4838     // source byte is not also even, shift the extracted word right 8 bits. If
4839     // Elt1 was also defined, OR the extracted values together before
4840     // inserting them in the result.
4841     if (Elt0 >= 0) {
4842       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4843                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4844       if ((Elt0 & 1) != 0)
4845         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4846                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4847       else if (Elt1 >= 0)
4848         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4849                              DAG.getConstant(0x00FF, MVT::i16));
4850       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4851                          : InsElt0;
4852     }
4853     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4854                        DAG.getIntPtrConstant(i));
4855   }
4856   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4857 }
4858
4859 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4860 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4861 /// done when every pair / quad of shuffle mask elements point to elements in
4862 /// the right sequence. e.g.
4863 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4864 static
4865 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4866                                  SelectionDAG &DAG, DebugLoc dl) {
4867   EVT VT = SVOp->getValueType(0);
4868   SDValue V1 = SVOp->getOperand(0);
4869   SDValue V2 = SVOp->getOperand(1);
4870   unsigned NumElems = VT.getVectorNumElements();
4871   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4872   EVT NewVT;
4873   switch (VT.getSimpleVT().SimpleTy) {
4874   default: assert(false && "Unexpected!");
4875   case MVT::v4f32: NewVT = MVT::v2f64; break;
4876   case MVT::v4i32: NewVT = MVT::v2i64; break;
4877   case MVT::v8i16: NewVT = MVT::v4i32; break;
4878   case MVT::v16i8: NewVT = MVT::v4i32; break;
4879   }
4880
4881   int Scale = NumElems / NewWidth;
4882   SmallVector<int, 8> MaskVec;
4883   for (unsigned i = 0; i < NumElems; i += Scale) {
4884     int StartIdx = -1;
4885     for (int j = 0; j < Scale; ++j) {
4886       int EltIdx = SVOp->getMaskElt(i+j);
4887       if (EltIdx < 0)
4888         continue;
4889       if (StartIdx == -1)
4890         StartIdx = EltIdx - (EltIdx % Scale);
4891       if (EltIdx != StartIdx + j)
4892         return SDValue();
4893     }
4894     if (StartIdx == -1)
4895       MaskVec.push_back(-1);
4896     else
4897       MaskVec.push_back(StartIdx / Scale);
4898   }
4899
4900   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4901   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4902   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4903 }
4904
4905 /// getVZextMovL - Return a zero-extending vector move low node.
4906 ///
4907 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4908                             SDValue SrcOp, SelectionDAG &DAG,
4909                             const X86Subtarget *Subtarget, DebugLoc dl) {
4910   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4911     LoadSDNode *LD = NULL;
4912     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4913       LD = dyn_cast<LoadSDNode>(SrcOp);
4914     if (!LD) {
4915       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4916       // instead.
4917       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4918       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4919           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4920           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4921           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4922         // PR2108
4923         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4924         return DAG.getNode(ISD::BITCAST, dl, VT,
4925                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4926                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4927                                                    OpVT,
4928                                                    SrcOp.getOperand(0)
4929                                                           .getOperand(0))));
4930       }
4931     }
4932   }
4933
4934   return DAG.getNode(ISD::BITCAST, dl, VT,
4935                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4936                                  DAG.getNode(ISD::BITCAST, dl,
4937                                              OpVT, SrcOp)));
4938 }
4939
4940 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4941 /// shuffles.
4942 static SDValue
4943 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4944   SDValue V1 = SVOp->getOperand(0);
4945   SDValue V2 = SVOp->getOperand(1);
4946   DebugLoc dl = SVOp->getDebugLoc();
4947   EVT VT = SVOp->getValueType(0);
4948
4949   SmallVector<std::pair<int, int>, 8> Locs;
4950   Locs.resize(4);
4951   SmallVector<int, 8> Mask1(4U, -1);
4952   SmallVector<int, 8> PermMask;
4953   SVOp->getMask(PermMask);
4954
4955   unsigned NumHi = 0;
4956   unsigned NumLo = 0;
4957   for (unsigned i = 0; i != 4; ++i) {
4958     int Idx = PermMask[i];
4959     if (Idx < 0) {
4960       Locs[i] = std::make_pair(-1, -1);
4961     } else {
4962       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4963       if (Idx < 4) {
4964         Locs[i] = std::make_pair(0, NumLo);
4965         Mask1[NumLo] = Idx;
4966         NumLo++;
4967       } else {
4968         Locs[i] = std::make_pair(1, NumHi);
4969         if (2+NumHi < 4)
4970           Mask1[2+NumHi] = Idx;
4971         NumHi++;
4972       }
4973     }
4974   }
4975
4976   if (NumLo <= 2 && NumHi <= 2) {
4977     // If no more than two elements come from either vector. This can be
4978     // implemented with two shuffles. First shuffle gather the elements.
4979     // The second shuffle, which takes the first shuffle as both of its
4980     // vector operands, put the elements into the right order.
4981     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4982
4983     SmallVector<int, 8> Mask2(4U, -1);
4984
4985     for (unsigned i = 0; i != 4; ++i) {
4986       if (Locs[i].first == -1)
4987         continue;
4988       else {
4989         unsigned Idx = (i < 2) ? 0 : 4;
4990         Idx += Locs[i].first * 2 + Locs[i].second;
4991         Mask2[i] = Idx;
4992       }
4993     }
4994
4995     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4996   } else if (NumLo == 3 || NumHi == 3) {
4997     // Otherwise, we must have three elements from one vector, call it X, and
4998     // one element from the other, call it Y.  First, use a shufps to build an
4999     // intermediate vector with the one element from Y and the element from X
5000     // that will be in the same half in the final destination (the indexes don't
5001     // matter). Then, use a shufps to build the final vector, taking the half
5002     // containing the element from Y from the intermediate, and the other half
5003     // from X.
5004     if (NumHi == 3) {
5005       // Normalize it so the 3 elements come from V1.
5006       CommuteVectorShuffleMask(PermMask, VT);
5007       std::swap(V1, V2);
5008     }
5009
5010     // Find the element from V2.
5011     unsigned HiIndex;
5012     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5013       int Val = PermMask[HiIndex];
5014       if (Val < 0)
5015         continue;
5016       if (Val >= 4)
5017         break;
5018     }
5019
5020     Mask1[0] = PermMask[HiIndex];
5021     Mask1[1] = -1;
5022     Mask1[2] = PermMask[HiIndex^1];
5023     Mask1[3] = -1;
5024     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5025
5026     if (HiIndex >= 2) {
5027       Mask1[0] = PermMask[0];
5028       Mask1[1] = PermMask[1];
5029       Mask1[2] = HiIndex & 1 ? 6 : 4;
5030       Mask1[3] = HiIndex & 1 ? 4 : 6;
5031       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5032     } else {
5033       Mask1[0] = HiIndex & 1 ? 2 : 0;
5034       Mask1[1] = HiIndex & 1 ? 0 : 2;
5035       Mask1[2] = PermMask[2];
5036       Mask1[3] = PermMask[3];
5037       if (Mask1[2] >= 0)
5038         Mask1[2] += 4;
5039       if (Mask1[3] >= 0)
5040         Mask1[3] += 4;
5041       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5042     }
5043   }
5044
5045   // Break it into (shuffle shuffle_hi, shuffle_lo).
5046   Locs.clear();
5047   SmallVector<int,8> LoMask(4U, -1);
5048   SmallVector<int,8> HiMask(4U, -1);
5049
5050   SmallVector<int,8> *MaskPtr = &LoMask;
5051   unsigned MaskIdx = 0;
5052   unsigned LoIdx = 0;
5053   unsigned HiIdx = 2;
5054   for (unsigned i = 0; i != 4; ++i) {
5055     if (i == 2) {
5056       MaskPtr = &HiMask;
5057       MaskIdx = 1;
5058       LoIdx = 0;
5059       HiIdx = 2;
5060     }
5061     int Idx = PermMask[i];
5062     if (Idx < 0) {
5063       Locs[i] = std::make_pair(-1, -1);
5064     } else if (Idx < 4) {
5065       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5066       (*MaskPtr)[LoIdx] = Idx;
5067       LoIdx++;
5068     } else {
5069       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5070       (*MaskPtr)[HiIdx] = Idx;
5071       HiIdx++;
5072     }
5073   }
5074
5075   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5076   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5077   SmallVector<int, 8> MaskOps;
5078   for (unsigned i = 0; i != 4; ++i) {
5079     if (Locs[i].first == -1) {
5080       MaskOps.push_back(-1);
5081     } else {
5082       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5083       MaskOps.push_back(Idx);
5084     }
5085   }
5086   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5087 }
5088
5089 static bool MayFoldVectorLoad(SDValue V) {
5090   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5091     V = V.getOperand(0);
5092   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5093     V = V.getOperand(0);
5094   if (MayFoldLoad(V))
5095     return true;
5096   return false;
5097 }
5098
5099 // FIXME: the version above should always be used. Since there's
5100 // a bug where several vector shuffles can't be folded because the
5101 // DAG is not updated during lowering and a node claims to have two
5102 // uses while it only has one, use this version, and let isel match
5103 // another instruction if the load really happens to have more than
5104 // one use. Remove this version after this bug get fixed.
5105 // rdar://8434668, PR8156
5106 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5107   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5108     V = V.getOperand(0);
5109   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5110     V = V.getOperand(0);
5111   if (ISD::isNormalLoad(V.getNode()))
5112     return true;
5113   return false;
5114 }
5115
5116 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5117 /// a vector extract, and if both can be later optimized into a single load.
5118 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5119 /// here because otherwise a target specific shuffle node is going to be
5120 /// emitted for this shuffle, and the optimization not done.
5121 /// FIXME: This is probably not the best approach, but fix the problem
5122 /// until the right path is decided.
5123 static
5124 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5125                                          const TargetLowering &TLI) {
5126   EVT VT = V.getValueType();
5127   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5128
5129   // Be sure that the vector shuffle is present in a pattern like this:
5130   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5131   if (!V.hasOneUse())
5132     return false;
5133
5134   SDNode *N = *V.getNode()->use_begin();
5135   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5136     return false;
5137
5138   SDValue EltNo = N->getOperand(1);
5139   if (!isa<ConstantSDNode>(EltNo))
5140     return false;
5141
5142   // If the bit convert changed the number of elements, it is unsafe
5143   // to examine the mask.
5144   bool HasShuffleIntoBitcast = false;
5145   if (V.getOpcode() == ISD::BITCAST) {
5146     EVT SrcVT = V.getOperand(0).getValueType();
5147     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5148       return false;
5149     V = V.getOperand(0);
5150     HasShuffleIntoBitcast = true;
5151   }
5152
5153   // Select the input vector, guarding against out of range extract vector.
5154   unsigned NumElems = VT.getVectorNumElements();
5155   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5156   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5157   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5158
5159   // Skip one more bit_convert if necessary
5160   if (V.getOpcode() == ISD::BITCAST)
5161     V = V.getOperand(0);
5162
5163   if (ISD::isNormalLoad(V.getNode())) {
5164     // Is the original load suitable?
5165     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5166
5167     // FIXME: avoid the multi-use bug that is preventing lots of
5168     // of foldings to be detected, this is still wrong of course, but
5169     // give the temporary desired behavior, and if it happens that
5170     // the load has real more uses, during isel it will not fold, and
5171     // will generate poor code.
5172     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5173       return false;
5174
5175     if (!HasShuffleIntoBitcast)
5176       return true;
5177
5178     // If there's a bitcast before the shuffle, check if the load type and
5179     // alignment is valid.
5180     unsigned Align = LN0->getAlignment();
5181     unsigned NewAlign =
5182       TLI.getTargetData()->getABITypeAlignment(
5183                                     VT.getTypeForEVT(*DAG.getContext()));
5184
5185     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5186       return false;
5187   }
5188
5189   return true;
5190 }
5191
5192 static
5193 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5194   EVT VT = Op.getValueType();
5195
5196   // Canonizalize to v2f64.
5197   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5198   return DAG.getNode(ISD::BITCAST, dl, VT,
5199                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5200                                           V1, DAG));
5201 }
5202
5203 static
5204 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5205                         bool HasSSE2) {
5206   SDValue V1 = Op.getOperand(0);
5207   SDValue V2 = Op.getOperand(1);
5208   EVT VT = Op.getValueType();
5209
5210   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5211
5212   if (HasSSE2 && VT == MVT::v2f64)
5213     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5214
5215   // v4f32 or v4i32
5216   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5217 }
5218
5219 static
5220 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5221   SDValue V1 = Op.getOperand(0);
5222   SDValue V2 = Op.getOperand(1);
5223   EVT VT = Op.getValueType();
5224
5225   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5226          "unsupported shuffle type");
5227
5228   if (V2.getOpcode() == ISD::UNDEF)
5229     V2 = V1;
5230
5231   // v4i32 or v4f32
5232   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5233 }
5234
5235 static
5236 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5237   SDValue V1 = Op.getOperand(0);
5238   SDValue V2 = Op.getOperand(1);
5239   EVT VT = Op.getValueType();
5240   unsigned NumElems = VT.getVectorNumElements();
5241
5242   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5243   // operand of these instructions is only memory, so check if there's a
5244   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5245   // same masks.
5246   bool CanFoldLoad = false;
5247
5248   // Trivial case, when V2 comes from a load.
5249   if (MayFoldVectorLoad(V2))
5250     CanFoldLoad = true;
5251
5252   // When V1 is a load, it can be folded later into a store in isel, example:
5253   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5254   //    turns into:
5255   //  (MOVLPSmr addr:$src1, VR128:$src2)
5256   // So, recognize this potential and also use MOVLPS or MOVLPD
5257   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5258     CanFoldLoad = true;
5259
5260   if (CanFoldLoad) {
5261     if (HasSSE2 && NumElems == 2)
5262       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5263
5264     if (NumElems == 4)
5265       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5266   }
5267
5268   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5269   // movl and movlp will both match v2i64, but v2i64 is never matched by
5270   // movl earlier because we make it strict to avoid messing with the movlp load
5271   // folding logic (see the code above getMOVLP call). Match it here then,
5272   // this is horrible, but will stay like this until we move all shuffle
5273   // matching to x86 specific nodes. Note that for the 1st condition all
5274   // types are matched with movsd.
5275   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5276     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5277   else if (HasSSE2)
5278     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5279
5280
5281   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5282
5283   // Invert the operand order and use SHUFPS to match it.
5284   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5285                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5286 }
5287
5288 static inline unsigned getUNPCKLOpcode(EVT VT) {
5289   switch(VT.getSimpleVT().SimpleTy) {
5290   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5291   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5292   case MVT::v4f32: return X86ISD::UNPCKLPS;
5293   case MVT::v2f64: return X86ISD::UNPCKLPD;
5294   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5295   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5296   default:
5297     llvm_unreachable("Unknow type for unpckl");
5298   }
5299   return 0;
5300 }
5301
5302 static inline unsigned getUNPCKHOpcode(EVT VT) {
5303   switch(VT.getSimpleVT().SimpleTy) {
5304   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5305   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5306   case MVT::v4f32: return X86ISD::UNPCKHPS;
5307   case MVT::v2f64: return X86ISD::UNPCKHPD;
5308   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5309   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5310   default:
5311     llvm_unreachable("Unknow type for unpckh");
5312   }
5313   return 0;
5314 }
5315
5316 static
5317 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5318                                const TargetLowering &TLI,
5319                                const X86Subtarget *Subtarget) {
5320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5321   EVT VT = Op.getValueType();
5322   DebugLoc dl = Op.getDebugLoc();
5323   SDValue V1 = Op.getOperand(0);
5324   SDValue V2 = Op.getOperand(1);
5325
5326   if (isZeroShuffle(SVOp))
5327     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5328
5329   // Handle splat operations
5330   if (SVOp->isSplat()) {
5331     // Special case, this is the only place now where it's
5332     // allowed to return a vector_shuffle operation without
5333     // using a target specific node, because *hopefully* it
5334     // will be optimized away by the dag combiner.
5335     if (VT.getVectorNumElements() <= 4 &&
5336         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5337       return Op;
5338
5339     // Handle splats by matching through known masks
5340     if (VT.getVectorNumElements() <= 4)
5341       return SDValue();
5342
5343     // Canonicalize all of the remaining to v4f32.
5344     return PromoteSplat(SVOp, DAG);
5345   }
5346
5347   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5348   // do it!
5349   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5350     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5351     if (NewOp.getNode())
5352       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5353   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5354     // FIXME: Figure out a cleaner way to do this.
5355     // Try to make use of movq to zero out the top part.
5356     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5357       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5358       if (NewOp.getNode()) {
5359         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5360           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5361                               DAG, Subtarget, dl);
5362       }
5363     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5364       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5365       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5366         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5367                             DAG, Subtarget, dl);
5368     }
5369   }
5370   return SDValue();
5371 }
5372
5373 SDValue
5374 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5375   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5376   SDValue V1 = Op.getOperand(0);
5377   SDValue V2 = Op.getOperand(1);
5378   EVT VT = Op.getValueType();
5379   DebugLoc dl = Op.getDebugLoc();
5380   unsigned NumElems = VT.getVectorNumElements();
5381   bool isMMX = VT.getSizeInBits() == 64;
5382   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5383   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5384   bool V1IsSplat = false;
5385   bool V2IsSplat = false;
5386   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5387   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5388   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5389   MachineFunction &MF = DAG.getMachineFunction();
5390   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5391
5392   // Shuffle operations on MMX not supported.
5393   if (isMMX)
5394     return Op;
5395
5396   // Vector shuffle lowering takes 3 steps:
5397   //
5398   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5399   //    narrowing and commutation of operands should be handled.
5400   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5401   //    shuffle nodes.
5402   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5403   //    so the shuffle can be broken into other shuffles and the legalizer can
5404   //    try the lowering again.
5405   //
5406   // The general ideia is that no vector_shuffle operation should be left to
5407   // be matched during isel, all of them must be converted to a target specific
5408   // node here.
5409
5410   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5411   // narrowing and commutation of operands should be handled. The actual code
5412   // doesn't include all of those, work in progress...
5413   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5414   if (NewOp.getNode())
5415     return NewOp;
5416
5417   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5418   // unpckh_undef). Only use pshufd if speed is more important than size.
5419   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5420     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5421       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5422   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5423     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5424       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5425
5426   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5427       RelaxedMayFoldVectorLoad(V1))
5428     return getMOVDDup(Op, dl, V1, DAG);
5429
5430   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5431     return getMOVHighToLow(Op, dl, DAG);
5432
5433   // Use to match splats
5434   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5435       (VT == MVT::v2f64 || VT == MVT::v2i64))
5436     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5437
5438   if (X86::isPSHUFDMask(SVOp)) {
5439     // The actual implementation will match the mask in the if above and then
5440     // during isel it can match several different instructions, not only pshufd
5441     // as its name says, sad but true, emulate the behavior for now...
5442     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5443         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5444
5445     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5446
5447     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5448       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5449
5450     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5451       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5452                                   TargetMask, DAG);
5453
5454     if (VT == MVT::v4f32)
5455       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5456                                   TargetMask, DAG);
5457   }
5458
5459   // Check if this can be converted into a logical shift.
5460   bool isLeft = false;
5461   unsigned ShAmt = 0;
5462   SDValue ShVal;
5463   bool isShift = getSubtarget()->hasSSE2() &&
5464     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5465   if (isShift && ShVal.hasOneUse()) {
5466     // If the shifted value has multiple uses, it may be cheaper to use
5467     // v_set0 + movlhps or movhlps, etc.
5468     EVT EltVT = VT.getVectorElementType();
5469     ShAmt *= EltVT.getSizeInBits();
5470     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5471   }
5472
5473   if (X86::isMOVLMask(SVOp)) {
5474     if (V1IsUndef)
5475       return V2;
5476     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5477       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5478     if (!X86::isMOVLPMask(SVOp)) {
5479       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5480         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5481
5482       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5483         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5484     }
5485   }
5486
5487   // FIXME: fold these into legal mask.
5488   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5489     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5490
5491   if (X86::isMOVHLPSMask(SVOp))
5492     return getMOVHighToLow(Op, dl, DAG);
5493
5494   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5495     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5496
5497   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5498     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5499
5500   if (X86::isMOVLPMask(SVOp))
5501     return getMOVLP(Op, dl, DAG, HasSSE2);
5502
5503   if (ShouldXformToMOVHLPS(SVOp) ||
5504       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5505     return CommuteVectorShuffle(SVOp, DAG);
5506
5507   if (isShift) {
5508     // No better options. Use a vshl / vsrl.
5509     EVT EltVT = VT.getVectorElementType();
5510     ShAmt *= EltVT.getSizeInBits();
5511     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5512   }
5513
5514   bool Commuted = false;
5515   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5516   // 1,1,1,1 -> v8i16 though.
5517   V1IsSplat = isSplatVector(V1.getNode());
5518   V2IsSplat = isSplatVector(V2.getNode());
5519
5520   // Canonicalize the splat or undef, if present, to be on the RHS.
5521   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5522     Op = CommuteVectorShuffle(SVOp, DAG);
5523     SVOp = cast<ShuffleVectorSDNode>(Op);
5524     V1 = SVOp->getOperand(0);
5525     V2 = SVOp->getOperand(1);
5526     std::swap(V1IsSplat, V2IsSplat);
5527     std::swap(V1IsUndef, V2IsUndef);
5528     Commuted = true;
5529   }
5530
5531   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5532     // Shuffling low element of v1 into undef, just return v1.
5533     if (V2IsUndef)
5534       return V1;
5535     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5536     // the instruction selector will not match, so get a canonical MOVL with
5537     // swapped operands to undo the commute.
5538     return getMOVL(DAG, dl, VT, V2, V1);
5539   }
5540
5541   if (X86::isUNPCKLMask(SVOp))
5542     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5543
5544   if (X86::isUNPCKHMask(SVOp))
5545     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5546
5547   if (V2IsSplat) {
5548     // Normalize mask so all entries that point to V2 points to its first
5549     // element then try to match unpck{h|l} again. If match, return a
5550     // new vector_shuffle with the corrected mask.
5551     SDValue NewMask = NormalizeMask(SVOp, DAG);
5552     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5553     if (NSVOp != SVOp) {
5554       if (X86::isUNPCKLMask(NSVOp, true)) {
5555         return NewMask;
5556       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5557         return NewMask;
5558       }
5559     }
5560   }
5561
5562   if (Commuted) {
5563     // Commute is back and try unpck* again.
5564     // FIXME: this seems wrong.
5565     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5566     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5567
5568     if (X86::isUNPCKLMask(NewSVOp))
5569       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5570
5571     if (X86::isUNPCKHMask(NewSVOp))
5572       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5573   }
5574
5575   // Normalize the node to match x86 shuffle ops if needed
5576   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5577     return CommuteVectorShuffle(SVOp, DAG);
5578
5579   // The checks below are all present in isShuffleMaskLegal, but they are
5580   // inlined here right now to enable us to directly emit target specific
5581   // nodes, and remove one by one until they don't return Op anymore.
5582   SmallVector<int, 16> M;
5583   SVOp->getMask(M);
5584
5585   if (isPALIGNRMask(M, VT, HasSSSE3))
5586     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5587                                 X86::getShufflePALIGNRImmediate(SVOp),
5588                                 DAG);
5589
5590   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5591       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5592     if (VT == MVT::v2f64)
5593       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5594     if (VT == MVT::v2i64)
5595       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5596   }
5597
5598   if (isPSHUFHWMask(M, VT))
5599     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5600                                 X86::getShufflePSHUFHWImmediate(SVOp),
5601                                 DAG);
5602
5603   if (isPSHUFLWMask(M, VT))
5604     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5605                                 X86::getShufflePSHUFLWImmediate(SVOp),
5606                                 DAG);
5607
5608   if (isSHUFPMask(M, VT)) {
5609     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5610     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5611       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5612                                   TargetMask, DAG);
5613     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5614       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5615                                   TargetMask, DAG);
5616   }
5617
5618   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5619     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5620       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5621   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5622     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5623       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5624
5625   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5626   if (VT == MVT::v8i16) {
5627     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5628     if (NewOp.getNode())
5629       return NewOp;
5630   }
5631
5632   if (VT == MVT::v16i8) {
5633     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5634     if (NewOp.getNode())
5635       return NewOp;
5636   }
5637
5638   // Handle all 4 wide cases with a number of shuffles.
5639   if (NumElems == 4)
5640     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5641
5642   return SDValue();
5643 }
5644
5645 SDValue
5646 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5647                                                 SelectionDAG &DAG) const {
5648   EVT VT = Op.getValueType();
5649   DebugLoc dl = Op.getDebugLoc();
5650   if (VT.getSizeInBits() == 8) {
5651     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5652                                     Op.getOperand(0), Op.getOperand(1));
5653     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5654                                     DAG.getValueType(VT));
5655     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5656   } else if (VT.getSizeInBits() == 16) {
5657     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5658     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5659     if (Idx == 0)
5660       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5661                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5662                                      DAG.getNode(ISD::BITCAST, dl,
5663                                                  MVT::v4i32,
5664                                                  Op.getOperand(0)),
5665                                      Op.getOperand(1)));
5666     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5667                                     Op.getOperand(0), Op.getOperand(1));
5668     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5669                                     DAG.getValueType(VT));
5670     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5671   } else if (VT == MVT::f32) {
5672     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5673     // the result back to FR32 register. It's only worth matching if the
5674     // result has a single use which is a store or a bitcast to i32.  And in
5675     // the case of a store, it's not worth it if the index is a constant 0,
5676     // because a MOVSSmr can be used instead, which is smaller and faster.
5677     if (!Op.hasOneUse())
5678       return SDValue();
5679     SDNode *User = *Op.getNode()->use_begin();
5680     if ((User->getOpcode() != ISD::STORE ||
5681          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5682           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5683         (User->getOpcode() != ISD::BITCAST ||
5684          User->getValueType(0) != MVT::i32))
5685       return SDValue();
5686     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5687                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5688                                               Op.getOperand(0)),
5689                                               Op.getOperand(1));
5690     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5691   } else if (VT == MVT::i32) {
5692     // ExtractPS works with constant index.
5693     if (isa<ConstantSDNode>(Op.getOperand(1)))
5694       return Op;
5695   }
5696   return SDValue();
5697 }
5698
5699
5700 SDValue
5701 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5702                                            SelectionDAG &DAG) const {
5703   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5704     return SDValue();
5705
5706   if (Subtarget->hasSSE41()) {
5707     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5708     if (Res.getNode())
5709       return Res;
5710   }
5711
5712   EVT VT = Op.getValueType();
5713   DebugLoc dl = Op.getDebugLoc();
5714   // TODO: handle v16i8.
5715   if (VT.getSizeInBits() == 16) {
5716     SDValue Vec = Op.getOperand(0);
5717     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5718     if (Idx == 0)
5719       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5720                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5721                                      DAG.getNode(ISD::BITCAST, dl,
5722                                                  MVT::v4i32, Vec),
5723                                      Op.getOperand(1)));
5724     // Transform it so it match pextrw which produces a 32-bit result.
5725     EVT EltVT = MVT::i32;
5726     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5727                                     Op.getOperand(0), Op.getOperand(1));
5728     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5729                                     DAG.getValueType(VT));
5730     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5731   } else if (VT.getSizeInBits() == 32) {
5732     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5733     if (Idx == 0)
5734       return Op;
5735
5736     // SHUFPS the element to the lowest double word, then movss.
5737     int Mask[4] = { Idx, -1, -1, -1 };
5738     EVT VVT = Op.getOperand(0).getValueType();
5739     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5740                                        DAG.getUNDEF(VVT), Mask);
5741     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5742                        DAG.getIntPtrConstant(0));
5743   } else if (VT.getSizeInBits() == 64) {
5744     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5745     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5746     //        to match extract_elt for f64.
5747     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5748     if (Idx == 0)
5749       return Op;
5750
5751     // UNPCKHPD the element to the lowest double word, then movsd.
5752     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5753     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5754     int Mask[2] = { 1, -1 };
5755     EVT VVT = Op.getOperand(0).getValueType();
5756     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5757                                        DAG.getUNDEF(VVT), Mask);
5758     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5759                        DAG.getIntPtrConstant(0));
5760   }
5761
5762   return SDValue();
5763 }
5764
5765 SDValue
5766 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5767                                                SelectionDAG &DAG) const {
5768   EVT VT = Op.getValueType();
5769   EVT EltVT = VT.getVectorElementType();
5770   DebugLoc dl = Op.getDebugLoc();
5771
5772   SDValue N0 = Op.getOperand(0);
5773   SDValue N1 = Op.getOperand(1);
5774   SDValue N2 = Op.getOperand(2);
5775
5776   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5777       isa<ConstantSDNode>(N2)) {
5778     unsigned Opc;
5779     if (VT == MVT::v8i16)
5780       Opc = X86ISD::PINSRW;
5781     else if (VT == MVT::v16i8)
5782       Opc = X86ISD::PINSRB;
5783     else
5784       Opc = X86ISD::PINSRB;
5785
5786     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5787     // argument.
5788     if (N1.getValueType() != MVT::i32)
5789       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5790     if (N2.getValueType() != MVT::i32)
5791       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5792     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5793   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5794     // Bits [7:6] of the constant are the source select.  This will always be
5795     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5796     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5797     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5798     // Bits [5:4] of the constant are the destination select.  This is the
5799     //  value of the incoming immediate.
5800     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5801     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5802     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5803     // Create this as a scalar to vector..
5804     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5805     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5806   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5807     // PINSR* works with constant index.
5808     return Op;
5809   }
5810   return SDValue();
5811 }
5812
5813 SDValue
5814 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5815   EVT VT = Op.getValueType();
5816   EVT EltVT = VT.getVectorElementType();
5817
5818   if (Subtarget->hasSSE41())
5819     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5820
5821   if (EltVT == MVT::i8)
5822     return SDValue();
5823
5824   DebugLoc dl = Op.getDebugLoc();
5825   SDValue N0 = Op.getOperand(0);
5826   SDValue N1 = Op.getOperand(1);
5827   SDValue N2 = Op.getOperand(2);
5828
5829   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5830     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5831     // as its second argument.
5832     if (N1.getValueType() != MVT::i32)
5833       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5834     if (N2.getValueType() != MVT::i32)
5835       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5836     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5837   }
5838   return SDValue();
5839 }
5840
5841 SDValue
5842 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5843   DebugLoc dl = Op.getDebugLoc();
5844
5845   if (Op.getValueType() == MVT::v1i64 &&
5846       Op.getOperand(0).getValueType() == MVT::i64)
5847     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5848
5849   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5850   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5851          "Expected an SSE type!");
5852   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5853                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5854 }
5855
5856 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5857 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5858 // one of the above mentioned nodes. It has to be wrapped because otherwise
5859 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5860 // be used to form addressing mode. These wrapped nodes will be selected
5861 // into MOV32ri.
5862 SDValue
5863 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5864   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5865
5866   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5867   // global base reg.
5868   unsigned char OpFlag = 0;
5869   unsigned WrapperKind = X86ISD::Wrapper;
5870   CodeModel::Model M = getTargetMachine().getCodeModel();
5871
5872   if (Subtarget->isPICStyleRIPRel() &&
5873       (M == CodeModel::Small || M == CodeModel::Kernel))
5874     WrapperKind = X86ISD::WrapperRIP;
5875   else if (Subtarget->isPICStyleGOT())
5876     OpFlag = X86II::MO_GOTOFF;
5877   else if (Subtarget->isPICStyleStubPIC())
5878     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5879
5880   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5881                                              CP->getAlignment(),
5882                                              CP->getOffset(), OpFlag);
5883   DebugLoc DL = CP->getDebugLoc();
5884   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5885   // With PIC, the address is actually $g + Offset.
5886   if (OpFlag) {
5887     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5888                          DAG.getNode(X86ISD::GlobalBaseReg,
5889                                      DebugLoc(), getPointerTy()),
5890                          Result);
5891   }
5892
5893   return Result;
5894 }
5895
5896 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5897   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5898
5899   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5900   // global base reg.
5901   unsigned char OpFlag = 0;
5902   unsigned WrapperKind = X86ISD::Wrapper;
5903   CodeModel::Model M = getTargetMachine().getCodeModel();
5904
5905   if (Subtarget->isPICStyleRIPRel() &&
5906       (M == CodeModel::Small || M == CodeModel::Kernel))
5907     WrapperKind = X86ISD::WrapperRIP;
5908   else if (Subtarget->isPICStyleGOT())
5909     OpFlag = X86II::MO_GOTOFF;
5910   else if (Subtarget->isPICStyleStubPIC())
5911     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5912
5913   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5914                                           OpFlag);
5915   DebugLoc DL = JT->getDebugLoc();
5916   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5917
5918   // With PIC, the address is actually $g + Offset.
5919   if (OpFlag)
5920     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5921                          DAG.getNode(X86ISD::GlobalBaseReg,
5922                                      DebugLoc(), getPointerTy()),
5923                          Result);
5924
5925   return Result;
5926 }
5927
5928 SDValue
5929 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5930   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5931
5932   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5933   // global base reg.
5934   unsigned char OpFlag = 0;
5935   unsigned WrapperKind = X86ISD::Wrapper;
5936   CodeModel::Model M = getTargetMachine().getCodeModel();
5937
5938   if (Subtarget->isPICStyleRIPRel() &&
5939       (M == CodeModel::Small || M == CodeModel::Kernel))
5940     WrapperKind = X86ISD::WrapperRIP;
5941   else if (Subtarget->isPICStyleGOT())
5942     OpFlag = X86II::MO_GOTOFF;
5943   else if (Subtarget->isPICStyleStubPIC())
5944     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5945
5946   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5947
5948   DebugLoc DL = Op.getDebugLoc();
5949   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5950
5951
5952   // With PIC, the address is actually $g + Offset.
5953   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5954       !Subtarget->is64Bit()) {
5955     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5956                          DAG.getNode(X86ISD::GlobalBaseReg,
5957                                      DebugLoc(), getPointerTy()),
5958                          Result);
5959   }
5960
5961   return Result;
5962 }
5963
5964 SDValue
5965 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5966   // Create the TargetBlockAddressAddress node.
5967   unsigned char OpFlags =
5968     Subtarget->ClassifyBlockAddressReference();
5969   CodeModel::Model M = getTargetMachine().getCodeModel();
5970   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5971   DebugLoc dl = Op.getDebugLoc();
5972   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5973                                        /*isTarget=*/true, OpFlags);
5974
5975   if (Subtarget->isPICStyleRIPRel() &&
5976       (M == CodeModel::Small || M == CodeModel::Kernel))
5977     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5978   else
5979     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5980
5981   // With PIC, the address is actually $g + Offset.
5982   if (isGlobalRelativeToPICBase(OpFlags)) {
5983     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5984                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5985                          Result);
5986   }
5987
5988   return Result;
5989 }
5990
5991 SDValue
5992 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5993                                       int64_t Offset,
5994                                       SelectionDAG &DAG) const {
5995   // Create the TargetGlobalAddress node, folding in the constant
5996   // offset if it is legal.
5997   unsigned char OpFlags =
5998     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5999   CodeModel::Model M = getTargetMachine().getCodeModel();
6000   SDValue Result;
6001   if (OpFlags == X86II::MO_NO_FLAG &&
6002       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6003     // A direct static reference to a global.
6004     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6005     Offset = 0;
6006   } else {
6007     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6008   }
6009
6010   if (Subtarget->isPICStyleRIPRel() &&
6011       (M == CodeModel::Small || M == CodeModel::Kernel))
6012     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6013   else
6014     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6015
6016   // With PIC, the address is actually $g + Offset.
6017   if (isGlobalRelativeToPICBase(OpFlags)) {
6018     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6019                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6020                          Result);
6021   }
6022
6023   // For globals that require a load from a stub to get the address, emit the
6024   // load.
6025   if (isGlobalStubReference(OpFlags))
6026     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6027                          MachinePointerInfo::getGOT(), false, false, 0);
6028
6029   // If there was a non-zero offset that we didn't fold, create an explicit
6030   // addition for it.
6031   if (Offset != 0)
6032     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6033                          DAG.getConstant(Offset, getPointerTy()));
6034
6035   return Result;
6036 }
6037
6038 SDValue
6039 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6040   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6041   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6042   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6043 }
6044
6045 static SDValue
6046 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6047            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6048            unsigned char OperandFlags) {
6049   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6050   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6051   DebugLoc dl = GA->getDebugLoc();
6052   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6053                                            GA->getValueType(0),
6054                                            GA->getOffset(),
6055                                            OperandFlags);
6056   if (InFlag) {
6057     SDValue Ops[] = { Chain,  TGA, *InFlag };
6058     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6059   } else {
6060     SDValue Ops[]  = { Chain, TGA };
6061     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6062   }
6063
6064   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6065   MFI->setAdjustsStack(true);
6066
6067   SDValue Flag = Chain.getValue(1);
6068   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6069 }
6070
6071 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6072 static SDValue
6073 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6074                                 const EVT PtrVT) {
6075   SDValue InFlag;
6076   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6077   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6078                                      DAG.getNode(X86ISD::GlobalBaseReg,
6079                                                  DebugLoc(), PtrVT), InFlag);
6080   InFlag = Chain.getValue(1);
6081
6082   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6083 }
6084
6085 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6086 static SDValue
6087 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6088                                 const EVT PtrVT) {
6089   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6090                     X86::RAX, X86II::MO_TLSGD);
6091 }
6092
6093 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6094 // "local exec" model.
6095 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6096                                    const EVT PtrVT, TLSModel::Model model,
6097                                    bool is64Bit) {
6098   DebugLoc dl = GA->getDebugLoc();
6099
6100   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6101   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6102                                                          is64Bit ? 257 : 256));
6103
6104   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6105                                       DAG.getIntPtrConstant(0),
6106                                       MachinePointerInfo(Ptr), false, false, 0);
6107
6108   unsigned char OperandFlags = 0;
6109   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6110   // initialexec.
6111   unsigned WrapperKind = X86ISD::Wrapper;
6112   if (model == TLSModel::LocalExec) {
6113     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6114   } else if (is64Bit) {
6115     assert(model == TLSModel::InitialExec);
6116     OperandFlags = X86II::MO_GOTTPOFF;
6117     WrapperKind = X86ISD::WrapperRIP;
6118   } else {
6119     assert(model == TLSModel::InitialExec);
6120     OperandFlags = X86II::MO_INDNTPOFF;
6121   }
6122
6123   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6124   // exec)
6125   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6126                                            GA->getValueType(0),
6127                                            GA->getOffset(), OperandFlags);
6128   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6129
6130   if (model == TLSModel::InitialExec)
6131     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6132                          MachinePointerInfo::getGOT(), false, false, 0);
6133
6134   // The address of the thread local variable is the add of the thread
6135   // pointer with the offset of the variable.
6136   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6137 }
6138
6139 SDValue
6140 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6141
6142   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6143   const GlobalValue *GV = GA->getGlobal();
6144
6145   if (Subtarget->isTargetELF()) {
6146     // TODO: implement the "local dynamic" model
6147     // TODO: implement the "initial exec"model for pic executables
6148
6149     // If GV is an alias then use the aliasee for determining
6150     // thread-localness.
6151     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6152       GV = GA->resolveAliasedGlobal(false);
6153
6154     TLSModel::Model model
6155       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6156
6157     switch (model) {
6158       case TLSModel::GeneralDynamic:
6159       case TLSModel::LocalDynamic: // not implemented
6160         if (Subtarget->is64Bit())
6161           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6162         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6163
6164       case TLSModel::InitialExec:
6165       case TLSModel::LocalExec:
6166         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6167                                    Subtarget->is64Bit());
6168     }
6169   } else if (Subtarget->isTargetDarwin()) {
6170     // Darwin only has one model of TLS.  Lower to that.
6171     unsigned char OpFlag = 0;
6172     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6173                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6174
6175     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6176     // global base reg.
6177     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6178                   !Subtarget->is64Bit();
6179     if (PIC32)
6180       OpFlag = X86II::MO_TLVP_PIC_BASE;
6181     else
6182       OpFlag = X86II::MO_TLVP;
6183     DebugLoc DL = Op.getDebugLoc();
6184     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6185                                                 GA->getValueType(0),
6186                                                 GA->getOffset(), OpFlag);
6187     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6188
6189     // With PIC32, the address is actually $g + Offset.
6190     if (PIC32)
6191       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6192                            DAG.getNode(X86ISD::GlobalBaseReg,
6193                                        DebugLoc(), getPointerTy()),
6194                            Offset);
6195
6196     // Lowering the machine isd will make sure everything is in the right
6197     // location.
6198     SDValue Chain = DAG.getEntryNode();
6199     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6200     SDValue Args[] = { Chain, Offset };
6201     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6202
6203     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6204     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6205     MFI->setAdjustsStack(true);
6206     
6207     // And our return value (tls address) is in the standard call return value
6208     // location.
6209     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6210     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6211   }
6212
6213   assert(false &&
6214          "TLS not implemented for this target.");
6215
6216   llvm_unreachable("Unreachable");
6217   return SDValue();
6218 }
6219
6220
6221 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6222 /// take a 2 x i32 value to shift plus a shift amount.
6223 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6224   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6225   EVT VT = Op.getValueType();
6226   unsigned VTBits = VT.getSizeInBits();
6227   DebugLoc dl = Op.getDebugLoc();
6228   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6229   SDValue ShOpLo = Op.getOperand(0);
6230   SDValue ShOpHi = Op.getOperand(1);
6231   SDValue ShAmt  = Op.getOperand(2);
6232   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6233                                      DAG.getConstant(VTBits - 1, MVT::i8))
6234                        : DAG.getConstant(0, VT);
6235
6236   SDValue Tmp2, Tmp3;
6237   if (Op.getOpcode() == ISD::SHL_PARTS) {
6238     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6239     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6240   } else {
6241     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6242     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6243   }
6244
6245   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6246                                 DAG.getConstant(VTBits, MVT::i8));
6247   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6248                              AndNode, DAG.getConstant(0, MVT::i8));
6249
6250   SDValue Hi, Lo;
6251   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6252   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6253   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6254
6255   if (Op.getOpcode() == ISD::SHL_PARTS) {
6256     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6257     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6258   } else {
6259     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6260     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6261   }
6262
6263   SDValue Ops[2] = { Lo, Hi };
6264   return DAG.getMergeValues(Ops, 2, dl);
6265 }
6266
6267 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6268                                            SelectionDAG &DAG) const {
6269   EVT SrcVT = Op.getOperand(0).getValueType();
6270
6271   if (SrcVT.isVector())
6272     return SDValue();
6273
6274   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6275          "Unknown SINT_TO_FP to lower!");
6276
6277   // These are really Legal; return the operand so the caller accepts it as
6278   // Legal.
6279   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6280     return Op;
6281   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6282       Subtarget->is64Bit()) {
6283     return Op;
6284   }
6285
6286   DebugLoc dl = Op.getDebugLoc();
6287   unsigned Size = SrcVT.getSizeInBits()/8;
6288   MachineFunction &MF = DAG.getMachineFunction();
6289   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6290   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6291   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6292                                StackSlot,
6293                                MachinePointerInfo::getFixedStack(SSFI),
6294                                false, false, 0);
6295   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6296 }
6297
6298 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6299                                      SDValue StackSlot,
6300                                      SelectionDAG &DAG) const {
6301   // Build the FILD
6302   DebugLoc DL = Op.getDebugLoc();
6303   SDVTList Tys;
6304   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6305   if (useSSE)
6306     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6307   else
6308     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6309
6310   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6311
6312   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6313   MachineMemOperand *MMO =
6314     DAG.getMachineFunction()
6315     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6316                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6317
6318   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6319   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6320                                            X86ISD::FILD, DL,
6321                                            Tys, Ops, array_lengthof(Ops),
6322                                            SrcVT, MMO);
6323
6324   if (useSSE) {
6325     Chain = Result.getValue(1);
6326     SDValue InFlag = Result.getValue(2);
6327
6328     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6329     // shouldn't be necessary except that RFP cannot be live across
6330     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6331     MachineFunction &MF = DAG.getMachineFunction();
6332     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6333     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6334     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6335     Tys = DAG.getVTList(MVT::Other);
6336     SDValue Ops[] = {
6337       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6338     };
6339     MachineMemOperand *MMO =
6340       DAG.getMachineFunction()
6341       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6342                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6343
6344     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6345                                     Ops, array_lengthof(Ops),
6346                                     Op.getValueType(), MMO);
6347     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6348                          MachinePointerInfo::getFixedStack(SSFI),
6349                          false, false, 0);
6350   }
6351
6352   return Result;
6353 }
6354
6355 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6356 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6357                                                SelectionDAG &DAG) const {
6358   // This algorithm is not obvious. Here it is in C code, more or less:
6359   /*
6360     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6361       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6362       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6363
6364       // Copy ints to xmm registers.
6365       __m128i xh = _mm_cvtsi32_si128( hi );
6366       __m128i xl = _mm_cvtsi32_si128( lo );
6367
6368       // Combine into low half of a single xmm register.
6369       __m128i x = _mm_unpacklo_epi32( xh, xl );
6370       __m128d d;
6371       double sd;
6372
6373       // Merge in appropriate exponents to give the integer bits the right
6374       // magnitude.
6375       x = _mm_unpacklo_epi32( x, exp );
6376
6377       // Subtract away the biases to deal with the IEEE-754 double precision
6378       // implicit 1.
6379       d = _mm_sub_pd( (__m128d) x, bias );
6380
6381       // All conversions up to here are exact. The correctly rounded result is
6382       // calculated using the current rounding mode using the following
6383       // horizontal add.
6384       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6385       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6386                                 // store doesn't really need to be here (except
6387                                 // maybe to zero the other double)
6388       return sd;
6389     }
6390   */
6391
6392   DebugLoc dl = Op.getDebugLoc();
6393   LLVMContext *Context = DAG.getContext();
6394
6395   // Build some magic constants.
6396   std::vector<Constant*> CV0;
6397   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6398   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6399   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6400   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6401   Constant *C0 = ConstantVector::get(CV0);
6402   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6403
6404   std::vector<Constant*> CV1;
6405   CV1.push_back(
6406     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6407   CV1.push_back(
6408     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6409   Constant *C1 = ConstantVector::get(CV1);
6410   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6411
6412   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6413                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6414                                         Op.getOperand(0),
6415                                         DAG.getIntPtrConstant(1)));
6416   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6417                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6418                                         Op.getOperand(0),
6419                                         DAG.getIntPtrConstant(0)));
6420   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6421   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6422                               MachinePointerInfo::getConstantPool(),
6423                               false, false, 16);
6424   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6425   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6426   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6427                               MachinePointerInfo::getConstantPool(),
6428                               false, false, 16);
6429   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6430
6431   // Add the halves; easiest way is to swap them into another reg first.
6432   int ShufMask[2] = { 1, -1 };
6433   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6434                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6435   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6436   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6437                      DAG.getIntPtrConstant(0));
6438 }
6439
6440 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6441 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6442                                                SelectionDAG &DAG) const {
6443   DebugLoc dl = Op.getDebugLoc();
6444   // FP constant to bias correct the final result.
6445   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6446                                    MVT::f64);
6447
6448   // Load the 32-bit value into an XMM register.
6449   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6450                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6451                                          Op.getOperand(0),
6452                                          DAG.getIntPtrConstant(0)));
6453
6454   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6455                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6456                      DAG.getIntPtrConstant(0));
6457
6458   // Or the load with the bias.
6459   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6460                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6461                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6462                                                    MVT::v2f64, Load)),
6463                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6464                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6465                                                    MVT::v2f64, Bias)));
6466   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6467                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6468                    DAG.getIntPtrConstant(0));
6469
6470   // Subtract the bias.
6471   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6472
6473   // Handle final rounding.
6474   EVT DestVT = Op.getValueType();
6475
6476   if (DestVT.bitsLT(MVT::f64)) {
6477     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6478                        DAG.getIntPtrConstant(0));
6479   } else if (DestVT.bitsGT(MVT::f64)) {
6480     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6481   }
6482
6483   // Handle final rounding.
6484   return Sub;
6485 }
6486
6487 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6488                                            SelectionDAG &DAG) const {
6489   SDValue N0 = Op.getOperand(0);
6490   DebugLoc dl = Op.getDebugLoc();
6491
6492   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6493   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6494   // the optimization here.
6495   if (DAG.SignBitIsZero(N0))
6496     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6497
6498   EVT SrcVT = N0.getValueType();
6499   EVT DstVT = Op.getValueType();
6500   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6501     return LowerUINT_TO_FP_i64(Op, DAG);
6502   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6503     return LowerUINT_TO_FP_i32(Op, DAG);
6504
6505   // Make a 64-bit buffer, and use it to build an FILD.
6506   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6507   if (SrcVT == MVT::i32) {
6508     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6509     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6510                                      getPointerTy(), StackSlot, WordOff);
6511     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6512                                   StackSlot, MachinePointerInfo(),
6513                                   false, false, 0);
6514     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6515                                   OffsetSlot, MachinePointerInfo(),
6516                                   false, false, 0);
6517     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6518     return Fild;
6519   }
6520
6521   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6522   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6523                                 StackSlot, MachinePointerInfo(),
6524                                false, false, 0);
6525   // For i64 source, we need to add the appropriate power of 2 if the input
6526   // was negative.  This is the same as the optimization in
6527   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6528   // we must be careful to do the computation in x87 extended precision, not
6529   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6530   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6531   MachineMemOperand *MMO =
6532     DAG.getMachineFunction()
6533     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6534                           MachineMemOperand::MOLoad, 8, 8);
6535
6536   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6537   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6538   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6539                                          MVT::i64, MMO);
6540
6541   APInt FF(32, 0x5F800000ULL);
6542
6543   // Check whether the sign bit is set.
6544   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6545                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6546                                  ISD::SETLT);
6547
6548   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6549   SDValue FudgePtr = DAG.getConstantPool(
6550                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6551                                          getPointerTy());
6552
6553   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6554   SDValue Zero = DAG.getIntPtrConstant(0);
6555   SDValue Four = DAG.getIntPtrConstant(4);
6556   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6557                                Zero, Four);
6558   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6559
6560   // Load the value out, extending it from f32 to f80.
6561   // FIXME: Avoid the extend by constructing the right constant pool?
6562   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6563                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6564                                  MVT::f32, false, false, 4);
6565   // Extend everything to 80 bits to force it to be done on x87.
6566   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6567   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6568 }
6569
6570 std::pair<SDValue,SDValue> X86TargetLowering::
6571 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6572   DebugLoc DL = Op.getDebugLoc();
6573
6574   EVT DstTy = Op.getValueType();
6575
6576   if (!IsSigned) {
6577     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6578     DstTy = MVT::i64;
6579   }
6580
6581   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6582          DstTy.getSimpleVT() >= MVT::i16 &&
6583          "Unknown FP_TO_SINT to lower!");
6584
6585   // These are really Legal.
6586   if (DstTy == MVT::i32 &&
6587       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6588     return std::make_pair(SDValue(), SDValue());
6589   if (Subtarget->is64Bit() &&
6590       DstTy == MVT::i64 &&
6591       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6592     return std::make_pair(SDValue(), SDValue());
6593
6594   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6595   // stack slot.
6596   MachineFunction &MF = DAG.getMachineFunction();
6597   unsigned MemSize = DstTy.getSizeInBits()/8;
6598   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6599   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6600
6601
6602
6603   unsigned Opc;
6604   switch (DstTy.getSimpleVT().SimpleTy) {
6605   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6606   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6607   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6608   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6609   }
6610
6611   SDValue Chain = DAG.getEntryNode();
6612   SDValue Value = Op.getOperand(0);
6613   EVT TheVT = Op.getOperand(0).getValueType();
6614   if (isScalarFPTypeInSSEReg(TheVT)) {
6615     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6616     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6617                          MachinePointerInfo::getFixedStack(SSFI),
6618                          false, false, 0);
6619     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6620     SDValue Ops[] = {
6621       Chain, StackSlot, DAG.getValueType(TheVT)
6622     };
6623
6624     MachineMemOperand *MMO =
6625       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6626                               MachineMemOperand::MOLoad, MemSize, MemSize);
6627     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6628                                     DstTy, MMO);
6629     Chain = Value.getValue(1);
6630     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6631     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6632   }
6633
6634   MachineMemOperand *MMO =
6635     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6636                             MachineMemOperand::MOStore, MemSize, MemSize);
6637
6638   // Build the FP_TO_INT*_IN_MEM
6639   SDValue Ops[] = { Chain, Value, StackSlot };
6640   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6641                                          Ops, 3, DstTy, MMO);
6642
6643   return std::make_pair(FIST, StackSlot);
6644 }
6645
6646 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6647                                            SelectionDAG &DAG) const {
6648   if (Op.getValueType().isVector())
6649     return SDValue();
6650
6651   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6652   SDValue FIST = Vals.first, StackSlot = Vals.second;
6653   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6654   if (FIST.getNode() == 0) return Op;
6655
6656   // Load the result.
6657   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6658                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6659 }
6660
6661 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6662                                            SelectionDAG &DAG) const {
6663   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6664   SDValue FIST = Vals.first, StackSlot = Vals.second;
6665   assert(FIST.getNode() && "Unexpected failure");
6666
6667   // Load the result.
6668   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6669                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6670 }
6671
6672 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6673                                      SelectionDAG &DAG) const {
6674   LLVMContext *Context = DAG.getContext();
6675   DebugLoc dl = Op.getDebugLoc();
6676   EVT VT = Op.getValueType();
6677   EVT EltVT = VT;
6678   if (VT.isVector())
6679     EltVT = VT.getVectorElementType();
6680   std::vector<Constant*> CV;
6681   if (EltVT == MVT::f64) {
6682     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6683     CV.push_back(C);
6684     CV.push_back(C);
6685   } else {
6686     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6687     CV.push_back(C);
6688     CV.push_back(C);
6689     CV.push_back(C);
6690     CV.push_back(C);
6691   }
6692   Constant *C = ConstantVector::get(CV);
6693   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6694   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6695                              MachinePointerInfo::getConstantPool(),
6696                              false, false, 16);
6697   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6698 }
6699
6700 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6701   LLVMContext *Context = DAG.getContext();
6702   DebugLoc dl = Op.getDebugLoc();
6703   EVT VT = Op.getValueType();
6704   EVT EltVT = VT;
6705   if (VT.isVector())
6706     EltVT = VT.getVectorElementType();
6707   std::vector<Constant*> CV;
6708   if (EltVT == MVT::f64) {
6709     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6710     CV.push_back(C);
6711     CV.push_back(C);
6712   } else {
6713     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6714     CV.push_back(C);
6715     CV.push_back(C);
6716     CV.push_back(C);
6717     CV.push_back(C);
6718   }
6719   Constant *C = ConstantVector::get(CV);
6720   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6721   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6722                              MachinePointerInfo::getConstantPool(),
6723                              false, false, 16);
6724   if (VT.isVector()) {
6725     return DAG.getNode(ISD::BITCAST, dl, VT,
6726                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6727                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6728                                 Op.getOperand(0)),
6729                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6730   } else {
6731     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6732   }
6733 }
6734
6735 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6736   LLVMContext *Context = DAG.getContext();
6737   SDValue Op0 = Op.getOperand(0);
6738   SDValue Op1 = Op.getOperand(1);
6739   DebugLoc dl = Op.getDebugLoc();
6740   EVT VT = Op.getValueType();
6741   EVT SrcVT = Op1.getValueType();
6742
6743   // If second operand is smaller, extend it first.
6744   if (SrcVT.bitsLT(VT)) {
6745     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6746     SrcVT = VT;
6747   }
6748   // And if it is bigger, shrink it first.
6749   if (SrcVT.bitsGT(VT)) {
6750     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6751     SrcVT = VT;
6752   }
6753
6754   // At this point the operands and the result should have the same
6755   // type, and that won't be f80 since that is not custom lowered.
6756
6757   // First get the sign bit of second operand.
6758   std::vector<Constant*> CV;
6759   if (SrcVT == MVT::f64) {
6760     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6761     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6762   } else {
6763     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6764     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6765     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6766     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6767   }
6768   Constant *C = ConstantVector::get(CV);
6769   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6770   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6771                               MachinePointerInfo::getConstantPool(),
6772                               false, false, 16);
6773   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6774
6775   // Shift sign bit right or left if the two operands have different types.
6776   if (SrcVT.bitsGT(VT)) {
6777     // Op0 is MVT::f32, Op1 is MVT::f64.
6778     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6779     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6780                           DAG.getConstant(32, MVT::i32));
6781     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6782     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6783                           DAG.getIntPtrConstant(0));
6784   }
6785
6786   // Clear first operand sign bit.
6787   CV.clear();
6788   if (VT == MVT::f64) {
6789     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6790     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6791   } else {
6792     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6793     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6794     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6795     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6796   }
6797   C = ConstantVector::get(CV);
6798   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6799   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6800                               MachinePointerInfo::getConstantPool(),
6801                               false, false, 16);
6802   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6803
6804   // Or the value with the sign bit.
6805   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6806 }
6807
6808 /// Emit nodes that will be selected as "test Op0,Op0", or something
6809 /// equivalent.
6810 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6811                                     SelectionDAG &DAG) const {
6812   DebugLoc dl = Op.getDebugLoc();
6813
6814   // CF and OF aren't always set the way we want. Determine which
6815   // of these we need.
6816   bool NeedCF = false;
6817   bool NeedOF = false;
6818   switch (X86CC) {
6819   default: break;
6820   case X86::COND_A: case X86::COND_AE:
6821   case X86::COND_B: case X86::COND_BE:
6822     NeedCF = true;
6823     break;
6824   case X86::COND_G: case X86::COND_GE:
6825   case X86::COND_L: case X86::COND_LE:
6826   case X86::COND_O: case X86::COND_NO:
6827     NeedOF = true;
6828     break;
6829   }
6830
6831   // See if we can use the EFLAGS value from the operand instead of
6832   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6833   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6834   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6835     // Emit a CMP with 0, which is the TEST pattern.
6836     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6837                        DAG.getConstant(0, Op.getValueType()));
6838
6839   unsigned Opcode = 0;
6840   unsigned NumOperands = 0;
6841   switch (Op.getNode()->getOpcode()) {
6842   case ISD::ADD:
6843     // Due to an isel shortcoming, be conservative if this add is likely to be
6844     // selected as part of a load-modify-store instruction. When the root node
6845     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6846     // uses of other nodes in the match, such as the ADD in this case. This
6847     // leads to the ADD being left around and reselected, with the result being
6848     // two adds in the output.  Alas, even if none our users are stores, that
6849     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6850     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6851     // climbing the DAG back to the root, and it doesn't seem to be worth the
6852     // effort.
6853     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6854            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6855       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6856         goto default_case;
6857
6858     if (ConstantSDNode *C =
6859         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6860       // An add of one will be selected as an INC.
6861       if (C->getAPIntValue() == 1) {
6862         Opcode = X86ISD::INC;
6863         NumOperands = 1;
6864         break;
6865       }
6866
6867       // An add of negative one (subtract of one) will be selected as a DEC.
6868       if (C->getAPIntValue().isAllOnesValue()) {
6869         Opcode = X86ISD::DEC;
6870         NumOperands = 1;
6871         break;
6872       }
6873     }
6874
6875     // Otherwise use a regular EFLAGS-setting add.
6876     Opcode = X86ISD::ADD;
6877     NumOperands = 2;
6878     break;
6879   case ISD::AND: {
6880     // If the primary and result isn't used, don't bother using X86ISD::AND,
6881     // because a TEST instruction will be better.
6882     bool NonFlagUse = false;
6883     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6884            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6885       SDNode *User = *UI;
6886       unsigned UOpNo = UI.getOperandNo();
6887       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6888         // Look pass truncate.
6889         UOpNo = User->use_begin().getOperandNo();
6890         User = *User->use_begin();
6891       }
6892
6893       if (User->getOpcode() != ISD::BRCOND &&
6894           User->getOpcode() != ISD::SETCC &&
6895           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6896         NonFlagUse = true;
6897         break;
6898       }
6899     }
6900
6901     if (!NonFlagUse)
6902       break;
6903   }
6904     // FALL THROUGH
6905   case ISD::SUB:
6906   case ISD::OR:
6907   case ISD::XOR:
6908     // Due to the ISEL shortcoming noted above, be conservative if this op is
6909     // likely to be selected as part of a load-modify-store instruction.
6910     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6911            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6912       if (UI->getOpcode() == ISD::STORE)
6913         goto default_case;
6914
6915     // Otherwise use a regular EFLAGS-setting instruction.
6916     switch (Op.getNode()->getOpcode()) {
6917     default: llvm_unreachable("unexpected operator!");
6918     case ISD::SUB: Opcode = X86ISD::SUB; break;
6919     case ISD::OR:  Opcode = X86ISD::OR;  break;
6920     case ISD::XOR: Opcode = X86ISD::XOR; break;
6921     case ISD::AND: Opcode = X86ISD::AND; break;
6922     }
6923
6924     NumOperands = 2;
6925     break;
6926   case X86ISD::ADD:
6927   case X86ISD::SUB:
6928   case X86ISD::INC:
6929   case X86ISD::DEC:
6930   case X86ISD::OR:
6931   case X86ISD::XOR:
6932   case X86ISD::AND:
6933     return SDValue(Op.getNode(), 1);
6934   default:
6935   default_case:
6936     break;
6937   }
6938
6939   if (Opcode == 0)
6940     // Emit a CMP with 0, which is the TEST pattern.
6941     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6942                        DAG.getConstant(0, Op.getValueType()));
6943
6944   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6945   SmallVector<SDValue, 4> Ops;
6946   for (unsigned i = 0; i != NumOperands; ++i)
6947     Ops.push_back(Op.getOperand(i));
6948
6949   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6950   DAG.ReplaceAllUsesWith(Op, New);
6951   return SDValue(New.getNode(), 1);
6952 }
6953
6954 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6955 /// equivalent.
6956 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6957                                    SelectionDAG &DAG) const {
6958   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6959     if (C->getAPIntValue() == 0)
6960       return EmitTest(Op0, X86CC, DAG);
6961
6962   DebugLoc dl = Op0.getDebugLoc();
6963   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6964 }
6965
6966 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6967 /// if it's possible.
6968 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6969                                      DebugLoc dl, SelectionDAG &DAG) const {
6970   SDValue Op0 = And.getOperand(0);
6971   SDValue Op1 = And.getOperand(1);
6972   if (Op0.getOpcode() == ISD::TRUNCATE)
6973     Op0 = Op0.getOperand(0);
6974   if (Op1.getOpcode() == ISD::TRUNCATE)
6975     Op1 = Op1.getOperand(0);
6976
6977   SDValue LHS, RHS;
6978   if (Op1.getOpcode() == ISD::SHL)
6979     std::swap(Op0, Op1);
6980   if (Op0.getOpcode() == ISD::SHL) {
6981     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6982       if (And00C->getZExtValue() == 1) {
6983         // If we looked past a truncate, check that it's only truncating away
6984         // known zeros.
6985         unsigned BitWidth = Op0.getValueSizeInBits();
6986         unsigned AndBitWidth = And.getValueSizeInBits();
6987         if (BitWidth > AndBitWidth) {
6988           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6989           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6990           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6991             return SDValue();
6992         }
6993         LHS = Op1;
6994         RHS = Op0.getOperand(1);
6995       }
6996   } else if (Op1.getOpcode() == ISD::Constant) {
6997     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6998     SDValue AndLHS = Op0;
6999     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7000       LHS = AndLHS.getOperand(0);
7001       RHS = AndLHS.getOperand(1);
7002     }
7003   }
7004
7005   if (LHS.getNode()) {
7006     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7007     // instruction.  Since the shift amount is in-range-or-undefined, we know
7008     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7009     // the encoding for the i16 version is larger than the i32 version.
7010     // Also promote i16 to i32 for performance / code size reason.
7011     if (LHS.getValueType() == MVT::i8 ||
7012         LHS.getValueType() == MVT::i16)
7013       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7014
7015     // If the operand types disagree, extend the shift amount to match.  Since
7016     // BT ignores high bits (like shifts) we can use anyextend.
7017     if (LHS.getValueType() != RHS.getValueType())
7018       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7019
7020     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7021     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7022     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7023                        DAG.getConstant(Cond, MVT::i8), BT);
7024   }
7025
7026   return SDValue();
7027 }
7028
7029 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7030   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7031   SDValue Op0 = Op.getOperand(0);
7032   SDValue Op1 = Op.getOperand(1);
7033   DebugLoc dl = Op.getDebugLoc();
7034   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7035
7036   // Optimize to BT if possible.
7037   // Lower (X & (1 << N)) == 0 to BT(X, N).
7038   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7039   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7040   if (Op0.getOpcode() == ISD::AND &&
7041       Op0.hasOneUse() &&
7042       Op1.getOpcode() == ISD::Constant &&
7043       cast<ConstantSDNode>(Op1)->isNullValue() &&
7044       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7045     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7046     if (NewSetCC.getNode())
7047       return NewSetCC;
7048   }
7049
7050   // Look for "(setcc) == / != 1" to avoid unnecessary setcc.
7051   if (Op0.getOpcode() == X86ISD::SETCC &&
7052       Op1.getOpcode() == ISD::Constant &&
7053       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7054        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7055       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7056     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7057     bool Invert = (CC == ISD::SETNE) ^
7058       cast<ConstantSDNode>(Op1)->isNullValue();
7059     if (Invert)
7060       CCode = X86::GetOppositeBranchCondition(CCode);
7061     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7062                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7063   }
7064
7065   bool isFP = Op1.getValueType().isFloatingPoint();
7066   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7067   if (X86CC == X86::COND_INVALID)
7068     return SDValue();
7069
7070   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7071
7072   // Use sbb x, x to materialize carry bit into a GPR.
7073   if (X86CC == X86::COND_B)
7074     return DAG.getNode(ISD::AND, dl, MVT::i8,
7075                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7076                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7077                        DAG.getConstant(1, MVT::i8));
7078
7079   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7080                      DAG.getConstant(X86CC, MVT::i8), Cond);
7081 }
7082
7083 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7084   SDValue Cond;
7085   SDValue Op0 = Op.getOperand(0);
7086   SDValue Op1 = Op.getOperand(1);
7087   SDValue CC = Op.getOperand(2);
7088   EVT VT = Op.getValueType();
7089   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7090   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7091   DebugLoc dl = Op.getDebugLoc();
7092
7093   if (isFP) {
7094     unsigned SSECC = 8;
7095     EVT VT0 = Op0.getValueType();
7096     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7097     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7098     bool Swap = false;
7099
7100     switch (SetCCOpcode) {
7101     default: break;
7102     case ISD::SETOEQ:
7103     case ISD::SETEQ:  SSECC = 0; break;
7104     case ISD::SETOGT:
7105     case ISD::SETGT: Swap = true; // Fallthrough
7106     case ISD::SETLT:
7107     case ISD::SETOLT: SSECC = 1; break;
7108     case ISD::SETOGE:
7109     case ISD::SETGE: Swap = true; // Fallthrough
7110     case ISD::SETLE:
7111     case ISD::SETOLE: SSECC = 2; break;
7112     case ISD::SETUO:  SSECC = 3; break;
7113     case ISD::SETUNE:
7114     case ISD::SETNE:  SSECC = 4; break;
7115     case ISD::SETULE: Swap = true;
7116     case ISD::SETUGE: SSECC = 5; break;
7117     case ISD::SETULT: Swap = true;
7118     case ISD::SETUGT: SSECC = 6; break;
7119     case ISD::SETO:   SSECC = 7; break;
7120     }
7121     if (Swap)
7122       std::swap(Op0, Op1);
7123
7124     // In the two special cases we can't handle, emit two comparisons.
7125     if (SSECC == 8) {
7126       if (SetCCOpcode == ISD::SETUEQ) {
7127         SDValue UNORD, EQ;
7128         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7129         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7130         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7131       }
7132       else if (SetCCOpcode == ISD::SETONE) {
7133         SDValue ORD, NEQ;
7134         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7135         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7136         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7137       }
7138       llvm_unreachable("Illegal FP comparison");
7139     }
7140     // Handle all other FP comparisons here.
7141     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7142   }
7143
7144   // We are handling one of the integer comparisons here.  Since SSE only has
7145   // GT and EQ comparisons for integer, swapping operands and multiple
7146   // operations may be required for some comparisons.
7147   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7148   bool Swap = false, Invert = false, FlipSigns = false;
7149
7150   switch (VT.getSimpleVT().SimpleTy) {
7151   default: break;
7152   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7153   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7154   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7155   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7156   }
7157
7158   switch (SetCCOpcode) {
7159   default: break;
7160   case ISD::SETNE:  Invert = true;
7161   case ISD::SETEQ:  Opc = EQOpc; break;
7162   case ISD::SETLT:  Swap = true;
7163   case ISD::SETGT:  Opc = GTOpc; break;
7164   case ISD::SETGE:  Swap = true;
7165   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7166   case ISD::SETULT: Swap = true;
7167   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7168   case ISD::SETUGE: Swap = true;
7169   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7170   }
7171   if (Swap)
7172     std::swap(Op0, Op1);
7173
7174   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7175   // bits of the inputs before performing those operations.
7176   if (FlipSigns) {
7177     EVT EltVT = VT.getVectorElementType();
7178     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7179                                       EltVT);
7180     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7181     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7182                                     SignBits.size());
7183     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7184     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7185   }
7186
7187   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7188
7189   // If the logical-not of the result is required, perform that now.
7190   if (Invert)
7191     Result = DAG.getNOT(dl, Result, VT);
7192
7193   return Result;
7194 }
7195
7196 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7197 static bool isX86LogicalCmp(SDValue Op) {
7198   unsigned Opc = Op.getNode()->getOpcode();
7199   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7200     return true;
7201   if (Op.getResNo() == 1 &&
7202       (Opc == X86ISD::ADD ||
7203        Opc == X86ISD::SUB ||
7204        Opc == X86ISD::SMUL ||
7205        Opc == X86ISD::UMUL ||
7206        Opc == X86ISD::INC ||
7207        Opc == X86ISD::DEC ||
7208        Opc == X86ISD::OR ||
7209        Opc == X86ISD::XOR ||
7210        Opc == X86ISD::AND))
7211     return true;
7212
7213   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7214     return true;
7215     
7216   return false;
7217 }
7218
7219 static bool isZero(SDValue V) {
7220   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7221   return C && C->isNullValue();
7222 }
7223
7224 static bool isAllOnes(SDValue V) {
7225   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7226   return C && C->isAllOnesValue();
7227 }
7228
7229 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7230   bool addTest = true;
7231   SDValue Cond  = Op.getOperand(0);
7232   SDValue Op1 = Op.getOperand(1);
7233   SDValue Op2 = Op.getOperand(2);
7234   DebugLoc DL = Op.getDebugLoc();
7235   SDValue CC;
7236
7237   if (Cond.getOpcode() == ISD::SETCC) {
7238     SDValue NewCond = LowerSETCC(Cond, DAG);
7239     if (NewCond.getNode())
7240       Cond = NewCond;
7241   }
7242
7243   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7244   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7245   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7246   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7247   if (Cond.getOpcode() == X86ISD::SETCC &&
7248       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7249       isZero(Cond.getOperand(1).getOperand(1))) {
7250     SDValue Cmp = Cond.getOperand(1);
7251     
7252     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7253     
7254     if ((isAllOnes(Op1) || isAllOnes(Op2)) && 
7255         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7256       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7257
7258       SDValue CmpOp0 = Cmp.getOperand(0);
7259       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7260                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7261       
7262       SDValue Res =   // Res = 0 or -1.
7263         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7264                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7265       
7266       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7267         Res = DAG.getNOT(DL, Res, Res.getValueType());
7268       
7269       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7270       if (N2C == 0 || !N2C->isNullValue())
7271         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7272       return Res;
7273     }
7274   }
7275
7276   // Look past (and (setcc_carry (cmp ...)), 1).
7277   if (Cond.getOpcode() == ISD::AND &&
7278       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7279     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7280     if (C && C->getAPIntValue() == 1)
7281       Cond = Cond.getOperand(0);
7282   }
7283
7284   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7285   // setting operand in place of the X86ISD::SETCC.
7286   if (Cond.getOpcode() == X86ISD::SETCC ||
7287       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7288     CC = Cond.getOperand(0);
7289
7290     SDValue Cmp = Cond.getOperand(1);
7291     unsigned Opc = Cmp.getOpcode();
7292     EVT VT = Op.getValueType();
7293
7294     bool IllegalFPCMov = false;
7295     if (VT.isFloatingPoint() && !VT.isVector() &&
7296         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7297       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7298
7299     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7300         Opc == X86ISD::BT) { // FIXME
7301       Cond = Cmp;
7302       addTest = false;
7303     }
7304   }
7305
7306   if (addTest) {
7307     // Look pass the truncate.
7308     if (Cond.getOpcode() == ISD::TRUNCATE)
7309       Cond = Cond.getOperand(0);
7310
7311     // We know the result of AND is compared against zero. Try to match
7312     // it to BT.
7313     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7314       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7315       if (NewSetCC.getNode()) {
7316         CC = NewSetCC.getOperand(0);
7317         Cond = NewSetCC.getOperand(1);
7318         addTest = false;
7319       }
7320     }
7321   }
7322
7323   if (addTest) {
7324     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7325     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7326   }
7327
7328   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7329   // condition is true.
7330   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7331   SDValue Ops[] = { Op2, Op1, CC, Cond };
7332   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7333 }
7334
7335 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7336 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7337 // from the AND / OR.
7338 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7339   Opc = Op.getOpcode();
7340   if (Opc != ISD::OR && Opc != ISD::AND)
7341     return false;
7342   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7343           Op.getOperand(0).hasOneUse() &&
7344           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7345           Op.getOperand(1).hasOneUse());
7346 }
7347
7348 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7349 // 1 and that the SETCC node has a single use.
7350 static bool isXor1OfSetCC(SDValue Op) {
7351   if (Op.getOpcode() != ISD::XOR)
7352     return false;
7353   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7354   if (N1C && N1C->getAPIntValue() == 1) {
7355     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7356       Op.getOperand(0).hasOneUse();
7357   }
7358   return false;
7359 }
7360
7361 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7362   bool addTest = true;
7363   SDValue Chain = Op.getOperand(0);
7364   SDValue Cond  = Op.getOperand(1);
7365   SDValue Dest  = Op.getOperand(2);
7366   DebugLoc dl = Op.getDebugLoc();
7367   SDValue CC;
7368
7369   if (Cond.getOpcode() == ISD::SETCC) {
7370     SDValue NewCond = LowerSETCC(Cond, DAG);
7371     if (NewCond.getNode())
7372       Cond = NewCond;
7373   }
7374 #if 0
7375   // FIXME: LowerXALUO doesn't handle these!!
7376   else if (Cond.getOpcode() == X86ISD::ADD  ||
7377            Cond.getOpcode() == X86ISD::SUB  ||
7378            Cond.getOpcode() == X86ISD::SMUL ||
7379            Cond.getOpcode() == X86ISD::UMUL)
7380     Cond = LowerXALUO(Cond, DAG);
7381 #endif
7382
7383   // Look pass (and (setcc_carry (cmp ...)), 1).
7384   if (Cond.getOpcode() == ISD::AND &&
7385       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7386     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7387     if (C && C->getAPIntValue() == 1)
7388       Cond = Cond.getOperand(0);
7389   }
7390
7391   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7392   // setting operand in place of the X86ISD::SETCC.
7393   if (Cond.getOpcode() == X86ISD::SETCC ||
7394       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7395     CC = Cond.getOperand(0);
7396
7397     SDValue Cmp = Cond.getOperand(1);
7398     unsigned Opc = Cmp.getOpcode();
7399     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7400     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7401       Cond = Cmp;
7402       addTest = false;
7403     } else {
7404       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7405       default: break;
7406       case X86::COND_O:
7407       case X86::COND_B:
7408         // These can only come from an arithmetic instruction with overflow,
7409         // e.g. SADDO, UADDO.
7410         Cond = Cond.getNode()->getOperand(1);
7411         addTest = false;
7412         break;
7413       }
7414     }
7415   } else {
7416     unsigned CondOpc;
7417     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7418       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7419       if (CondOpc == ISD::OR) {
7420         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7421         // two branches instead of an explicit OR instruction with a
7422         // separate test.
7423         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7424             isX86LogicalCmp(Cmp)) {
7425           CC = Cond.getOperand(0).getOperand(0);
7426           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7427                               Chain, Dest, CC, Cmp);
7428           CC = Cond.getOperand(1).getOperand(0);
7429           Cond = Cmp;
7430           addTest = false;
7431         }
7432       } else { // ISD::AND
7433         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7434         // two branches instead of an explicit AND instruction with a
7435         // separate test. However, we only do this if this block doesn't
7436         // have a fall-through edge, because this requires an explicit
7437         // jmp when the condition is false.
7438         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7439             isX86LogicalCmp(Cmp) &&
7440             Op.getNode()->hasOneUse()) {
7441           X86::CondCode CCode =
7442             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7443           CCode = X86::GetOppositeBranchCondition(CCode);
7444           CC = DAG.getConstant(CCode, MVT::i8);
7445           SDNode *User = *Op.getNode()->use_begin();
7446           // Look for an unconditional branch following this conditional branch.
7447           // We need this because we need to reverse the successors in order
7448           // to implement FCMP_OEQ.
7449           if (User->getOpcode() == ISD::BR) {
7450             SDValue FalseBB = User->getOperand(1);
7451             SDNode *NewBR =
7452               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7453             assert(NewBR == User);
7454             (void)NewBR;
7455             Dest = FalseBB;
7456
7457             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7458                                 Chain, Dest, CC, Cmp);
7459             X86::CondCode CCode =
7460               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7461             CCode = X86::GetOppositeBranchCondition(CCode);
7462             CC = DAG.getConstant(CCode, MVT::i8);
7463             Cond = Cmp;
7464             addTest = false;
7465           }
7466         }
7467       }
7468     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7469       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7470       // It should be transformed during dag combiner except when the condition
7471       // is set by a arithmetics with overflow node.
7472       X86::CondCode CCode =
7473         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7474       CCode = X86::GetOppositeBranchCondition(CCode);
7475       CC = DAG.getConstant(CCode, MVT::i8);
7476       Cond = Cond.getOperand(0).getOperand(1);
7477       addTest = false;
7478     }
7479   }
7480
7481   if (addTest) {
7482     // Look pass the truncate.
7483     if (Cond.getOpcode() == ISD::TRUNCATE)
7484       Cond = Cond.getOperand(0);
7485
7486     // We know the result of AND is compared against zero. Try to match
7487     // it to BT.
7488     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7489       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7490       if (NewSetCC.getNode()) {
7491         CC = NewSetCC.getOperand(0);
7492         Cond = NewSetCC.getOperand(1);
7493         addTest = false;
7494       }
7495     }
7496   }
7497
7498   if (addTest) {
7499     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7500     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7501   }
7502   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7503                      Chain, Dest, CC, Cond);
7504 }
7505
7506
7507 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7508 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7509 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7510 // that the guard pages used by the OS virtual memory manager are allocated in
7511 // correct sequence.
7512 SDValue
7513 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7514                                            SelectionDAG &DAG) const {
7515   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7516          "This should be used only on Windows targets");
7517   DebugLoc dl = Op.getDebugLoc();
7518
7519   // Get the inputs.
7520   SDValue Chain = Op.getOperand(0);
7521   SDValue Size  = Op.getOperand(1);
7522   // FIXME: Ensure alignment here
7523
7524   SDValue Flag;
7525
7526   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7527
7528   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7529   Flag = Chain.getValue(1);
7530
7531   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7532
7533   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7534   Flag = Chain.getValue(1);
7535
7536   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7537
7538   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7539   return DAG.getMergeValues(Ops1, 2, dl);
7540 }
7541
7542 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7543   MachineFunction &MF = DAG.getMachineFunction();
7544   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7545
7546   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7547   DebugLoc DL = Op.getDebugLoc();
7548
7549   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7550     // vastart just stores the address of the VarArgsFrameIndex slot into the
7551     // memory location argument.
7552     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7553                                    getPointerTy());
7554     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7555                         MachinePointerInfo(SV), false, false, 0);
7556   }
7557
7558   // __va_list_tag:
7559   //   gp_offset         (0 - 6 * 8)
7560   //   fp_offset         (48 - 48 + 8 * 16)
7561   //   overflow_arg_area (point to parameters coming in memory).
7562   //   reg_save_area
7563   SmallVector<SDValue, 8> MemOps;
7564   SDValue FIN = Op.getOperand(1);
7565   // Store gp_offset
7566   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7567                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7568                                                MVT::i32),
7569                                FIN, MachinePointerInfo(SV), false, false, 0);
7570   MemOps.push_back(Store);
7571
7572   // Store fp_offset
7573   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7574                     FIN, DAG.getIntPtrConstant(4));
7575   Store = DAG.getStore(Op.getOperand(0), DL,
7576                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7577                                        MVT::i32),
7578                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7579   MemOps.push_back(Store);
7580
7581   // Store ptr to overflow_arg_area
7582   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7583                     FIN, DAG.getIntPtrConstant(4));
7584   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7585                                     getPointerTy());
7586   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7587                        MachinePointerInfo(SV, 8),
7588                        false, false, 0);
7589   MemOps.push_back(Store);
7590
7591   // Store ptr to reg_save_area.
7592   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7593                     FIN, DAG.getIntPtrConstant(8));
7594   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7595                                     getPointerTy());
7596   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7597                        MachinePointerInfo(SV, 16), false, false, 0);
7598   MemOps.push_back(Store);
7599   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7600                      &MemOps[0], MemOps.size());
7601 }
7602
7603 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7604   assert(Subtarget->is64Bit() &&
7605          "LowerVAARG only handles 64-bit va_arg!");
7606   assert((Subtarget->isTargetLinux() ||
7607           Subtarget->isTargetDarwin()) &&
7608           "Unhandled target in LowerVAARG");
7609   assert(Op.getNode()->getNumOperands() == 4);
7610   SDValue Chain = Op.getOperand(0);
7611   SDValue SrcPtr = Op.getOperand(1);
7612   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7613   unsigned Align = Op.getConstantOperandVal(3);
7614   DebugLoc dl = Op.getDebugLoc();
7615
7616   EVT ArgVT = Op.getNode()->getValueType(0);
7617   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7618   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7619   uint8_t ArgMode;
7620
7621   // Decide which area this value should be read from.
7622   // TODO: Implement the AMD64 ABI in its entirety. This simple
7623   // selection mechanism works only for the basic types.
7624   if (ArgVT == MVT::f80) {
7625     llvm_unreachable("va_arg for f80 not yet implemented");
7626   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7627     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7628   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7629     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7630   } else {
7631     llvm_unreachable("Unhandled argument type in LowerVAARG");
7632   }
7633
7634   if (ArgMode == 2) {
7635     // Sanity Check: Make sure using fp_offset makes sense.
7636     assert(!UseSoftFloat &&
7637            !(DAG.getMachineFunction()
7638                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7639            Subtarget->hasXMM());
7640   }
7641
7642   // Insert VAARG_64 node into the DAG
7643   // VAARG_64 returns two values: Variable Argument Address, Chain
7644   SmallVector<SDValue, 11> InstOps;
7645   InstOps.push_back(Chain);
7646   InstOps.push_back(SrcPtr);
7647   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7648   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7649   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7650   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7651   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7652                                           VTs, &InstOps[0], InstOps.size(),
7653                                           MVT::i64,
7654                                           MachinePointerInfo(SV),
7655                                           /*Align=*/0,
7656                                           /*Volatile=*/false,
7657                                           /*ReadMem=*/true,
7658                                           /*WriteMem=*/true);
7659   Chain = VAARG.getValue(1);
7660
7661   // Load the next argument and return it
7662   return DAG.getLoad(ArgVT, dl,
7663                      Chain,
7664                      VAARG,
7665                      MachinePointerInfo(),
7666                      false, false, 0);
7667 }
7668
7669 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7670   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7671   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7672   SDValue Chain = Op.getOperand(0);
7673   SDValue DstPtr = Op.getOperand(1);
7674   SDValue SrcPtr = Op.getOperand(2);
7675   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7676   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7677   DebugLoc DL = Op.getDebugLoc();
7678
7679   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7680                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7681                        false,
7682                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7683 }
7684
7685 SDValue
7686 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7687   DebugLoc dl = Op.getDebugLoc();
7688   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7689   switch (IntNo) {
7690   default: return SDValue();    // Don't custom lower most intrinsics.
7691   // Comparison intrinsics.
7692   case Intrinsic::x86_sse_comieq_ss:
7693   case Intrinsic::x86_sse_comilt_ss:
7694   case Intrinsic::x86_sse_comile_ss:
7695   case Intrinsic::x86_sse_comigt_ss:
7696   case Intrinsic::x86_sse_comige_ss:
7697   case Intrinsic::x86_sse_comineq_ss:
7698   case Intrinsic::x86_sse_ucomieq_ss:
7699   case Intrinsic::x86_sse_ucomilt_ss:
7700   case Intrinsic::x86_sse_ucomile_ss:
7701   case Intrinsic::x86_sse_ucomigt_ss:
7702   case Intrinsic::x86_sse_ucomige_ss:
7703   case Intrinsic::x86_sse_ucomineq_ss:
7704   case Intrinsic::x86_sse2_comieq_sd:
7705   case Intrinsic::x86_sse2_comilt_sd:
7706   case Intrinsic::x86_sse2_comile_sd:
7707   case Intrinsic::x86_sse2_comigt_sd:
7708   case Intrinsic::x86_sse2_comige_sd:
7709   case Intrinsic::x86_sse2_comineq_sd:
7710   case Intrinsic::x86_sse2_ucomieq_sd:
7711   case Intrinsic::x86_sse2_ucomilt_sd:
7712   case Intrinsic::x86_sse2_ucomile_sd:
7713   case Intrinsic::x86_sse2_ucomigt_sd:
7714   case Intrinsic::x86_sse2_ucomige_sd:
7715   case Intrinsic::x86_sse2_ucomineq_sd: {
7716     unsigned Opc = 0;
7717     ISD::CondCode CC = ISD::SETCC_INVALID;
7718     switch (IntNo) {
7719     default: break;
7720     case Intrinsic::x86_sse_comieq_ss:
7721     case Intrinsic::x86_sse2_comieq_sd:
7722       Opc = X86ISD::COMI;
7723       CC = ISD::SETEQ;
7724       break;
7725     case Intrinsic::x86_sse_comilt_ss:
7726     case Intrinsic::x86_sse2_comilt_sd:
7727       Opc = X86ISD::COMI;
7728       CC = ISD::SETLT;
7729       break;
7730     case Intrinsic::x86_sse_comile_ss:
7731     case Intrinsic::x86_sse2_comile_sd:
7732       Opc = X86ISD::COMI;
7733       CC = ISD::SETLE;
7734       break;
7735     case Intrinsic::x86_sse_comigt_ss:
7736     case Intrinsic::x86_sse2_comigt_sd:
7737       Opc = X86ISD::COMI;
7738       CC = ISD::SETGT;
7739       break;
7740     case Intrinsic::x86_sse_comige_ss:
7741     case Intrinsic::x86_sse2_comige_sd:
7742       Opc = X86ISD::COMI;
7743       CC = ISD::SETGE;
7744       break;
7745     case Intrinsic::x86_sse_comineq_ss:
7746     case Intrinsic::x86_sse2_comineq_sd:
7747       Opc = X86ISD::COMI;
7748       CC = ISD::SETNE;
7749       break;
7750     case Intrinsic::x86_sse_ucomieq_ss:
7751     case Intrinsic::x86_sse2_ucomieq_sd:
7752       Opc = X86ISD::UCOMI;
7753       CC = ISD::SETEQ;
7754       break;
7755     case Intrinsic::x86_sse_ucomilt_ss:
7756     case Intrinsic::x86_sse2_ucomilt_sd:
7757       Opc = X86ISD::UCOMI;
7758       CC = ISD::SETLT;
7759       break;
7760     case Intrinsic::x86_sse_ucomile_ss:
7761     case Intrinsic::x86_sse2_ucomile_sd:
7762       Opc = X86ISD::UCOMI;
7763       CC = ISD::SETLE;
7764       break;
7765     case Intrinsic::x86_sse_ucomigt_ss:
7766     case Intrinsic::x86_sse2_ucomigt_sd:
7767       Opc = X86ISD::UCOMI;
7768       CC = ISD::SETGT;
7769       break;
7770     case Intrinsic::x86_sse_ucomige_ss:
7771     case Intrinsic::x86_sse2_ucomige_sd:
7772       Opc = X86ISD::UCOMI;
7773       CC = ISD::SETGE;
7774       break;
7775     case Intrinsic::x86_sse_ucomineq_ss:
7776     case Intrinsic::x86_sse2_ucomineq_sd:
7777       Opc = X86ISD::UCOMI;
7778       CC = ISD::SETNE;
7779       break;
7780     }
7781
7782     SDValue LHS = Op.getOperand(1);
7783     SDValue RHS = Op.getOperand(2);
7784     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7785     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7786     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7787     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7788                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7789     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7790   }
7791   // ptest and testp intrinsics. The intrinsic these come from are designed to
7792   // return an integer value, not just an instruction so lower it to the ptest
7793   // or testp pattern and a setcc for the result.
7794   case Intrinsic::x86_sse41_ptestz:
7795   case Intrinsic::x86_sse41_ptestc:
7796   case Intrinsic::x86_sse41_ptestnzc:
7797   case Intrinsic::x86_avx_ptestz_256:
7798   case Intrinsic::x86_avx_ptestc_256:
7799   case Intrinsic::x86_avx_ptestnzc_256:
7800   case Intrinsic::x86_avx_vtestz_ps:
7801   case Intrinsic::x86_avx_vtestc_ps:
7802   case Intrinsic::x86_avx_vtestnzc_ps:
7803   case Intrinsic::x86_avx_vtestz_pd:
7804   case Intrinsic::x86_avx_vtestc_pd:
7805   case Intrinsic::x86_avx_vtestnzc_pd:
7806   case Intrinsic::x86_avx_vtestz_ps_256:
7807   case Intrinsic::x86_avx_vtestc_ps_256:
7808   case Intrinsic::x86_avx_vtestnzc_ps_256:
7809   case Intrinsic::x86_avx_vtestz_pd_256:
7810   case Intrinsic::x86_avx_vtestc_pd_256:
7811   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7812     bool IsTestPacked = false;
7813     unsigned X86CC = 0;
7814     switch (IntNo) {
7815     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7816     case Intrinsic::x86_avx_vtestz_ps:
7817     case Intrinsic::x86_avx_vtestz_pd:
7818     case Intrinsic::x86_avx_vtestz_ps_256:
7819     case Intrinsic::x86_avx_vtestz_pd_256:
7820       IsTestPacked = true; // Fallthrough
7821     case Intrinsic::x86_sse41_ptestz:
7822     case Intrinsic::x86_avx_ptestz_256:
7823       // ZF = 1
7824       X86CC = X86::COND_E;
7825       break;
7826     case Intrinsic::x86_avx_vtestc_ps:
7827     case Intrinsic::x86_avx_vtestc_pd:
7828     case Intrinsic::x86_avx_vtestc_ps_256:
7829     case Intrinsic::x86_avx_vtestc_pd_256:
7830       IsTestPacked = true; // Fallthrough
7831     case Intrinsic::x86_sse41_ptestc:
7832     case Intrinsic::x86_avx_ptestc_256:
7833       // CF = 1
7834       X86CC = X86::COND_B;
7835       break;
7836     case Intrinsic::x86_avx_vtestnzc_ps:
7837     case Intrinsic::x86_avx_vtestnzc_pd:
7838     case Intrinsic::x86_avx_vtestnzc_ps_256:
7839     case Intrinsic::x86_avx_vtestnzc_pd_256:
7840       IsTestPacked = true; // Fallthrough
7841     case Intrinsic::x86_sse41_ptestnzc:
7842     case Intrinsic::x86_avx_ptestnzc_256:
7843       // ZF and CF = 0
7844       X86CC = X86::COND_A;
7845       break;
7846     }
7847
7848     SDValue LHS = Op.getOperand(1);
7849     SDValue RHS = Op.getOperand(2);
7850     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7851     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7852     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7853     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7854     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7855   }
7856
7857   // Fix vector shift instructions where the last operand is a non-immediate
7858   // i32 value.
7859   case Intrinsic::x86_sse2_pslli_w:
7860   case Intrinsic::x86_sse2_pslli_d:
7861   case Intrinsic::x86_sse2_pslli_q:
7862   case Intrinsic::x86_sse2_psrli_w:
7863   case Intrinsic::x86_sse2_psrli_d:
7864   case Intrinsic::x86_sse2_psrli_q:
7865   case Intrinsic::x86_sse2_psrai_w:
7866   case Intrinsic::x86_sse2_psrai_d:
7867   case Intrinsic::x86_mmx_pslli_w:
7868   case Intrinsic::x86_mmx_pslli_d:
7869   case Intrinsic::x86_mmx_pslli_q:
7870   case Intrinsic::x86_mmx_psrli_w:
7871   case Intrinsic::x86_mmx_psrli_d:
7872   case Intrinsic::x86_mmx_psrli_q:
7873   case Intrinsic::x86_mmx_psrai_w:
7874   case Intrinsic::x86_mmx_psrai_d: {
7875     SDValue ShAmt = Op.getOperand(2);
7876     if (isa<ConstantSDNode>(ShAmt))
7877       return SDValue();
7878
7879     unsigned NewIntNo = 0;
7880     EVT ShAmtVT = MVT::v4i32;
7881     switch (IntNo) {
7882     case Intrinsic::x86_sse2_pslli_w:
7883       NewIntNo = Intrinsic::x86_sse2_psll_w;
7884       break;
7885     case Intrinsic::x86_sse2_pslli_d:
7886       NewIntNo = Intrinsic::x86_sse2_psll_d;
7887       break;
7888     case Intrinsic::x86_sse2_pslli_q:
7889       NewIntNo = Intrinsic::x86_sse2_psll_q;
7890       break;
7891     case Intrinsic::x86_sse2_psrli_w:
7892       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7893       break;
7894     case Intrinsic::x86_sse2_psrli_d:
7895       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7896       break;
7897     case Intrinsic::x86_sse2_psrli_q:
7898       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7899       break;
7900     case Intrinsic::x86_sse2_psrai_w:
7901       NewIntNo = Intrinsic::x86_sse2_psra_w;
7902       break;
7903     case Intrinsic::x86_sse2_psrai_d:
7904       NewIntNo = Intrinsic::x86_sse2_psra_d;
7905       break;
7906     default: {
7907       ShAmtVT = MVT::v2i32;
7908       switch (IntNo) {
7909       case Intrinsic::x86_mmx_pslli_w:
7910         NewIntNo = Intrinsic::x86_mmx_psll_w;
7911         break;
7912       case Intrinsic::x86_mmx_pslli_d:
7913         NewIntNo = Intrinsic::x86_mmx_psll_d;
7914         break;
7915       case Intrinsic::x86_mmx_pslli_q:
7916         NewIntNo = Intrinsic::x86_mmx_psll_q;
7917         break;
7918       case Intrinsic::x86_mmx_psrli_w:
7919         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7920         break;
7921       case Intrinsic::x86_mmx_psrli_d:
7922         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7923         break;
7924       case Intrinsic::x86_mmx_psrli_q:
7925         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7926         break;
7927       case Intrinsic::x86_mmx_psrai_w:
7928         NewIntNo = Intrinsic::x86_mmx_psra_w;
7929         break;
7930       case Intrinsic::x86_mmx_psrai_d:
7931         NewIntNo = Intrinsic::x86_mmx_psra_d;
7932         break;
7933       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7934       }
7935       break;
7936     }
7937     }
7938
7939     // The vector shift intrinsics with scalars uses 32b shift amounts but
7940     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7941     // to be zero.
7942     SDValue ShOps[4];
7943     ShOps[0] = ShAmt;
7944     ShOps[1] = DAG.getConstant(0, MVT::i32);
7945     if (ShAmtVT == MVT::v4i32) {
7946       ShOps[2] = DAG.getUNDEF(MVT::i32);
7947       ShOps[3] = DAG.getUNDEF(MVT::i32);
7948       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7949     } else {
7950       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7951 // FIXME this must be lowered to get rid of the invalid type.
7952     }
7953
7954     EVT VT = Op.getValueType();
7955     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7956     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7957                        DAG.getConstant(NewIntNo, MVT::i32),
7958                        Op.getOperand(1), ShAmt);
7959   }
7960   }
7961 }
7962
7963 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7964                                            SelectionDAG &DAG) const {
7965   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7966   MFI->setReturnAddressIsTaken(true);
7967
7968   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7969   DebugLoc dl = Op.getDebugLoc();
7970
7971   if (Depth > 0) {
7972     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7973     SDValue Offset =
7974       DAG.getConstant(TD->getPointerSize(),
7975                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7976     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7977                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7978                                    FrameAddr, Offset),
7979                        MachinePointerInfo(), false, false, 0);
7980   }
7981
7982   // Just load the return address.
7983   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7984   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7985                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7986 }
7987
7988 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7989   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7990   MFI->setFrameAddressIsTaken(true);
7991
7992   EVT VT = Op.getValueType();
7993   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7994   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7995   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7996   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7997   while (Depth--)
7998     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7999                             MachinePointerInfo(),
8000                             false, false, 0);
8001   return FrameAddr;
8002 }
8003
8004 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8005                                                      SelectionDAG &DAG) const {
8006   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8007 }
8008
8009 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8010   MachineFunction &MF = DAG.getMachineFunction();
8011   SDValue Chain     = Op.getOperand(0);
8012   SDValue Offset    = Op.getOperand(1);
8013   SDValue Handler   = Op.getOperand(2);
8014   DebugLoc dl       = Op.getDebugLoc();
8015
8016   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8017                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8018                                      getPointerTy());
8019   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8020
8021   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8022                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8023   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8024   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8025                        false, false, 0);
8026   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8027   MF.getRegInfo().addLiveOut(StoreAddrReg);
8028
8029   return DAG.getNode(X86ISD::EH_RETURN, dl,
8030                      MVT::Other,
8031                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8032 }
8033
8034 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8035                                              SelectionDAG &DAG) const {
8036   SDValue Root = Op.getOperand(0);
8037   SDValue Trmp = Op.getOperand(1); // trampoline
8038   SDValue FPtr = Op.getOperand(2); // nested function
8039   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8040   DebugLoc dl  = Op.getDebugLoc();
8041
8042   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8043
8044   if (Subtarget->is64Bit()) {
8045     SDValue OutChains[6];
8046
8047     // Large code-model.
8048     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8049     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8050
8051     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8052     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8053
8054     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8055
8056     // Load the pointer to the nested function into R11.
8057     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8058     SDValue Addr = Trmp;
8059     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8060                                 Addr, MachinePointerInfo(TrmpAddr),
8061                                 false, false, 0);
8062
8063     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8064                        DAG.getConstant(2, MVT::i64));
8065     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8066                                 MachinePointerInfo(TrmpAddr, 2),
8067                                 false, false, 2);
8068
8069     // Load the 'nest' parameter value into R10.
8070     // R10 is specified in X86CallingConv.td
8071     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8072     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8073                        DAG.getConstant(10, MVT::i64));
8074     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8075                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8076                                 false, false, 0);
8077
8078     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8079                        DAG.getConstant(12, MVT::i64));
8080     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8081                                 MachinePointerInfo(TrmpAddr, 12),
8082                                 false, false, 2);
8083
8084     // Jump to the nested function.
8085     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8086     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8087                        DAG.getConstant(20, MVT::i64));
8088     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8089                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8090                                 false, false, 0);
8091
8092     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8093     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8094                        DAG.getConstant(22, MVT::i64));
8095     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8096                                 MachinePointerInfo(TrmpAddr, 22),
8097                                 false, false, 0);
8098
8099     SDValue Ops[] =
8100       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8101     return DAG.getMergeValues(Ops, 2, dl);
8102   } else {
8103     const Function *Func =
8104       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8105     CallingConv::ID CC = Func->getCallingConv();
8106     unsigned NestReg;
8107
8108     switch (CC) {
8109     default:
8110       llvm_unreachable("Unsupported calling convention");
8111     case CallingConv::C:
8112     case CallingConv::X86_StdCall: {
8113       // Pass 'nest' parameter in ECX.
8114       // Must be kept in sync with X86CallingConv.td
8115       NestReg = X86::ECX;
8116
8117       // Check that ECX wasn't needed by an 'inreg' parameter.
8118       const FunctionType *FTy = Func->getFunctionType();
8119       const AttrListPtr &Attrs = Func->getAttributes();
8120
8121       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8122         unsigned InRegCount = 0;
8123         unsigned Idx = 1;
8124
8125         for (FunctionType::param_iterator I = FTy->param_begin(),
8126              E = FTy->param_end(); I != E; ++I, ++Idx)
8127           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8128             // FIXME: should only count parameters that are lowered to integers.
8129             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8130
8131         if (InRegCount > 2) {
8132           report_fatal_error("Nest register in use - reduce number of inreg"
8133                              " parameters!");
8134         }
8135       }
8136       break;
8137     }
8138     case CallingConv::X86_FastCall:
8139     case CallingConv::X86_ThisCall:
8140     case CallingConv::Fast:
8141       // Pass 'nest' parameter in EAX.
8142       // Must be kept in sync with X86CallingConv.td
8143       NestReg = X86::EAX;
8144       break;
8145     }
8146
8147     SDValue OutChains[4];
8148     SDValue Addr, Disp;
8149
8150     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8151                        DAG.getConstant(10, MVT::i32));
8152     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8153
8154     // This is storing the opcode for MOV32ri.
8155     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8156     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8157     OutChains[0] = DAG.getStore(Root, dl,
8158                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8159                                 Trmp, MachinePointerInfo(TrmpAddr),
8160                                 false, false, 0);
8161
8162     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8163                        DAG.getConstant(1, MVT::i32));
8164     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8165                                 MachinePointerInfo(TrmpAddr, 1),
8166                                 false, false, 1);
8167
8168     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8169     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8170                        DAG.getConstant(5, MVT::i32));
8171     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8172                                 MachinePointerInfo(TrmpAddr, 5),
8173                                 false, false, 1);
8174
8175     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8176                        DAG.getConstant(6, MVT::i32));
8177     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8178                                 MachinePointerInfo(TrmpAddr, 6),
8179                                 false, false, 1);
8180
8181     SDValue Ops[] =
8182       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8183     return DAG.getMergeValues(Ops, 2, dl);
8184   }
8185 }
8186
8187 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8188                                             SelectionDAG &DAG) const {
8189   /*
8190    The rounding mode is in bits 11:10 of FPSR, and has the following
8191    settings:
8192      00 Round to nearest
8193      01 Round to -inf
8194      10 Round to +inf
8195      11 Round to 0
8196
8197   FLT_ROUNDS, on the other hand, expects the following:
8198     -1 Undefined
8199      0 Round to 0
8200      1 Round to nearest
8201      2 Round to +inf
8202      3 Round to -inf
8203
8204   To perform the conversion, we do:
8205     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8206   */
8207
8208   MachineFunction &MF = DAG.getMachineFunction();
8209   const TargetMachine &TM = MF.getTarget();
8210   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8211   unsigned StackAlignment = TFI.getStackAlignment();
8212   EVT VT = Op.getValueType();
8213   DebugLoc DL = Op.getDebugLoc();
8214
8215   // Save FP Control Word to stack slot
8216   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8217   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8218
8219
8220   MachineMemOperand *MMO =
8221    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8222                            MachineMemOperand::MOStore, 2, 2);
8223
8224   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8225   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8226                                           DAG.getVTList(MVT::Other),
8227                                           Ops, 2, MVT::i16, MMO);
8228
8229   // Load FP Control Word from stack slot
8230   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8231                             MachinePointerInfo(), false, false, 0);
8232
8233   // Transform as necessary
8234   SDValue CWD1 =
8235     DAG.getNode(ISD::SRL, DL, MVT::i16,
8236                 DAG.getNode(ISD::AND, DL, MVT::i16,
8237                             CWD, DAG.getConstant(0x800, MVT::i16)),
8238                 DAG.getConstant(11, MVT::i8));
8239   SDValue CWD2 =
8240     DAG.getNode(ISD::SRL, DL, MVT::i16,
8241                 DAG.getNode(ISD::AND, DL, MVT::i16,
8242                             CWD, DAG.getConstant(0x400, MVT::i16)),
8243                 DAG.getConstant(9, MVT::i8));
8244
8245   SDValue RetVal =
8246     DAG.getNode(ISD::AND, DL, MVT::i16,
8247                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8248                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8249                             DAG.getConstant(1, MVT::i16)),
8250                 DAG.getConstant(3, MVT::i16));
8251
8252
8253   return DAG.getNode((VT.getSizeInBits() < 16 ?
8254                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8255 }
8256
8257 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8258   EVT VT = Op.getValueType();
8259   EVT OpVT = VT;
8260   unsigned NumBits = VT.getSizeInBits();
8261   DebugLoc dl = Op.getDebugLoc();
8262
8263   Op = Op.getOperand(0);
8264   if (VT == MVT::i8) {
8265     // Zero extend to i32 since there is not an i8 bsr.
8266     OpVT = MVT::i32;
8267     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8268   }
8269
8270   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8271   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8272   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8273
8274   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8275   SDValue Ops[] = {
8276     Op,
8277     DAG.getConstant(NumBits+NumBits-1, OpVT),
8278     DAG.getConstant(X86::COND_E, MVT::i8),
8279     Op.getValue(1)
8280   };
8281   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8282
8283   // Finally xor with NumBits-1.
8284   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8285
8286   if (VT == MVT::i8)
8287     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8288   return Op;
8289 }
8290
8291 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8292   EVT VT = Op.getValueType();
8293   EVT OpVT = VT;
8294   unsigned NumBits = VT.getSizeInBits();
8295   DebugLoc dl = Op.getDebugLoc();
8296
8297   Op = Op.getOperand(0);
8298   if (VT == MVT::i8) {
8299     OpVT = MVT::i32;
8300     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8301   }
8302
8303   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8304   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8305   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8306
8307   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8308   SDValue Ops[] = {
8309     Op,
8310     DAG.getConstant(NumBits, OpVT),
8311     DAG.getConstant(X86::COND_E, MVT::i8),
8312     Op.getValue(1)
8313   };
8314   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8315
8316   if (VT == MVT::i8)
8317     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8318   return Op;
8319 }
8320
8321 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8322   EVT VT = Op.getValueType();
8323   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8324   DebugLoc dl = Op.getDebugLoc();
8325
8326   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8327   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8328   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8329   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8330   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8331   //
8332   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8333   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8334   //  return AloBlo + AloBhi + AhiBlo;
8335
8336   SDValue A = Op.getOperand(0);
8337   SDValue B = Op.getOperand(1);
8338
8339   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8340                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8341                        A, DAG.getConstant(32, MVT::i32));
8342   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8343                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8344                        B, DAG.getConstant(32, MVT::i32));
8345   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8346                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8347                        A, B);
8348   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8349                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8350                        A, Bhi);
8351   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8352                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8353                        Ahi, B);
8354   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8355                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8356                        AloBhi, DAG.getConstant(32, MVT::i32));
8357   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8358                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8359                        AhiBlo, DAG.getConstant(32, MVT::i32));
8360   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8361   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8362   return Res;
8363 }
8364
8365 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8366   EVT VT = Op.getValueType();
8367   DebugLoc dl = Op.getDebugLoc();
8368   SDValue R = Op.getOperand(0);
8369
8370   LLVMContext *Context = DAG.getContext();
8371
8372   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8373
8374   if (VT == MVT::v4i32) {
8375     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8376                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8377                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8378
8379     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8380
8381     std::vector<Constant*> CV(4, CI);
8382     Constant *C = ConstantVector::get(CV);
8383     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8384     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8385                                  MachinePointerInfo::getConstantPool(),
8386                                  false, false, 16);
8387
8388     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8389     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8390     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8391     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8392   }
8393   if (VT == MVT::v16i8) {
8394     // a = a << 5;
8395     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8396                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8397                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8398
8399     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8400     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8401
8402     std::vector<Constant*> CVM1(16, CM1);
8403     std::vector<Constant*> CVM2(16, CM2);
8404     Constant *C = ConstantVector::get(CVM1);
8405     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8406     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8407                             MachinePointerInfo::getConstantPool(),
8408                             false, false, 16);
8409
8410     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8411     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8412     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8413                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8414                     DAG.getConstant(4, MVT::i32));
8415     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8416                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8417                     R, M, Op);
8418     // a += a
8419     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8420
8421     C = ConstantVector::get(CVM2);
8422     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8423     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8424                     MachinePointerInfo::getConstantPool(),
8425                     false, false, 16);
8426
8427     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8428     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8429     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8430                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8431                     DAG.getConstant(2, MVT::i32));
8432     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8433                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8434                     R, M, Op);
8435     // a += a
8436     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8437
8438     // return pblendv(r, r+r, a);
8439     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8440                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8441                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8442     return R;
8443   }
8444   return SDValue();
8445 }
8446
8447 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8448   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8449   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8450   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8451   // has only one use.
8452   SDNode *N = Op.getNode();
8453   SDValue LHS = N->getOperand(0);
8454   SDValue RHS = N->getOperand(1);
8455   unsigned BaseOp = 0;
8456   unsigned Cond = 0;
8457   DebugLoc DL = Op.getDebugLoc();
8458   switch (Op.getOpcode()) {
8459   default: llvm_unreachable("Unknown ovf instruction!");
8460   case ISD::SADDO:
8461     // A subtract of one will be selected as a INC. Note that INC doesn't
8462     // set CF, so we can't do this for UADDO.
8463     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8464       if (C->getAPIntValue() == 1) {
8465         BaseOp = X86ISD::INC;
8466         Cond = X86::COND_O;
8467         break;
8468       }
8469     BaseOp = X86ISD::ADD;
8470     Cond = X86::COND_O;
8471     break;
8472   case ISD::UADDO:
8473     BaseOp = X86ISD::ADD;
8474     Cond = X86::COND_B;
8475     break;
8476   case ISD::SSUBO:
8477     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8478     // set CF, so we can't do this for USUBO.
8479     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8480       if (C->getAPIntValue() == 1) {
8481         BaseOp = X86ISD::DEC;
8482         Cond = X86::COND_O;
8483         break;
8484       }
8485     BaseOp = X86ISD::SUB;
8486     Cond = X86::COND_O;
8487     break;
8488   case ISD::USUBO:
8489     BaseOp = X86ISD::SUB;
8490     Cond = X86::COND_B;
8491     break;
8492   case ISD::SMULO:
8493     BaseOp = X86ISD::SMUL;
8494     Cond = X86::COND_O;
8495     break;
8496   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8497     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8498                                  MVT::i32);
8499     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8500     
8501     SDValue SetCC =
8502       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8503                   DAG.getConstant(X86::COND_O, MVT::i32),
8504                   SDValue(Sum.getNode(), 2));
8505     
8506     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8507     return Sum;
8508   }
8509   }
8510
8511   // Also sets EFLAGS.
8512   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8513   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8514
8515   SDValue SetCC =
8516     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8517                 DAG.getConstant(Cond, MVT::i32),
8518                 SDValue(Sum.getNode(), 1));
8519
8520   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8521   return Sum;
8522 }
8523
8524 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8525   DebugLoc dl = Op.getDebugLoc();
8526
8527   if (!Subtarget->hasSSE2()) {
8528     SDValue Chain = Op.getOperand(0);
8529     SDValue Zero = DAG.getConstant(0,
8530                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8531     SDValue Ops[] = {
8532       DAG.getRegister(X86::ESP, MVT::i32), // Base
8533       DAG.getTargetConstant(1, MVT::i8),   // Scale
8534       DAG.getRegister(0, MVT::i32),        // Index
8535       DAG.getTargetConstant(0, MVT::i32),  // Disp
8536       DAG.getRegister(0, MVT::i32),        // Segment.
8537       Zero,
8538       Chain
8539     };
8540     SDNode *Res =
8541       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8542                           array_lengthof(Ops));
8543     return SDValue(Res, 0);
8544   }
8545
8546   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8547   if (!isDev)
8548     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8549
8550   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8551   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8552   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8553   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8554
8555   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8556   if (!Op1 && !Op2 && !Op3 && Op4)
8557     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8558
8559   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8560   if (Op1 && !Op2 && !Op3 && !Op4)
8561     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8562
8563   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8564   //           (MFENCE)>;
8565   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8566 }
8567
8568 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8569   EVT T = Op.getValueType();
8570   DebugLoc DL = Op.getDebugLoc();
8571   unsigned Reg = 0;
8572   unsigned size = 0;
8573   switch(T.getSimpleVT().SimpleTy) {
8574   default:
8575     assert(false && "Invalid value type!");
8576   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8577   case MVT::i16: Reg = X86::AX;  size = 2; break;
8578   case MVT::i32: Reg = X86::EAX; size = 4; break;
8579   case MVT::i64:
8580     assert(Subtarget->is64Bit() && "Node not type legal!");
8581     Reg = X86::RAX; size = 8;
8582     break;
8583   }
8584   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8585                                     Op.getOperand(2), SDValue());
8586   SDValue Ops[] = { cpIn.getValue(0),
8587                     Op.getOperand(1),
8588                     Op.getOperand(3),
8589                     DAG.getTargetConstant(size, MVT::i8),
8590                     cpIn.getValue(1) };
8591   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8592   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8593   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8594                                            Ops, 5, T, MMO);
8595   SDValue cpOut =
8596     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8597   return cpOut;
8598 }
8599
8600 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8601                                                  SelectionDAG &DAG) const {
8602   assert(Subtarget->is64Bit() && "Result not type legalized?");
8603   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8604   SDValue TheChain = Op.getOperand(0);
8605   DebugLoc dl = Op.getDebugLoc();
8606   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8607   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8608   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8609                                    rax.getValue(2));
8610   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8611                             DAG.getConstant(32, MVT::i8));
8612   SDValue Ops[] = {
8613     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8614     rdx.getValue(1)
8615   };
8616   return DAG.getMergeValues(Ops, 2, dl);
8617 }
8618
8619 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8620                                             SelectionDAG &DAG) const {
8621   EVT SrcVT = Op.getOperand(0).getValueType();
8622   EVT DstVT = Op.getValueType();
8623   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8624           Subtarget->hasMMX() && !DisableMMX) &&
8625          "Unexpected custom BITCAST");
8626   assert((DstVT == MVT::i64 ||
8627           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8628          "Unexpected custom BITCAST");
8629   // i64 <=> MMX conversions are Legal.
8630   if (SrcVT==MVT::i64 && DstVT.isVector())
8631     return Op;
8632   if (DstVT==MVT::i64 && SrcVT.isVector())
8633     return Op;
8634   // MMX <=> MMX conversions are Legal.
8635   if (SrcVT.isVector() && DstVT.isVector())
8636     return Op;
8637   // All other conversions need to be expanded.
8638   return SDValue();
8639 }
8640 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8641   SDNode *Node = Op.getNode();
8642   DebugLoc dl = Node->getDebugLoc();
8643   EVT T = Node->getValueType(0);
8644   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8645                               DAG.getConstant(0, T), Node->getOperand(2));
8646   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8647                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8648                        Node->getOperand(0),
8649                        Node->getOperand(1), negOp,
8650                        cast<AtomicSDNode>(Node)->getSrcValue(),
8651                        cast<AtomicSDNode>(Node)->getAlignment());
8652 }
8653
8654 /// LowerOperation - Provide custom lowering hooks for some operations.
8655 ///
8656 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8657   switch (Op.getOpcode()) {
8658   default: llvm_unreachable("Should not custom lower this!");
8659   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8660   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8661   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8662   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8663   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8664   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8665   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8666   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8667   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8668   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8669   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8670   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8671   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8672   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8673   case ISD::SHL_PARTS:
8674   case ISD::SRA_PARTS:
8675   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8676   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8677   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8678   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8679   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8680   case ISD::FABS:               return LowerFABS(Op, DAG);
8681   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8682   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8683   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8684   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8685   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8686   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8687   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8688   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8689   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8690   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8691   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8692   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8693   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8694   case ISD::FRAME_TO_ARGS_OFFSET:
8695                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8696   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8697   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8698   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8699   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8700   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8701   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8702   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8703   case ISD::SHL:                return LowerSHL(Op, DAG);
8704   case ISD::SADDO:
8705   case ISD::UADDO:
8706   case ISD::SSUBO:
8707   case ISD::USUBO:
8708   case ISD::SMULO:
8709   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8710   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8711   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8712   }
8713 }
8714
8715 void X86TargetLowering::
8716 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8717                         SelectionDAG &DAG, unsigned NewOp) const {
8718   EVT T = Node->getValueType(0);
8719   DebugLoc dl = Node->getDebugLoc();
8720   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8721
8722   SDValue Chain = Node->getOperand(0);
8723   SDValue In1 = Node->getOperand(1);
8724   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8725                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8726   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8727                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8728   SDValue Ops[] = { Chain, In1, In2L, In2H };
8729   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8730   SDValue Result =
8731     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8732                             cast<MemSDNode>(Node)->getMemOperand());
8733   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8734   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8735   Results.push_back(Result.getValue(2));
8736 }
8737
8738 /// ReplaceNodeResults - Replace a node with an illegal result type
8739 /// with a new node built out of custom code.
8740 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8741                                            SmallVectorImpl<SDValue>&Results,
8742                                            SelectionDAG &DAG) const {
8743   DebugLoc dl = N->getDebugLoc();
8744   switch (N->getOpcode()) {
8745   default:
8746     assert(false && "Do not know how to custom type legalize this operation!");
8747     return;
8748   case ISD::FP_TO_SINT: {
8749     std::pair<SDValue,SDValue> Vals =
8750         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8751     SDValue FIST = Vals.first, StackSlot = Vals.second;
8752     if (FIST.getNode() != 0) {
8753       EVT VT = N->getValueType(0);
8754       // Return a load from the stack slot.
8755       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8756                                     MachinePointerInfo(), false, false, 0));
8757     }
8758     return;
8759   }
8760   case ISD::READCYCLECOUNTER: {
8761     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8762     SDValue TheChain = N->getOperand(0);
8763     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8764     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8765                                      rd.getValue(1));
8766     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8767                                      eax.getValue(2));
8768     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8769     SDValue Ops[] = { eax, edx };
8770     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8771     Results.push_back(edx.getValue(1));
8772     return;
8773   }
8774   case ISD::ATOMIC_CMP_SWAP: {
8775     EVT T = N->getValueType(0);
8776     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8777     SDValue cpInL, cpInH;
8778     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8779                         DAG.getConstant(0, MVT::i32));
8780     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8781                         DAG.getConstant(1, MVT::i32));
8782     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8783     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8784                              cpInL.getValue(1));
8785     SDValue swapInL, swapInH;
8786     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8787                           DAG.getConstant(0, MVT::i32));
8788     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8789                           DAG.getConstant(1, MVT::i32));
8790     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8791                                cpInH.getValue(1));
8792     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8793                                swapInL.getValue(1));
8794     SDValue Ops[] = { swapInH.getValue(0),
8795                       N->getOperand(1),
8796                       swapInH.getValue(1) };
8797     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8798     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8799     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8800                                              Ops, 3, T, MMO);
8801     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8802                                         MVT::i32, Result.getValue(1));
8803     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8804                                         MVT::i32, cpOutL.getValue(2));
8805     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8806     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8807     Results.push_back(cpOutH.getValue(1));
8808     return;
8809   }
8810   case ISD::ATOMIC_LOAD_ADD:
8811     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8812     return;
8813   case ISD::ATOMIC_LOAD_AND:
8814     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8815     return;
8816   case ISD::ATOMIC_LOAD_NAND:
8817     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8818     return;
8819   case ISD::ATOMIC_LOAD_OR:
8820     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8821     return;
8822   case ISD::ATOMIC_LOAD_SUB:
8823     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8824     return;
8825   case ISD::ATOMIC_LOAD_XOR:
8826     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8827     return;
8828   case ISD::ATOMIC_SWAP:
8829     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8830     return;
8831   }
8832 }
8833
8834 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8835   switch (Opcode) {
8836   default: return NULL;
8837   case X86ISD::BSF:                return "X86ISD::BSF";
8838   case X86ISD::BSR:                return "X86ISD::BSR";
8839   case X86ISD::SHLD:               return "X86ISD::SHLD";
8840   case X86ISD::SHRD:               return "X86ISD::SHRD";
8841   case X86ISD::FAND:               return "X86ISD::FAND";
8842   case X86ISD::FOR:                return "X86ISD::FOR";
8843   case X86ISD::FXOR:               return "X86ISD::FXOR";
8844   case X86ISD::FSRL:               return "X86ISD::FSRL";
8845   case X86ISD::FILD:               return "X86ISD::FILD";
8846   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8847   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8848   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8849   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8850   case X86ISD::FLD:                return "X86ISD::FLD";
8851   case X86ISD::FST:                return "X86ISD::FST";
8852   case X86ISD::CALL:               return "X86ISD::CALL";
8853   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8854   case X86ISD::BT:                 return "X86ISD::BT";
8855   case X86ISD::CMP:                return "X86ISD::CMP";
8856   case X86ISD::COMI:               return "X86ISD::COMI";
8857   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8858   case X86ISD::SETCC:              return "X86ISD::SETCC";
8859   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8860   case X86ISD::CMOV:               return "X86ISD::CMOV";
8861   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8862   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8863   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8864   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8865   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8866   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8867   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8868   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8869   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8870   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8871   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8872   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8873   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8874   case X86ISD::PANDN:              return "X86ISD::PANDN";
8875   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
8876   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
8877   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
8878   case X86ISD::FMAX:               return "X86ISD::FMAX";
8879   case X86ISD::FMIN:               return "X86ISD::FMIN";
8880   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8881   case X86ISD::FRCP:               return "X86ISD::FRCP";
8882   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8883   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8884   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8885   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8886   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8887   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8888   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8889   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8890   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8891   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8892   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8893   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8894   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8895   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8896   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8897   case X86ISD::VSHL:               return "X86ISD::VSHL";
8898   case X86ISD::VSRL:               return "X86ISD::VSRL";
8899   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8900   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8901   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8902   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8903   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8904   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8905   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8906   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8907   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8908   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8909   case X86ISD::ADD:                return "X86ISD::ADD";
8910   case X86ISD::SUB:                return "X86ISD::SUB";
8911   case X86ISD::SMUL:               return "X86ISD::SMUL";
8912   case X86ISD::UMUL:               return "X86ISD::UMUL";
8913   case X86ISD::INC:                return "X86ISD::INC";
8914   case X86ISD::DEC:                return "X86ISD::DEC";
8915   case X86ISD::OR:                 return "X86ISD::OR";
8916   case X86ISD::XOR:                return "X86ISD::XOR";
8917   case X86ISD::AND:                return "X86ISD::AND";
8918   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8919   case X86ISD::PTEST:              return "X86ISD::PTEST";
8920   case X86ISD::TESTP:              return "X86ISD::TESTP";
8921   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8922   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8923   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8924   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8925   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8926   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8927   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8928   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8929   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8930   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8931   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8932   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8933   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8934   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8935   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8936   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8937   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8938   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8939   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8940   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8941   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8942   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8943   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8944   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8945   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8946   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8947   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8948   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8949   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8950   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8951   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8952   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8953   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8954   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8955   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
8956   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
8957   }
8958 }
8959
8960 // isLegalAddressingMode - Return true if the addressing mode represented
8961 // by AM is legal for this target, for a load/store of the specified type.
8962 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8963                                               const Type *Ty) const {
8964   // X86 supports extremely general addressing modes.
8965   CodeModel::Model M = getTargetMachine().getCodeModel();
8966   Reloc::Model R = getTargetMachine().getRelocationModel();
8967
8968   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8969   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8970     return false;
8971
8972   if (AM.BaseGV) {
8973     unsigned GVFlags =
8974       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8975
8976     // If a reference to this global requires an extra load, we can't fold it.
8977     if (isGlobalStubReference(GVFlags))
8978       return false;
8979
8980     // If BaseGV requires a register for the PIC base, we cannot also have a
8981     // BaseReg specified.
8982     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8983       return false;
8984
8985     // If lower 4G is not available, then we must use rip-relative addressing.
8986     if ((M != CodeModel::Small || R != Reloc::Static) &&
8987         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8988       return false;
8989   }
8990
8991   switch (AM.Scale) {
8992   case 0:
8993   case 1:
8994   case 2:
8995   case 4:
8996   case 8:
8997     // These scales always work.
8998     break;
8999   case 3:
9000   case 5:
9001   case 9:
9002     // These scales are formed with basereg+scalereg.  Only accept if there is
9003     // no basereg yet.
9004     if (AM.HasBaseReg)
9005       return false;
9006     break;
9007   default:  // Other stuff never works.
9008     return false;
9009   }
9010
9011   return true;
9012 }
9013
9014
9015 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9016   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9017     return false;
9018   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9019   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9020   if (NumBits1 <= NumBits2)
9021     return false;
9022   return true;
9023 }
9024
9025 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9026   if (!VT1.isInteger() || !VT2.isInteger())
9027     return false;
9028   unsigned NumBits1 = VT1.getSizeInBits();
9029   unsigned NumBits2 = VT2.getSizeInBits();
9030   if (NumBits1 <= NumBits2)
9031     return false;
9032   return true;
9033 }
9034
9035 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9036   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9037   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9038 }
9039
9040 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9041   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9042   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9043 }
9044
9045 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9046   // i16 instructions are longer (0x66 prefix) and potentially slower.
9047   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9048 }
9049
9050 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9051 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9052 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9053 /// are assumed to be legal.
9054 bool
9055 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9056                                       EVT VT) const {
9057   // Very little shuffling can be done for 64-bit vectors right now.
9058   if (VT.getSizeInBits() == 64)
9059     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9060
9061   // FIXME: pshufb, blends, shifts.
9062   return (VT.getVectorNumElements() == 2 ||
9063           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9064           isMOVLMask(M, VT) ||
9065           isSHUFPMask(M, VT) ||
9066           isPSHUFDMask(M, VT) ||
9067           isPSHUFHWMask(M, VT) ||
9068           isPSHUFLWMask(M, VT) ||
9069           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9070           isUNPCKLMask(M, VT) ||
9071           isUNPCKHMask(M, VT) ||
9072           isUNPCKL_v_undef_Mask(M, VT) ||
9073           isUNPCKH_v_undef_Mask(M, VT));
9074 }
9075
9076 bool
9077 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9078                                           EVT VT) const {
9079   unsigned NumElts = VT.getVectorNumElements();
9080   // FIXME: This collection of masks seems suspect.
9081   if (NumElts == 2)
9082     return true;
9083   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9084     return (isMOVLMask(Mask, VT)  ||
9085             isCommutedMOVLMask(Mask, VT, true) ||
9086             isSHUFPMask(Mask, VT) ||
9087             isCommutedSHUFPMask(Mask, VT));
9088   }
9089   return false;
9090 }
9091
9092 //===----------------------------------------------------------------------===//
9093 //                           X86 Scheduler Hooks
9094 //===----------------------------------------------------------------------===//
9095
9096 // private utility function
9097 MachineBasicBlock *
9098 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9099                                                        MachineBasicBlock *MBB,
9100                                                        unsigned regOpc,
9101                                                        unsigned immOpc,
9102                                                        unsigned LoadOpc,
9103                                                        unsigned CXchgOpc,
9104                                                        unsigned notOpc,
9105                                                        unsigned EAXreg,
9106                                                        TargetRegisterClass *RC,
9107                                                        bool invSrc) const {
9108   // For the atomic bitwise operator, we generate
9109   //   thisMBB:
9110   //   newMBB:
9111   //     ld  t1 = [bitinstr.addr]
9112   //     op  t2 = t1, [bitinstr.val]
9113   //     mov EAX = t1
9114   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9115   //     bz  newMBB
9116   //     fallthrough -->nextMBB
9117   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9118   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9119   MachineFunction::iterator MBBIter = MBB;
9120   ++MBBIter;
9121
9122   /// First build the CFG
9123   MachineFunction *F = MBB->getParent();
9124   MachineBasicBlock *thisMBB = MBB;
9125   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9126   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9127   F->insert(MBBIter, newMBB);
9128   F->insert(MBBIter, nextMBB);
9129
9130   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9131   nextMBB->splice(nextMBB->begin(), thisMBB,
9132                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9133                   thisMBB->end());
9134   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9135
9136   // Update thisMBB to fall through to newMBB
9137   thisMBB->addSuccessor(newMBB);
9138
9139   // newMBB jumps to itself and fall through to nextMBB
9140   newMBB->addSuccessor(nextMBB);
9141   newMBB->addSuccessor(newMBB);
9142
9143   // Insert instructions into newMBB based on incoming instruction
9144   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9145          "unexpected number of operands");
9146   DebugLoc dl = bInstr->getDebugLoc();
9147   MachineOperand& destOper = bInstr->getOperand(0);
9148   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9149   int numArgs = bInstr->getNumOperands() - 1;
9150   for (int i=0; i < numArgs; ++i)
9151     argOpers[i] = &bInstr->getOperand(i+1);
9152
9153   // x86 address has 4 operands: base, index, scale, and displacement
9154   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9155   int valArgIndx = lastAddrIndx + 1;
9156
9157   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9158   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9159   for (int i=0; i <= lastAddrIndx; ++i)
9160     (*MIB).addOperand(*argOpers[i]);
9161
9162   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9163   if (invSrc) {
9164     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9165   }
9166   else
9167     tt = t1;
9168
9169   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9170   assert((argOpers[valArgIndx]->isReg() ||
9171           argOpers[valArgIndx]->isImm()) &&
9172          "invalid operand");
9173   if (argOpers[valArgIndx]->isReg())
9174     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9175   else
9176     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9177   MIB.addReg(tt);
9178   (*MIB).addOperand(*argOpers[valArgIndx]);
9179
9180   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9181   MIB.addReg(t1);
9182
9183   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9184   for (int i=0; i <= lastAddrIndx; ++i)
9185     (*MIB).addOperand(*argOpers[i]);
9186   MIB.addReg(t2);
9187   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9188   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9189                     bInstr->memoperands_end());
9190
9191   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9192   MIB.addReg(EAXreg);
9193
9194   // insert branch
9195   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9196
9197   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9198   return nextMBB;
9199 }
9200
9201 // private utility function:  64 bit atomics on 32 bit host.
9202 MachineBasicBlock *
9203 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9204                                                        MachineBasicBlock *MBB,
9205                                                        unsigned regOpcL,
9206                                                        unsigned regOpcH,
9207                                                        unsigned immOpcL,
9208                                                        unsigned immOpcH,
9209                                                        bool invSrc) const {
9210   // For the atomic bitwise operator, we generate
9211   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9212   //     ld t1,t2 = [bitinstr.addr]
9213   //   newMBB:
9214   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9215   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9216   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9217   //     mov ECX, EBX <- t5, t6
9218   //     mov EAX, EDX <- t1, t2
9219   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9220   //     mov t3, t4 <- EAX, EDX
9221   //     bz  newMBB
9222   //     result in out1, out2
9223   //     fallthrough -->nextMBB
9224
9225   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9226   const unsigned LoadOpc = X86::MOV32rm;
9227   const unsigned NotOpc = X86::NOT32r;
9228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9229   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9230   MachineFunction::iterator MBBIter = MBB;
9231   ++MBBIter;
9232
9233   /// First build the CFG
9234   MachineFunction *F = MBB->getParent();
9235   MachineBasicBlock *thisMBB = MBB;
9236   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9237   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9238   F->insert(MBBIter, newMBB);
9239   F->insert(MBBIter, nextMBB);
9240
9241   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9242   nextMBB->splice(nextMBB->begin(), thisMBB,
9243                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9244                   thisMBB->end());
9245   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9246
9247   // Update thisMBB to fall through to newMBB
9248   thisMBB->addSuccessor(newMBB);
9249
9250   // newMBB jumps to itself and fall through to nextMBB
9251   newMBB->addSuccessor(nextMBB);
9252   newMBB->addSuccessor(newMBB);
9253
9254   DebugLoc dl = bInstr->getDebugLoc();
9255   // Insert instructions into newMBB based on incoming instruction
9256   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9257   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9258          "unexpected number of operands");
9259   MachineOperand& dest1Oper = bInstr->getOperand(0);
9260   MachineOperand& dest2Oper = bInstr->getOperand(1);
9261   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9262   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9263     argOpers[i] = &bInstr->getOperand(i+2);
9264
9265     // We use some of the operands multiple times, so conservatively just
9266     // clear any kill flags that might be present.
9267     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9268       argOpers[i]->setIsKill(false);
9269   }
9270
9271   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9272   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9273
9274   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9275   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9276   for (int i=0; i <= lastAddrIndx; ++i)
9277     (*MIB).addOperand(*argOpers[i]);
9278   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9279   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9280   // add 4 to displacement.
9281   for (int i=0; i <= lastAddrIndx-2; ++i)
9282     (*MIB).addOperand(*argOpers[i]);
9283   MachineOperand newOp3 = *(argOpers[3]);
9284   if (newOp3.isImm())
9285     newOp3.setImm(newOp3.getImm()+4);
9286   else
9287     newOp3.setOffset(newOp3.getOffset()+4);
9288   (*MIB).addOperand(newOp3);
9289   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9290
9291   // t3/4 are defined later, at the bottom of the loop
9292   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9293   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9294   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9295     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9296   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9297     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9298
9299   // The subsequent operations should be using the destination registers of
9300   //the PHI instructions.
9301   if (invSrc) {
9302     t1 = F->getRegInfo().createVirtualRegister(RC);
9303     t2 = F->getRegInfo().createVirtualRegister(RC);
9304     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9305     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9306   } else {
9307     t1 = dest1Oper.getReg();
9308     t2 = dest2Oper.getReg();
9309   }
9310
9311   int valArgIndx = lastAddrIndx + 1;
9312   assert((argOpers[valArgIndx]->isReg() ||
9313           argOpers[valArgIndx]->isImm()) &&
9314          "invalid operand");
9315   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9316   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9317   if (argOpers[valArgIndx]->isReg())
9318     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9319   else
9320     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9321   if (regOpcL != X86::MOV32rr)
9322     MIB.addReg(t1);
9323   (*MIB).addOperand(*argOpers[valArgIndx]);
9324   assert(argOpers[valArgIndx + 1]->isReg() ==
9325          argOpers[valArgIndx]->isReg());
9326   assert(argOpers[valArgIndx + 1]->isImm() ==
9327          argOpers[valArgIndx]->isImm());
9328   if (argOpers[valArgIndx + 1]->isReg())
9329     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9330   else
9331     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9332   if (regOpcH != X86::MOV32rr)
9333     MIB.addReg(t2);
9334   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9335
9336   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9337   MIB.addReg(t1);
9338   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9339   MIB.addReg(t2);
9340
9341   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9342   MIB.addReg(t5);
9343   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9344   MIB.addReg(t6);
9345
9346   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9347   for (int i=0; i <= lastAddrIndx; ++i)
9348     (*MIB).addOperand(*argOpers[i]);
9349
9350   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9351   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9352                     bInstr->memoperands_end());
9353
9354   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9355   MIB.addReg(X86::EAX);
9356   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9357   MIB.addReg(X86::EDX);
9358
9359   // insert branch
9360   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9361
9362   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9363   return nextMBB;
9364 }
9365
9366 // private utility function
9367 MachineBasicBlock *
9368 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9369                                                       MachineBasicBlock *MBB,
9370                                                       unsigned cmovOpc) const {
9371   // For the atomic min/max operator, we generate
9372   //   thisMBB:
9373   //   newMBB:
9374   //     ld t1 = [min/max.addr]
9375   //     mov t2 = [min/max.val]
9376   //     cmp  t1, t2
9377   //     cmov[cond] t2 = t1
9378   //     mov EAX = t1
9379   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9380   //     bz   newMBB
9381   //     fallthrough -->nextMBB
9382   //
9383   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9384   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9385   MachineFunction::iterator MBBIter = MBB;
9386   ++MBBIter;
9387
9388   /// First build the CFG
9389   MachineFunction *F = MBB->getParent();
9390   MachineBasicBlock *thisMBB = MBB;
9391   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9392   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9393   F->insert(MBBIter, newMBB);
9394   F->insert(MBBIter, nextMBB);
9395
9396   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9397   nextMBB->splice(nextMBB->begin(), thisMBB,
9398                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9399                   thisMBB->end());
9400   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9401
9402   // Update thisMBB to fall through to newMBB
9403   thisMBB->addSuccessor(newMBB);
9404
9405   // newMBB jumps to newMBB and fall through to nextMBB
9406   newMBB->addSuccessor(nextMBB);
9407   newMBB->addSuccessor(newMBB);
9408
9409   DebugLoc dl = mInstr->getDebugLoc();
9410   // Insert instructions into newMBB based on incoming instruction
9411   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9412          "unexpected number of operands");
9413   MachineOperand& destOper = mInstr->getOperand(0);
9414   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9415   int numArgs = mInstr->getNumOperands() - 1;
9416   for (int i=0; i < numArgs; ++i)
9417     argOpers[i] = &mInstr->getOperand(i+1);
9418
9419   // x86 address has 4 operands: base, index, scale, and displacement
9420   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9421   int valArgIndx = lastAddrIndx + 1;
9422
9423   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9424   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9425   for (int i=0; i <= lastAddrIndx; ++i)
9426     (*MIB).addOperand(*argOpers[i]);
9427
9428   // We only support register and immediate values
9429   assert((argOpers[valArgIndx]->isReg() ||
9430           argOpers[valArgIndx]->isImm()) &&
9431          "invalid operand");
9432
9433   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9434   if (argOpers[valArgIndx]->isReg())
9435     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9436   else
9437     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9438   (*MIB).addOperand(*argOpers[valArgIndx]);
9439
9440   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9441   MIB.addReg(t1);
9442
9443   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9444   MIB.addReg(t1);
9445   MIB.addReg(t2);
9446
9447   // Generate movc
9448   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9449   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9450   MIB.addReg(t2);
9451   MIB.addReg(t1);
9452
9453   // Cmp and exchange if none has modified the memory location
9454   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9455   for (int i=0; i <= lastAddrIndx; ++i)
9456     (*MIB).addOperand(*argOpers[i]);
9457   MIB.addReg(t3);
9458   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9459   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9460                     mInstr->memoperands_end());
9461
9462   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9463   MIB.addReg(X86::EAX);
9464
9465   // insert branch
9466   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9467
9468   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9469   return nextMBB;
9470 }
9471
9472 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9473 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9474 // in the .td file.
9475 MachineBasicBlock *
9476 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9477                             unsigned numArgs, bool memArg) const {
9478   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9479          "Target must have SSE4.2 or AVX features enabled");
9480
9481   DebugLoc dl = MI->getDebugLoc();
9482   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9483   unsigned Opc;
9484   if (!Subtarget->hasAVX()) {
9485     if (memArg)
9486       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9487     else
9488       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9489   } else {
9490     if (memArg)
9491       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9492     else
9493       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9494   }
9495
9496   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9497   for (unsigned i = 0; i < numArgs; ++i) {
9498     MachineOperand &Op = MI->getOperand(i+1);
9499     if (!(Op.isReg() && Op.isImplicit()))
9500       MIB.addOperand(Op);
9501   }
9502   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9503     .addReg(X86::XMM0);
9504
9505   MI->eraseFromParent();
9506   return BB;
9507 }
9508
9509 MachineBasicBlock *
9510 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9511   DebugLoc dl = MI->getDebugLoc();
9512   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9513   
9514   // Address into RAX/EAX, other two args into ECX, EDX.
9515   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9516   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9517   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9518   for (int i = 0; i < X86::AddrNumOperands; ++i)
9519     MIB.addOperand(MI->getOperand(i));
9520   
9521   unsigned ValOps = X86::AddrNumOperands;
9522   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9523     .addReg(MI->getOperand(ValOps).getReg());
9524   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9525     .addReg(MI->getOperand(ValOps+1).getReg());
9526
9527   // The instruction doesn't actually take any operands though.
9528   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9529   
9530   MI->eraseFromParent(); // The pseudo is gone now.
9531   return BB;
9532 }
9533
9534 MachineBasicBlock *
9535 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9536   DebugLoc dl = MI->getDebugLoc();
9537   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9538   
9539   // First arg in ECX, the second in EAX.
9540   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9541     .addReg(MI->getOperand(0).getReg());
9542   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9543     .addReg(MI->getOperand(1).getReg());
9544     
9545   // The instruction doesn't actually take any operands though.
9546   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9547   
9548   MI->eraseFromParent(); // The pseudo is gone now.
9549   return BB;
9550 }
9551
9552 MachineBasicBlock *
9553 X86TargetLowering::EmitVAARG64WithCustomInserter(
9554                    MachineInstr *MI,
9555                    MachineBasicBlock *MBB) const {
9556   // Emit va_arg instruction on X86-64.
9557
9558   // Operands to this pseudo-instruction:
9559   // 0  ) Output        : destination address (reg)
9560   // 1-5) Input         : va_list address (addr, i64mem)
9561   // 6  ) ArgSize       : Size (in bytes) of vararg type
9562   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9563   // 8  ) Align         : Alignment of type
9564   // 9  ) EFLAGS (implicit-def)
9565
9566   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9567   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9568
9569   unsigned DestReg = MI->getOperand(0).getReg();
9570   MachineOperand &Base = MI->getOperand(1);
9571   MachineOperand &Scale = MI->getOperand(2);
9572   MachineOperand &Index = MI->getOperand(3);
9573   MachineOperand &Disp = MI->getOperand(4);
9574   MachineOperand &Segment = MI->getOperand(5);
9575   unsigned ArgSize = MI->getOperand(6).getImm();
9576   unsigned ArgMode = MI->getOperand(7).getImm();
9577   unsigned Align = MI->getOperand(8).getImm();
9578
9579   // Memory Reference
9580   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9581   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9582   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9583
9584   // Machine Information
9585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9586   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9587   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9588   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9589   DebugLoc DL = MI->getDebugLoc();
9590
9591   // struct va_list {
9592   //   i32   gp_offset
9593   //   i32   fp_offset
9594   //   i64   overflow_area (address)
9595   //   i64   reg_save_area (address)
9596   // }
9597   // sizeof(va_list) = 24
9598   // alignment(va_list) = 8
9599
9600   unsigned TotalNumIntRegs = 6;
9601   unsigned TotalNumXMMRegs = 8;
9602   bool UseGPOffset = (ArgMode == 1);
9603   bool UseFPOffset = (ArgMode == 2);
9604   unsigned MaxOffset = TotalNumIntRegs * 8 +
9605                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9606
9607   /* Align ArgSize to a multiple of 8 */
9608   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9609   bool NeedsAlign = (Align > 8);
9610
9611   MachineBasicBlock *thisMBB = MBB;
9612   MachineBasicBlock *overflowMBB;
9613   MachineBasicBlock *offsetMBB;
9614   MachineBasicBlock *endMBB;
9615
9616   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9617   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9618   unsigned OffsetReg = 0;
9619
9620   if (!UseGPOffset && !UseFPOffset) {
9621     // If we only pull from the overflow region, we don't create a branch.
9622     // We don't need to alter control flow.
9623     OffsetDestReg = 0; // unused
9624     OverflowDestReg = DestReg;
9625
9626     offsetMBB = NULL;
9627     overflowMBB = thisMBB;
9628     endMBB = thisMBB;
9629   } else {
9630     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9631     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9632     // If not, pull from overflow_area. (branch to overflowMBB)
9633     //
9634     //       thisMBB
9635     //         |     .
9636     //         |        .
9637     //     offsetMBB   overflowMBB
9638     //         |        .
9639     //         |     .
9640     //        endMBB
9641
9642     // Registers for the PHI in endMBB
9643     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9644     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9645
9646     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9647     MachineFunction *MF = MBB->getParent();
9648     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9649     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9650     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9651
9652     MachineFunction::iterator MBBIter = MBB;
9653     ++MBBIter;
9654
9655     // Insert the new basic blocks
9656     MF->insert(MBBIter, offsetMBB);
9657     MF->insert(MBBIter, overflowMBB);
9658     MF->insert(MBBIter, endMBB);
9659
9660     // Transfer the remainder of MBB and its successor edges to endMBB.
9661     endMBB->splice(endMBB->begin(), thisMBB,
9662                     llvm::next(MachineBasicBlock::iterator(MI)),
9663                     thisMBB->end());
9664     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9665
9666     // Make offsetMBB and overflowMBB successors of thisMBB
9667     thisMBB->addSuccessor(offsetMBB);
9668     thisMBB->addSuccessor(overflowMBB);
9669
9670     // endMBB is a successor of both offsetMBB and overflowMBB
9671     offsetMBB->addSuccessor(endMBB);
9672     overflowMBB->addSuccessor(endMBB);
9673
9674     // Load the offset value into a register
9675     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9676     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9677       .addOperand(Base)
9678       .addOperand(Scale)
9679       .addOperand(Index)
9680       .addDisp(Disp, UseFPOffset ? 4 : 0)
9681       .addOperand(Segment)
9682       .setMemRefs(MMOBegin, MMOEnd);
9683
9684     // Check if there is enough room left to pull this argument.
9685     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9686       .addReg(OffsetReg)
9687       .addImm(MaxOffset + 8 - ArgSizeA8);
9688
9689     // Branch to "overflowMBB" if offset >= max
9690     // Fall through to "offsetMBB" otherwise
9691     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9692       .addMBB(overflowMBB);
9693   }
9694
9695   // In offsetMBB, emit code to use the reg_save_area.
9696   if (offsetMBB) {
9697     assert(OffsetReg != 0);
9698
9699     // Read the reg_save_area address.
9700     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9701     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9702       .addOperand(Base)
9703       .addOperand(Scale)
9704       .addOperand(Index)
9705       .addDisp(Disp, 16)
9706       .addOperand(Segment)
9707       .setMemRefs(MMOBegin, MMOEnd);
9708
9709     // Zero-extend the offset
9710     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9711       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9712         .addImm(0)
9713         .addReg(OffsetReg)
9714         .addImm(X86::sub_32bit);
9715
9716     // Add the offset to the reg_save_area to get the final address.
9717     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9718       .addReg(OffsetReg64)
9719       .addReg(RegSaveReg);
9720
9721     // Compute the offset for the next argument
9722     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9723     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9724       .addReg(OffsetReg)
9725       .addImm(UseFPOffset ? 16 : 8);
9726
9727     // Store it back into the va_list.
9728     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9729       .addOperand(Base)
9730       .addOperand(Scale)
9731       .addOperand(Index)
9732       .addDisp(Disp, UseFPOffset ? 4 : 0)
9733       .addOperand(Segment)
9734       .addReg(NextOffsetReg)
9735       .setMemRefs(MMOBegin, MMOEnd);
9736
9737     // Jump to endMBB
9738     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9739       .addMBB(endMBB);
9740   }
9741
9742   //
9743   // Emit code to use overflow area
9744   //
9745
9746   // Load the overflow_area address into a register.
9747   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9748   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9749     .addOperand(Base)
9750     .addOperand(Scale)
9751     .addOperand(Index)
9752     .addDisp(Disp, 8)
9753     .addOperand(Segment)
9754     .setMemRefs(MMOBegin, MMOEnd);
9755
9756   // If we need to align it, do so. Otherwise, just copy the address
9757   // to OverflowDestReg.
9758   if (NeedsAlign) {
9759     // Align the overflow address
9760     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9761     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9762
9763     // aligned_addr = (addr + (align-1)) & ~(align-1)
9764     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9765       .addReg(OverflowAddrReg)
9766       .addImm(Align-1);
9767
9768     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9769       .addReg(TmpReg)
9770       .addImm(~(uint64_t)(Align-1));
9771   } else {
9772     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9773       .addReg(OverflowAddrReg);
9774   }
9775
9776   // Compute the next overflow address after this argument.
9777   // (the overflow address should be kept 8-byte aligned)
9778   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9779   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9780     .addReg(OverflowDestReg)
9781     .addImm(ArgSizeA8);
9782
9783   // Store the new overflow address.
9784   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9785     .addOperand(Base)
9786     .addOperand(Scale)
9787     .addOperand(Index)
9788     .addDisp(Disp, 8)
9789     .addOperand(Segment)
9790     .addReg(NextAddrReg)
9791     .setMemRefs(MMOBegin, MMOEnd);
9792
9793   // If we branched, emit the PHI to the front of endMBB.
9794   if (offsetMBB) {
9795     BuildMI(*endMBB, endMBB->begin(), DL,
9796             TII->get(X86::PHI), DestReg)
9797       .addReg(OffsetDestReg).addMBB(offsetMBB)
9798       .addReg(OverflowDestReg).addMBB(overflowMBB);
9799   }
9800
9801   // Erase the pseudo instruction
9802   MI->eraseFromParent();
9803
9804   return endMBB;
9805 }
9806
9807 MachineBasicBlock *
9808 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9809                                                  MachineInstr *MI,
9810                                                  MachineBasicBlock *MBB) const {
9811   // Emit code to save XMM registers to the stack. The ABI says that the
9812   // number of registers to save is given in %al, so it's theoretically
9813   // possible to do an indirect jump trick to avoid saving all of them,
9814   // however this code takes a simpler approach and just executes all
9815   // of the stores if %al is non-zero. It's less code, and it's probably
9816   // easier on the hardware branch predictor, and stores aren't all that
9817   // expensive anyway.
9818
9819   // Create the new basic blocks. One block contains all the XMM stores,
9820   // and one block is the final destination regardless of whether any
9821   // stores were performed.
9822   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9823   MachineFunction *F = MBB->getParent();
9824   MachineFunction::iterator MBBIter = MBB;
9825   ++MBBIter;
9826   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9827   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9828   F->insert(MBBIter, XMMSaveMBB);
9829   F->insert(MBBIter, EndMBB);
9830
9831   // Transfer the remainder of MBB and its successor edges to EndMBB.
9832   EndMBB->splice(EndMBB->begin(), MBB,
9833                  llvm::next(MachineBasicBlock::iterator(MI)),
9834                  MBB->end());
9835   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9836
9837   // The original block will now fall through to the XMM save block.
9838   MBB->addSuccessor(XMMSaveMBB);
9839   // The XMMSaveMBB will fall through to the end block.
9840   XMMSaveMBB->addSuccessor(EndMBB);
9841
9842   // Now add the instructions.
9843   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9844   DebugLoc DL = MI->getDebugLoc();
9845
9846   unsigned CountReg = MI->getOperand(0).getReg();
9847   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9848   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9849
9850   if (!Subtarget->isTargetWin64()) {
9851     // If %al is 0, branch around the XMM save block.
9852     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9853     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9854     MBB->addSuccessor(EndMBB);
9855   }
9856
9857   // In the XMM save block, save all the XMM argument registers.
9858   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9859     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9860     MachineMemOperand *MMO =
9861       F->getMachineMemOperand(
9862           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9863         MachineMemOperand::MOStore,
9864         /*Size=*/16, /*Align=*/16);
9865     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9866       .addFrameIndex(RegSaveFrameIndex)
9867       .addImm(/*Scale=*/1)
9868       .addReg(/*IndexReg=*/0)
9869       .addImm(/*Disp=*/Offset)
9870       .addReg(/*Segment=*/0)
9871       .addReg(MI->getOperand(i).getReg())
9872       .addMemOperand(MMO);
9873   }
9874
9875   MI->eraseFromParent();   // The pseudo instruction is gone now.
9876
9877   return EndMBB;
9878 }
9879
9880 MachineBasicBlock *
9881 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9882                                      MachineBasicBlock *BB) const {
9883   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9884   DebugLoc DL = MI->getDebugLoc();
9885
9886   // To "insert" a SELECT_CC instruction, we actually have to insert the
9887   // diamond control-flow pattern.  The incoming instruction knows the
9888   // destination vreg to set, the condition code register to branch on, the
9889   // true/false values to select between, and a branch opcode to use.
9890   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9891   MachineFunction::iterator It = BB;
9892   ++It;
9893
9894   //  thisMBB:
9895   //  ...
9896   //   TrueVal = ...
9897   //   cmpTY ccX, r1, r2
9898   //   bCC copy1MBB
9899   //   fallthrough --> copy0MBB
9900   MachineBasicBlock *thisMBB = BB;
9901   MachineFunction *F = BB->getParent();
9902   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9903   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9904   F->insert(It, copy0MBB);
9905   F->insert(It, sinkMBB);
9906
9907   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9908   // live into the sink and copy blocks.
9909   const MachineFunction *MF = BB->getParent();
9910   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9911   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9912
9913   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9914     const MachineOperand &MO = MI->getOperand(I);
9915     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9916     unsigned Reg = MO.getReg();
9917     if (Reg != X86::EFLAGS) continue;
9918     copy0MBB->addLiveIn(Reg);
9919     sinkMBB->addLiveIn(Reg);
9920   }
9921
9922   // Transfer the remainder of BB and its successor edges to sinkMBB.
9923   sinkMBB->splice(sinkMBB->begin(), BB,
9924                   llvm::next(MachineBasicBlock::iterator(MI)),
9925                   BB->end());
9926   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9927
9928   // Add the true and fallthrough blocks as its successors.
9929   BB->addSuccessor(copy0MBB);
9930   BB->addSuccessor(sinkMBB);
9931
9932   // Create the conditional branch instruction.
9933   unsigned Opc =
9934     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9935   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9936
9937   //  copy0MBB:
9938   //   %FalseValue = ...
9939   //   # fallthrough to sinkMBB
9940   copy0MBB->addSuccessor(sinkMBB);
9941
9942   //  sinkMBB:
9943   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9944   //  ...
9945   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9946           TII->get(X86::PHI), MI->getOperand(0).getReg())
9947     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9948     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9949
9950   MI->eraseFromParent();   // The pseudo instruction is gone now.
9951   return sinkMBB;
9952 }
9953
9954 MachineBasicBlock *
9955 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9956                                           MachineBasicBlock *BB) const {
9957   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9958   DebugLoc DL = MI->getDebugLoc();
9959
9960   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9961   // non-trivial part is impdef of ESP.
9962   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9963   // mingw-w64.
9964
9965   const char *StackProbeSymbol =
9966       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9967
9968   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9969     .addExternalSymbol(StackProbeSymbol)
9970     .addReg(X86::EAX, RegState::Implicit)
9971     .addReg(X86::ESP, RegState::Implicit)
9972     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9973     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9974     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9975
9976   MI->eraseFromParent();   // The pseudo instruction is gone now.
9977   return BB;
9978 }
9979
9980 MachineBasicBlock *
9981 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9982                                       MachineBasicBlock *BB) const {
9983   // This is pretty easy.  We're taking the value that we received from
9984   // our load from the relocation, sticking it in either RDI (x86-64)
9985   // or EAX and doing an indirect call.  The return value will then
9986   // be in the normal return register.
9987   const X86InstrInfo *TII
9988     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9989   DebugLoc DL = MI->getDebugLoc();
9990   MachineFunction *F = BB->getParent();
9991
9992   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9993   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9994
9995   if (Subtarget->is64Bit()) {
9996     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9997                                       TII->get(X86::MOV64rm), X86::RDI)
9998     .addReg(X86::RIP)
9999     .addImm(0).addReg(0)
10000     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10001                       MI->getOperand(3).getTargetFlags())
10002     .addReg(0);
10003     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10004     addDirectMem(MIB, X86::RDI);
10005   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10006     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10007                                       TII->get(X86::MOV32rm), X86::EAX)
10008     .addReg(0)
10009     .addImm(0).addReg(0)
10010     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10011                       MI->getOperand(3).getTargetFlags())
10012     .addReg(0);
10013     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10014     addDirectMem(MIB, X86::EAX);
10015   } else {
10016     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10017                                       TII->get(X86::MOV32rm), X86::EAX)
10018     .addReg(TII->getGlobalBaseReg(F))
10019     .addImm(0).addReg(0)
10020     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10021                       MI->getOperand(3).getTargetFlags())
10022     .addReg(0);
10023     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10024     addDirectMem(MIB, X86::EAX);
10025   }
10026
10027   MI->eraseFromParent(); // The pseudo instruction is gone now.
10028   return BB;
10029 }
10030
10031 MachineBasicBlock *
10032 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10033                                                MachineBasicBlock *BB) const {
10034   switch (MI->getOpcode()) {
10035   default: assert(false && "Unexpected instr type to insert");
10036   case X86::WIN_ALLOCA:
10037     return EmitLoweredWinAlloca(MI, BB);
10038   case X86::TLSCall_32:
10039   case X86::TLSCall_64:
10040     return EmitLoweredTLSCall(MI, BB);
10041   case X86::CMOV_GR8:
10042   case X86::CMOV_FR32:
10043   case X86::CMOV_FR64:
10044   case X86::CMOV_V4F32:
10045   case X86::CMOV_V2F64:
10046   case X86::CMOV_V2I64:
10047   case X86::CMOV_GR16:
10048   case X86::CMOV_GR32:
10049   case X86::CMOV_RFP32:
10050   case X86::CMOV_RFP64:
10051   case X86::CMOV_RFP80:
10052     return EmitLoweredSelect(MI, BB);
10053
10054   case X86::FP32_TO_INT16_IN_MEM:
10055   case X86::FP32_TO_INT32_IN_MEM:
10056   case X86::FP32_TO_INT64_IN_MEM:
10057   case X86::FP64_TO_INT16_IN_MEM:
10058   case X86::FP64_TO_INT32_IN_MEM:
10059   case X86::FP64_TO_INT64_IN_MEM:
10060   case X86::FP80_TO_INT16_IN_MEM:
10061   case X86::FP80_TO_INT32_IN_MEM:
10062   case X86::FP80_TO_INT64_IN_MEM: {
10063     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10064     DebugLoc DL = MI->getDebugLoc();
10065
10066     // Change the floating point control register to use "round towards zero"
10067     // mode when truncating to an integer value.
10068     MachineFunction *F = BB->getParent();
10069     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10070     addFrameReference(BuildMI(*BB, MI, DL,
10071                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10072
10073     // Load the old value of the high byte of the control word...
10074     unsigned OldCW =
10075       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10076     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10077                       CWFrameIdx);
10078
10079     // Set the high part to be round to zero...
10080     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10081       .addImm(0xC7F);
10082
10083     // Reload the modified control word now...
10084     addFrameReference(BuildMI(*BB, MI, DL,
10085                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10086
10087     // Restore the memory image of control word to original value
10088     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10089       .addReg(OldCW);
10090
10091     // Get the X86 opcode to use.
10092     unsigned Opc;
10093     switch (MI->getOpcode()) {
10094     default: llvm_unreachable("illegal opcode!");
10095     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10096     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10097     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10098     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10099     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10100     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10101     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10102     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10103     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10104     }
10105
10106     X86AddressMode AM;
10107     MachineOperand &Op = MI->getOperand(0);
10108     if (Op.isReg()) {
10109       AM.BaseType = X86AddressMode::RegBase;
10110       AM.Base.Reg = Op.getReg();
10111     } else {
10112       AM.BaseType = X86AddressMode::FrameIndexBase;
10113       AM.Base.FrameIndex = Op.getIndex();
10114     }
10115     Op = MI->getOperand(1);
10116     if (Op.isImm())
10117       AM.Scale = Op.getImm();
10118     Op = MI->getOperand(2);
10119     if (Op.isImm())
10120       AM.IndexReg = Op.getImm();
10121     Op = MI->getOperand(3);
10122     if (Op.isGlobal()) {
10123       AM.GV = Op.getGlobal();
10124     } else {
10125       AM.Disp = Op.getImm();
10126     }
10127     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10128                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10129
10130     // Reload the original control word now.
10131     addFrameReference(BuildMI(*BB, MI, DL,
10132                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10133
10134     MI->eraseFromParent();   // The pseudo instruction is gone now.
10135     return BB;
10136   }
10137     // String/text processing lowering.
10138   case X86::PCMPISTRM128REG:
10139   case X86::VPCMPISTRM128REG:
10140     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10141   case X86::PCMPISTRM128MEM:
10142   case X86::VPCMPISTRM128MEM:
10143     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10144   case X86::PCMPESTRM128REG:
10145   case X86::VPCMPESTRM128REG:
10146     return EmitPCMP(MI, BB, 5, false /* in mem */);
10147   case X86::PCMPESTRM128MEM:
10148   case X86::VPCMPESTRM128MEM:
10149     return EmitPCMP(MI, BB, 5, true /* in mem */);
10150
10151     // Thread synchronization.
10152   case X86::MONITOR:
10153     return EmitMonitor(MI, BB);  
10154   case X86::MWAIT:
10155     return EmitMwait(MI, BB);
10156
10157     // Atomic Lowering.
10158   case X86::ATOMAND32:
10159     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10160                                                X86::AND32ri, X86::MOV32rm,
10161                                                X86::LCMPXCHG32,
10162                                                X86::NOT32r, X86::EAX,
10163                                                X86::GR32RegisterClass);
10164   case X86::ATOMOR32:
10165     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10166                                                X86::OR32ri, X86::MOV32rm,
10167                                                X86::LCMPXCHG32,
10168                                                X86::NOT32r, X86::EAX,
10169                                                X86::GR32RegisterClass);
10170   case X86::ATOMXOR32:
10171     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10172                                                X86::XOR32ri, X86::MOV32rm,
10173                                                X86::LCMPXCHG32,
10174                                                X86::NOT32r, X86::EAX,
10175                                                X86::GR32RegisterClass);
10176   case X86::ATOMNAND32:
10177     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10178                                                X86::AND32ri, X86::MOV32rm,
10179                                                X86::LCMPXCHG32,
10180                                                X86::NOT32r, X86::EAX,
10181                                                X86::GR32RegisterClass, true);
10182   case X86::ATOMMIN32:
10183     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10184   case X86::ATOMMAX32:
10185     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10186   case X86::ATOMUMIN32:
10187     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10188   case X86::ATOMUMAX32:
10189     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10190
10191   case X86::ATOMAND16:
10192     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10193                                                X86::AND16ri, X86::MOV16rm,
10194                                                X86::LCMPXCHG16,
10195                                                X86::NOT16r, X86::AX,
10196                                                X86::GR16RegisterClass);
10197   case X86::ATOMOR16:
10198     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10199                                                X86::OR16ri, X86::MOV16rm,
10200                                                X86::LCMPXCHG16,
10201                                                X86::NOT16r, X86::AX,
10202                                                X86::GR16RegisterClass);
10203   case X86::ATOMXOR16:
10204     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10205                                                X86::XOR16ri, X86::MOV16rm,
10206                                                X86::LCMPXCHG16,
10207                                                X86::NOT16r, X86::AX,
10208                                                X86::GR16RegisterClass);
10209   case X86::ATOMNAND16:
10210     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10211                                                X86::AND16ri, X86::MOV16rm,
10212                                                X86::LCMPXCHG16,
10213                                                X86::NOT16r, X86::AX,
10214                                                X86::GR16RegisterClass, true);
10215   case X86::ATOMMIN16:
10216     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10217   case X86::ATOMMAX16:
10218     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10219   case X86::ATOMUMIN16:
10220     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10221   case X86::ATOMUMAX16:
10222     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10223
10224   case X86::ATOMAND8:
10225     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10226                                                X86::AND8ri, X86::MOV8rm,
10227                                                X86::LCMPXCHG8,
10228                                                X86::NOT8r, X86::AL,
10229                                                X86::GR8RegisterClass);
10230   case X86::ATOMOR8:
10231     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10232                                                X86::OR8ri, X86::MOV8rm,
10233                                                X86::LCMPXCHG8,
10234                                                X86::NOT8r, X86::AL,
10235                                                X86::GR8RegisterClass);
10236   case X86::ATOMXOR8:
10237     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10238                                                X86::XOR8ri, X86::MOV8rm,
10239                                                X86::LCMPXCHG8,
10240                                                X86::NOT8r, X86::AL,
10241                                                X86::GR8RegisterClass);
10242   case X86::ATOMNAND8:
10243     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10244                                                X86::AND8ri, X86::MOV8rm,
10245                                                X86::LCMPXCHG8,
10246                                                X86::NOT8r, X86::AL,
10247                                                X86::GR8RegisterClass, true);
10248   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10249   // This group is for 64-bit host.
10250   case X86::ATOMAND64:
10251     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10252                                                X86::AND64ri32, X86::MOV64rm,
10253                                                X86::LCMPXCHG64,
10254                                                X86::NOT64r, X86::RAX,
10255                                                X86::GR64RegisterClass);
10256   case X86::ATOMOR64:
10257     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10258                                                X86::OR64ri32, X86::MOV64rm,
10259                                                X86::LCMPXCHG64,
10260                                                X86::NOT64r, X86::RAX,
10261                                                X86::GR64RegisterClass);
10262   case X86::ATOMXOR64:
10263     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10264                                                X86::XOR64ri32, X86::MOV64rm,
10265                                                X86::LCMPXCHG64,
10266                                                X86::NOT64r, X86::RAX,
10267                                                X86::GR64RegisterClass);
10268   case X86::ATOMNAND64:
10269     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10270                                                X86::AND64ri32, X86::MOV64rm,
10271                                                X86::LCMPXCHG64,
10272                                                X86::NOT64r, X86::RAX,
10273                                                X86::GR64RegisterClass, true);
10274   case X86::ATOMMIN64:
10275     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10276   case X86::ATOMMAX64:
10277     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10278   case X86::ATOMUMIN64:
10279     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10280   case X86::ATOMUMAX64:
10281     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10282
10283   // This group does 64-bit operations on a 32-bit host.
10284   case X86::ATOMAND6432:
10285     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10286                                                X86::AND32rr, X86::AND32rr,
10287                                                X86::AND32ri, X86::AND32ri,
10288                                                false);
10289   case X86::ATOMOR6432:
10290     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10291                                                X86::OR32rr, X86::OR32rr,
10292                                                X86::OR32ri, X86::OR32ri,
10293                                                false);
10294   case X86::ATOMXOR6432:
10295     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10296                                                X86::XOR32rr, X86::XOR32rr,
10297                                                X86::XOR32ri, X86::XOR32ri,
10298                                                false);
10299   case X86::ATOMNAND6432:
10300     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10301                                                X86::AND32rr, X86::AND32rr,
10302                                                X86::AND32ri, X86::AND32ri,
10303                                                true);
10304   case X86::ATOMADD6432:
10305     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10306                                                X86::ADD32rr, X86::ADC32rr,
10307                                                X86::ADD32ri, X86::ADC32ri,
10308                                                false);
10309   case X86::ATOMSUB6432:
10310     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10311                                                X86::SUB32rr, X86::SBB32rr,
10312                                                X86::SUB32ri, X86::SBB32ri,
10313                                                false);
10314   case X86::ATOMSWAP6432:
10315     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10316                                                X86::MOV32rr, X86::MOV32rr,
10317                                                X86::MOV32ri, X86::MOV32ri,
10318                                                false);
10319   case X86::VASTART_SAVE_XMM_REGS:
10320     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10321
10322   case X86::VAARG_64:
10323     return EmitVAARG64WithCustomInserter(MI, BB);
10324   }
10325 }
10326
10327 //===----------------------------------------------------------------------===//
10328 //                           X86 Optimization Hooks
10329 //===----------------------------------------------------------------------===//
10330
10331 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10332                                                        const APInt &Mask,
10333                                                        APInt &KnownZero,
10334                                                        APInt &KnownOne,
10335                                                        const SelectionDAG &DAG,
10336                                                        unsigned Depth) const {
10337   unsigned Opc = Op.getOpcode();
10338   assert((Opc >= ISD::BUILTIN_OP_END ||
10339           Opc == ISD::INTRINSIC_WO_CHAIN ||
10340           Opc == ISD::INTRINSIC_W_CHAIN ||
10341           Opc == ISD::INTRINSIC_VOID) &&
10342          "Should use MaskedValueIsZero if you don't know whether Op"
10343          " is a target node!");
10344
10345   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10346   switch (Opc) {
10347   default: break;
10348   case X86ISD::ADD:
10349   case X86ISD::SUB:
10350   case X86ISD::SMUL:
10351   case X86ISD::UMUL:
10352   case X86ISD::INC:
10353   case X86ISD::DEC:
10354   case X86ISD::OR:
10355   case X86ISD::XOR:
10356   case X86ISD::AND:
10357     // These nodes' second result is a boolean.
10358     if (Op.getResNo() == 0)
10359       break;
10360     // Fallthrough
10361   case X86ISD::SETCC:
10362     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10363                                        Mask.getBitWidth() - 1);
10364     break;
10365   }
10366 }
10367
10368 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10369                                                          unsigned Depth) const {
10370   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10371   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10372     return Op.getValueType().getScalarType().getSizeInBits();
10373
10374   // Fallback case.
10375   return 1;
10376 }
10377
10378 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10379 /// node is a GlobalAddress + offset.
10380 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10381                                        const GlobalValue* &GA,
10382                                        int64_t &Offset) const {
10383   if (N->getOpcode() == X86ISD::Wrapper) {
10384     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10385       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10386       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10387       return true;
10388     }
10389   }
10390   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10391 }
10392
10393 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10394 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10395 /// if the load addresses are consecutive, non-overlapping, and in the right
10396 /// order.
10397 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10398                                      const TargetLowering &TLI) {
10399   DebugLoc dl = N->getDebugLoc();
10400   EVT VT = N->getValueType(0);
10401
10402   if (VT.getSizeInBits() != 128)
10403     return SDValue();
10404
10405   SmallVector<SDValue, 16> Elts;
10406   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10407     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10408
10409   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10410 }
10411
10412 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10413 /// generation and convert it from being a bunch of shuffles and extracts
10414 /// to a simple store and scalar loads to extract the elements.
10415 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10416                                                 const TargetLowering &TLI) {
10417   SDValue InputVector = N->getOperand(0);
10418
10419   // Only operate on vectors of 4 elements, where the alternative shuffling
10420   // gets to be more expensive.
10421   if (InputVector.getValueType() != MVT::v4i32)
10422     return SDValue();
10423
10424   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10425   // single use which is a sign-extend or zero-extend, and all elements are
10426   // used.
10427   SmallVector<SDNode *, 4> Uses;
10428   unsigned ExtractedElements = 0;
10429   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10430        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10431     if (UI.getUse().getResNo() != InputVector.getResNo())
10432       return SDValue();
10433
10434     SDNode *Extract = *UI;
10435     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10436       return SDValue();
10437
10438     if (Extract->getValueType(0) != MVT::i32)
10439       return SDValue();
10440     if (!Extract->hasOneUse())
10441       return SDValue();
10442     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10443         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10444       return SDValue();
10445     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10446       return SDValue();
10447
10448     // Record which element was extracted.
10449     ExtractedElements |=
10450       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10451
10452     Uses.push_back(Extract);
10453   }
10454
10455   // If not all the elements were used, this may not be worthwhile.
10456   if (ExtractedElements != 15)
10457     return SDValue();
10458
10459   // Ok, we've now decided to do the transformation.
10460   DebugLoc dl = InputVector.getDebugLoc();
10461
10462   // Store the value to a temporary stack slot.
10463   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10464   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10465                             MachinePointerInfo(), false, false, 0);
10466
10467   // Replace each use (extract) with a load of the appropriate element.
10468   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10469        UE = Uses.end(); UI != UE; ++UI) {
10470     SDNode *Extract = *UI;
10471
10472     // Compute the element's address.
10473     SDValue Idx = Extract->getOperand(1);
10474     unsigned EltSize =
10475         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10476     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10477     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10478
10479     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10480                                      StackPtr, OffsetVal);
10481
10482     // Load the scalar.
10483     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10484                                      ScalarAddr, MachinePointerInfo(),
10485                                      false, false, 0);
10486
10487     // Replace the exact with the load.
10488     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10489   }
10490
10491   // The replacement was made in place; don't return anything.
10492   return SDValue();
10493 }
10494
10495 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10496 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10497                                     const X86Subtarget *Subtarget) {
10498   DebugLoc DL = N->getDebugLoc();
10499   SDValue Cond = N->getOperand(0);
10500   // Get the LHS/RHS of the select.
10501   SDValue LHS = N->getOperand(1);
10502   SDValue RHS = N->getOperand(2);
10503
10504   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10505   // instructions match the semantics of the common C idiom x<y?x:y but not
10506   // x<=y?x:y, because of how they handle negative zero (which can be
10507   // ignored in unsafe-math mode).
10508   if (Subtarget->hasSSE2() &&
10509       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10510       Cond.getOpcode() == ISD::SETCC) {
10511     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10512
10513     unsigned Opcode = 0;
10514     // Check for x CC y ? x : y.
10515     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10516         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10517       switch (CC) {
10518       default: break;
10519       case ISD::SETULT:
10520         // Converting this to a min would handle NaNs incorrectly, and swapping
10521         // the operands would cause it to handle comparisons between positive
10522         // and negative zero incorrectly.
10523         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10524           if (!UnsafeFPMath &&
10525               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10526             break;
10527           std::swap(LHS, RHS);
10528         }
10529         Opcode = X86ISD::FMIN;
10530         break;
10531       case ISD::SETOLE:
10532         // Converting this to a min would handle comparisons between positive
10533         // and negative zero incorrectly.
10534         if (!UnsafeFPMath &&
10535             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10536           break;
10537         Opcode = X86ISD::FMIN;
10538         break;
10539       case ISD::SETULE:
10540         // Converting this to a min would handle both negative zeros and NaNs
10541         // incorrectly, but we can swap the operands to fix both.
10542         std::swap(LHS, RHS);
10543       case ISD::SETOLT:
10544       case ISD::SETLT:
10545       case ISD::SETLE:
10546         Opcode = X86ISD::FMIN;
10547         break;
10548
10549       case ISD::SETOGE:
10550         // Converting this to a max would handle comparisons between positive
10551         // and negative zero incorrectly.
10552         if (!UnsafeFPMath &&
10553             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10554           break;
10555         Opcode = X86ISD::FMAX;
10556         break;
10557       case ISD::SETUGT:
10558         // Converting this to a max would handle NaNs incorrectly, and swapping
10559         // the operands would cause it to handle comparisons between positive
10560         // and negative zero incorrectly.
10561         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10562           if (!UnsafeFPMath &&
10563               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10564             break;
10565           std::swap(LHS, RHS);
10566         }
10567         Opcode = X86ISD::FMAX;
10568         break;
10569       case ISD::SETUGE:
10570         // Converting this to a max would handle both negative zeros and NaNs
10571         // incorrectly, but we can swap the operands to fix both.
10572         std::swap(LHS, RHS);
10573       case ISD::SETOGT:
10574       case ISD::SETGT:
10575       case ISD::SETGE:
10576         Opcode = X86ISD::FMAX;
10577         break;
10578       }
10579     // Check for x CC y ? y : x -- a min/max with reversed arms.
10580     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10581                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10582       switch (CC) {
10583       default: break;
10584       case ISD::SETOGE:
10585         // Converting this to a min would handle comparisons between positive
10586         // and negative zero incorrectly, and swapping the operands would
10587         // cause it to handle NaNs incorrectly.
10588         if (!UnsafeFPMath &&
10589             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10590           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10591             break;
10592           std::swap(LHS, RHS);
10593         }
10594         Opcode = X86ISD::FMIN;
10595         break;
10596       case ISD::SETUGT:
10597         // Converting this to a min would handle NaNs incorrectly.
10598         if (!UnsafeFPMath &&
10599             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10600           break;
10601         Opcode = X86ISD::FMIN;
10602         break;
10603       case ISD::SETUGE:
10604         // Converting this to a min would handle both negative zeros and NaNs
10605         // incorrectly, but we can swap the operands to fix both.
10606         std::swap(LHS, RHS);
10607       case ISD::SETOGT:
10608       case ISD::SETGT:
10609       case ISD::SETGE:
10610         Opcode = X86ISD::FMIN;
10611         break;
10612
10613       case ISD::SETULT:
10614         // Converting this to a max would handle NaNs incorrectly.
10615         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10616           break;
10617         Opcode = X86ISD::FMAX;
10618         break;
10619       case ISD::SETOLE:
10620         // Converting this to a max would handle comparisons between positive
10621         // and negative zero incorrectly, and swapping the operands would
10622         // cause it to handle NaNs incorrectly.
10623         if (!UnsafeFPMath &&
10624             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10625           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10626             break;
10627           std::swap(LHS, RHS);
10628         }
10629         Opcode = X86ISD::FMAX;
10630         break;
10631       case ISD::SETULE:
10632         // Converting this to a max would handle both negative zeros and NaNs
10633         // incorrectly, but we can swap the operands to fix both.
10634         std::swap(LHS, RHS);
10635       case ISD::SETOLT:
10636       case ISD::SETLT:
10637       case ISD::SETLE:
10638         Opcode = X86ISD::FMAX;
10639         break;
10640       }
10641     }
10642
10643     if (Opcode)
10644       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10645   }
10646
10647   // If this is a select between two integer constants, try to do some
10648   // optimizations.
10649   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10650     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10651       // Don't do this for crazy integer types.
10652       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10653         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10654         // so that TrueC (the true value) is larger than FalseC.
10655         bool NeedsCondInvert = false;
10656
10657         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10658             // Efficiently invertible.
10659             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10660              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10661               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10662           NeedsCondInvert = true;
10663           std::swap(TrueC, FalseC);
10664         }
10665
10666         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10667         if (FalseC->getAPIntValue() == 0 &&
10668             TrueC->getAPIntValue().isPowerOf2()) {
10669           if (NeedsCondInvert) // Invert the condition if needed.
10670             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10671                                DAG.getConstant(1, Cond.getValueType()));
10672
10673           // Zero extend the condition if needed.
10674           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10675
10676           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10677           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10678                              DAG.getConstant(ShAmt, MVT::i8));
10679         }
10680
10681         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10682         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10683           if (NeedsCondInvert) // Invert the condition if needed.
10684             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10685                                DAG.getConstant(1, Cond.getValueType()));
10686
10687           // Zero extend the condition if needed.
10688           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10689                              FalseC->getValueType(0), Cond);
10690           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10691                              SDValue(FalseC, 0));
10692         }
10693
10694         // Optimize cases that will turn into an LEA instruction.  This requires
10695         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10696         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10697           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10698           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10699
10700           bool isFastMultiplier = false;
10701           if (Diff < 10) {
10702             switch ((unsigned char)Diff) {
10703               default: break;
10704               case 1:  // result = add base, cond
10705               case 2:  // result = lea base(    , cond*2)
10706               case 3:  // result = lea base(cond, cond*2)
10707               case 4:  // result = lea base(    , cond*4)
10708               case 5:  // result = lea base(cond, cond*4)
10709               case 8:  // result = lea base(    , cond*8)
10710               case 9:  // result = lea base(cond, cond*8)
10711                 isFastMultiplier = true;
10712                 break;
10713             }
10714           }
10715
10716           if (isFastMultiplier) {
10717             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10718             if (NeedsCondInvert) // Invert the condition if needed.
10719               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10720                                  DAG.getConstant(1, Cond.getValueType()));
10721
10722             // Zero extend the condition if needed.
10723             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10724                                Cond);
10725             // Scale the condition by the difference.
10726             if (Diff != 1)
10727               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10728                                  DAG.getConstant(Diff, Cond.getValueType()));
10729
10730             // Add the base if non-zero.
10731             if (FalseC->getAPIntValue() != 0)
10732               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10733                                  SDValue(FalseC, 0));
10734             return Cond;
10735           }
10736         }
10737       }
10738   }
10739
10740   return SDValue();
10741 }
10742
10743 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10744 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10745                                   TargetLowering::DAGCombinerInfo &DCI) {
10746   DebugLoc DL = N->getDebugLoc();
10747
10748   // If the flag operand isn't dead, don't touch this CMOV.
10749   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10750     return SDValue();
10751
10752   // If this is a select between two integer constants, try to do some
10753   // optimizations.  Note that the operands are ordered the opposite of SELECT
10754   // operands.
10755   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10756     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10757       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10758       // larger than FalseC (the false value).
10759       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10760
10761       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10762         CC = X86::GetOppositeBranchCondition(CC);
10763         std::swap(TrueC, FalseC);
10764       }
10765
10766       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10767       // This is efficient for any integer data type (including i8/i16) and
10768       // shift amount.
10769       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10770         SDValue Cond = N->getOperand(3);
10771         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10772                            DAG.getConstant(CC, MVT::i8), Cond);
10773
10774         // Zero extend the condition if needed.
10775         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10776
10777         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10778         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10779                            DAG.getConstant(ShAmt, MVT::i8));
10780         if (N->getNumValues() == 2)  // Dead flag value?
10781           return DCI.CombineTo(N, Cond, SDValue());
10782         return Cond;
10783       }
10784
10785       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10786       // for any integer data type, including i8/i16.
10787       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10788         SDValue Cond = N->getOperand(3);
10789         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10790                            DAG.getConstant(CC, MVT::i8), Cond);
10791
10792         // Zero extend the condition if needed.
10793         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10794                            FalseC->getValueType(0), Cond);
10795         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10796                            SDValue(FalseC, 0));
10797
10798         if (N->getNumValues() == 2)  // Dead flag value?
10799           return DCI.CombineTo(N, Cond, SDValue());
10800         return Cond;
10801       }
10802
10803       // Optimize cases that will turn into an LEA instruction.  This requires
10804       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10805       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10806         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10807         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10808
10809         bool isFastMultiplier = false;
10810         if (Diff < 10) {
10811           switch ((unsigned char)Diff) {
10812           default: break;
10813           case 1:  // result = add base, cond
10814           case 2:  // result = lea base(    , cond*2)
10815           case 3:  // result = lea base(cond, cond*2)
10816           case 4:  // result = lea base(    , cond*4)
10817           case 5:  // result = lea base(cond, cond*4)
10818           case 8:  // result = lea base(    , cond*8)
10819           case 9:  // result = lea base(cond, cond*8)
10820             isFastMultiplier = true;
10821             break;
10822           }
10823         }
10824
10825         if (isFastMultiplier) {
10826           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10827           SDValue Cond = N->getOperand(3);
10828           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10829                              DAG.getConstant(CC, MVT::i8), Cond);
10830           // Zero extend the condition if needed.
10831           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10832                              Cond);
10833           // Scale the condition by the difference.
10834           if (Diff != 1)
10835             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10836                                DAG.getConstant(Diff, Cond.getValueType()));
10837
10838           // Add the base if non-zero.
10839           if (FalseC->getAPIntValue() != 0)
10840             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10841                                SDValue(FalseC, 0));
10842           if (N->getNumValues() == 2)  // Dead flag value?
10843             return DCI.CombineTo(N, Cond, SDValue());
10844           return Cond;
10845         }
10846       }
10847     }
10848   }
10849   return SDValue();
10850 }
10851
10852
10853 /// PerformMulCombine - Optimize a single multiply with constant into two
10854 /// in order to implement it with two cheaper instructions, e.g.
10855 /// LEA + SHL, LEA + LEA.
10856 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10857                                  TargetLowering::DAGCombinerInfo &DCI) {
10858   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10859     return SDValue();
10860
10861   EVT VT = N->getValueType(0);
10862   if (VT != MVT::i64)
10863     return SDValue();
10864
10865   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10866   if (!C)
10867     return SDValue();
10868   uint64_t MulAmt = C->getZExtValue();
10869   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10870     return SDValue();
10871
10872   uint64_t MulAmt1 = 0;
10873   uint64_t MulAmt2 = 0;
10874   if ((MulAmt % 9) == 0) {
10875     MulAmt1 = 9;
10876     MulAmt2 = MulAmt / 9;
10877   } else if ((MulAmt % 5) == 0) {
10878     MulAmt1 = 5;
10879     MulAmt2 = MulAmt / 5;
10880   } else if ((MulAmt % 3) == 0) {
10881     MulAmt1 = 3;
10882     MulAmt2 = MulAmt / 3;
10883   }
10884   if (MulAmt2 &&
10885       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10886     DebugLoc DL = N->getDebugLoc();
10887
10888     if (isPowerOf2_64(MulAmt2) &&
10889         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10890       // If second multiplifer is pow2, issue it first. We want the multiply by
10891       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10892       // is an add.
10893       std::swap(MulAmt1, MulAmt2);
10894
10895     SDValue NewMul;
10896     if (isPowerOf2_64(MulAmt1))
10897       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10898                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10899     else
10900       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10901                            DAG.getConstant(MulAmt1, VT));
10902
10903     if (isPowerOf2_64(MulAmt2))
10904       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10905                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10906     else
10907       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10908                            DAG.getConstant(MulAmt2, VT));
10909
10910     // Do not add new nodes to DAG combiner worklist.
10911     DCI.CombineTo(N, NewMul, false);
10912   }
10913   return SDValue();
10914 }
10915
10916 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10917   SDValue N0 = N->getOperand(0);
10918   SDValue N1 = N->getOperand(1);
10919   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10920   EVT VT = N0.getValueType();
10921
10922   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10923   // since the result of setcc_c is all zero's or all ones.
10924   if (N1C && N0.getOpcode() == ISD::AND &&
10925       N0.getOperand(1).getOpcode() == ISD::Constant) {
10926     SDValue N00 = N0.getOperand(0);
10927     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10928         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10929           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10930          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10931       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10932       APInt ShAmt = N1C->getAPIntValue();
10933       Mask = Mask.shl(ShAmt);
10934       if (Mask != 0)
10935         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10936                            N00, DAG.getConstant(Mask, VT));
10937     }
10938   }
10939
10940   return SDValue();
10941 }
10942
10943 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10944 ///                       when possible.
10945 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10946                                    const X86Subtarget *Subtarget) {
10947   EVT VT = N->getValueType(0);
10948   if (!VT.isVector() && VT.isInteger() &&
10949       N->getOpcode() == ISD::SHL)
10950     return PerformSHLCombine(N, DAG);
10951
10952   // On X86 with SSE2 support, we can transform this to a vector shift if
10953   // all elements are shifted by the same amount.  We can't do this in legalize
10954   // because the a constant vector is typically transformed to a constant pool
10955   // so we have no knowledge of the shift amount.
10956   if (!Subtarget->hasSSE2())
10957     return SDValue();
10958
10959   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10960     return SDValue();
10961
10962   SDValue ShAmtOp = N->getOperand(1);
10963   EVT EltVT = VT.getVectorElementType();
10964   DebugLoc DL = N->getDebugLoc();
10965   SDValue BaseShAmt = SDValue();
10966   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10967     unsigned NumElts = VT.getVectorNumElements();
10968     unsigned i = 0;
10969     for (; i != NumElts; ++i) {
10970       SDValue Arg = ShAmtOp.getOperand(i);
10971       if (Arg.getOpcode() == ISD::UNDEF) continue;
10972       BaseShAmt = Arg;
10973       break;
10974     }
10975     for (; i != NumElts; ++i) {
10976       SDValue Arg = ShAmtOp.getOperand(i);
10977       if (Arg.getOpcode() == ISD::UNDEF) continue;
10978       if (Arg != BaseShAmt) {
10979         return SDValue();
10980       }
10981     }
10982   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10983              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10984     SDValue InVec = ShAmtOp.getOperand(0);
10985     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10986       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10987       unsigned i = 0;
10988       for (; i != NumElts; ++i) {
10989         SDValue Arg = InVec.getOperand(i);
10990         if (Arg.getOpcode() == ISD::UNDEF) continue;
10991         BaseShAmt = Arg;
10992         break;
10993       }
10994     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10995        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10996          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10997          if (C->getZExtValue() == SplatIdx)
10998            BaseShAmt = InVec.getOperand(1);
10999        }
11000     }
11001     if (BaseShAmt.getNode() == 0)
11002       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11003                               DAG.getIntPtrConstant(0));
11004   } else
11005     return SDValue();
11006
11007   // The shift amount is an i32.
11008   if (EltVT.bitsGT(MVT::i32))
11009     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11010   else if (EltVT.bitsLT(MVT::i32))
11011     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11012
11013   // The shift amount is identical so we can do a vector shift.
11014   SDValue  ValOp = N->getOperand(0);
11015   switch (N->getOpcode()) {
11016   default:
11017     llvm_unreachable("Unknown shift opcode!");
11018     break;
11019   case ISD::SHL:
11020     if (VT == MVT::v2i64)
11021       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11022                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11023                          ValOp, BaseShAmt);
11024     if (VT == MVT::v4i32)
11025       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11026                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11027                          ValOp, BaseShAmt);
11028     if (VT == MVT::v8i16)
11029       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11030                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11031                          ValOp, BaseShAmt);
11032     break;
11033   case ISD::SRA:
11034     if (VT == MVT::v4i32)
11035       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11036                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11037                          ValOp, BaseShAmt);
11038     if (VT == MVT::v8i16)
11039       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11040                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11041                          ValOp, BaseShAmt);
11042     break;
11043   case ISD::SRL:
11044     if (VT == MVT::v2i64)
11045       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11046                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11047                          ValOp, BaseShAmt);
11048     if (VT == MVT::v4i32)
11049       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11050                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11051                          ValOp, BaseShAmt);
11052     if (VT ==  MVT::v8i16)
11053       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11054                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11055                          ValOp, BaseShAmt);
11056     break;
11057   }
11058   return SDValue();
11059 }
11060
11061
11062 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11063                                  TargetLowering::DAGCombinerInfo &DCI,
11064                                  const X86Subtarget *Subtarget) {
11065   if (DCI.isBeforeLegalizeOps())
11066     return SDValue();
11067   
11068   // Want to form PANDN nodes, in the hopes of then easily combining them with
11069   // OR and AND nodes to form PBLEND/PSIGN.
11070   EVT VT = N->getValueType(0);
11071   if (VT != MVT::v2i64)
11072     return SDValue();
11073   
11074   SDValue N0 = N->getOperand(0);
11075   SDValue N1 = N->getOperand(1);
11076   DebugLoc DL = N->getDebugLoc();
11077   
11078   // Check LHS for vnot
11079   if (N0.getOpcode() == ISD::XOR && 
11080       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11081     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11082
11083   // Check RHS for vnot
11084   if (N1.getOpcode() == ISD::XOR &&
11085       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11086     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11087   
11088   return SDValue();
11089 }
11090
11091 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11092                                 TargetLowering::DAGCombinerInfo &DCI,
11093                                 const X86Subtarget *Subtarget) {
11094   if (DCI.isBeforeLegalizeOps())
11095     return SDValue();
11096
11097   EVT VT = N->getValueType(0);
11098   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11099     return SDValue();
11100
11101   SDValue N0 = N->getOperand(0);
11102   SDValue N1 = N->getOperand(1);
11103   
11104   // look for psign/blend
11105   if (Subtarget->hasSSSE3()) {
11106     if (VT == MVT::v2i64) {
11107       // Canonicalize pandn to RHS
11108       if (N0.getOpcode() == X86ISD::PANDN)
11109         std::swap(N0, N1);
11110       // or (and (m, x), (pandn m, y))
11111       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11112         SDValue Mask = N1.getOperand(0);
11113         SDValue X    = N1.getOperand(1);
11114         SDValue Y;
11115         if (N0.getOperand(0) == Mask)
11116           Y = N0.getOperand(1);
11117         if (N0.getOperand(1) == Mask)
11118           Y = N0.getOperand(0);
11119         
11120         // Check to see if the mask appeared in both the AND and PANDN and
11121         if (!Y.getNode())
11122           return SDValue();
11123         
11124         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11125         if (Mask.getOpcode() != ISD::BITCAST ||
11126             X.getOpcode() != ISD::BITCAST ||
11127             Y.getOpcode() != ISD::BITCAST)
11128           return SDValue();
11129         
11130         // Look through mask bitcast.
11131         Mask = Mask.getOperand(0);
11132         EVT MaskVT = Mask.getValueType();
11133
11134         // Validate that the Mask operand is a vector sra node.  The sra node
11135         // will be an intrinsic.
11136         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11137           return SDValue();
11138         
11139         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11140         // there is no psrai.b
11141         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11142         case Intrinsic::x86_sse2_psrai_w:
11143         case Intrinsic::x86_sse2_psrai_d:
11144           break;
11145         default: return SDValue();
11146         }
11147         
11148         // Check that the SRA is all signbits.
11149         SDValue SraC = Mask.getOperand(2);
11150         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11151         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11152         if ((SraAmt + 1) != EltBits)
11153           return SDValue();
11154         
11155         DebugLoc DL = N->getDebugLoc();
11156
11157         // Now we know we at least have a plendvb with the mask val.  See if
11158         // we can form a psignb/w/d.
11159         // psign = x.type == y.type == mask.type && y = sub(0, x);
11160         X = X.getOperand(0);
11161         Y = Y.getOperand(0);
11162         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11163             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11164             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11165           unsigned Opc = 0;
11166           switch (EltBits) {
11167           case 8: Opc = X86ISD::PSIGNB; break;
11168           case 16: Opc = X86ISD::PSIGNW; break;
11169           case 32: Opc = X86ISD::PSIGND; break;
11170           default: break;
11171           }
11172           if (Opc) {
11173             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11174             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11175           }
11176         }
11177         // PBLENDVB only available on SSE 4.1
11178         if (!Subtarget->hasSSE41())
11179           return SDValue();
11180         
11181         unsigned IID = Intrinsic::x86_sse41_pblendvb;
11182         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11183         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11184         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11185         Mask = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::v16i8,
11186                            DAG.getConstant(IID, MVT::i32), X, Y, Mask);
11187         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11188       }
11189     }
11190   }
11191   
11192   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11193   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11194     std::swap(N0, N1);
11195   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11196     return SDValue();
11197   if (!N0.hasOneUse() || !N1.hasOneUse())
11198     return SDValue();
11199
11200   SDValue ShAmt0 = N0.getOperand(1);
11201   if (ShAmt0.getValueType() != MVT::i8)
11202     return SDValue();
11203   SDValue ShAmt1 = N1.getOperand(1);
11204   if (ShAmt1.getValueType() != MVT::i8)
11205     return SDValue();
11206   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11207     ShAmt0 = ShAmt0.getOperand(0);
11208   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11209     ShAmt1 = ShAmt1.getOperand(0);
11210
11211   DebugLoc DL = N->getDebugLoc();
11212   unsigned Opc = X86ISD::SHLD;
11213   SDValue Op0 = N0.getOperand(0);
11214   SDValue Op1 = N1.getOperand(0);
11215   if (ShAmt0.getOpcode() == ISD::SUB) {
11216     Opc = X86ISD::SHRD;
11217     std::swap(Op0, Op1);
11218     std::swap(ShAmt0, ShAmt1);
11219   }
11220
11221   unsigned Bits = VT.getSizeInBits();
11222   if (ShAmt1.getOpcode() == ISD::SUB) {
11223     SDValue Sum = ShAmt1.getOperand(0);
11224     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11225       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11226       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11227         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11228       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11229         return DAG.getNode(Opc, DL, VT,
11230                            Op0, Op1,
11231                            DAG.getNode(ISD::TRUNCATE, DL,
11232                                        MVT::i8, ShAmt0));
11233     }
11234   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11235     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11236     if (ShAmt0C &&
11237         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11238       return DAG.getNode(Opc, DL, VT,
11239                          N0.getOperand(0), N1.getOperand(0),
11240                          DAG.getNode(ISD::TRUNCATE, DL,
11241                                        MVT::i8, ShAmt0));
11242   }
11243   
11244   return SDValue();
11245 }
11246
11247 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11248 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11249                                    const X86Subtarget *Subtarget) {
11250   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11251   // the FP state in cases where an emms may be missing.
11252   // A preferable solution to the general problem is to figure out the right
11253   // places to insert EMMS.  This qualifies as a quick hack.
11254
11255   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11256   StoreSDNode *St = cast<StoreSDNode>(N);
11257   EVT VT = St->getValue().getValueType();
11258   if (VT.getSizeInBits() != 64)
11259     return SDValue();
11260
11261   const Function *F = DAG.getMachineFunction().getFunction();
11262   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11263   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11264     && Subtarget->hasSSE2();
11265   if ((VT.isVector() ||
11266        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11267       isa<LoadSDNode>(St->getValue()) &&
11268       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11269       St->getChain().hasOneUse() && !St->isVolatile()) {
11270     SDNode* LdVal = St->getValue().getNode();
11271     LoadSDNode *Ld = 0;
11272     int TokenFactorIndex = -1;
11273     SmallVector<SDValue, 8> Ops;
11274     SDNode* ChainVal = St->getChain().getNode();
11275     // Must be a store of a load.  We currently handle two cases:  the load
11276     // is a direct child, and it's under an intervening TokenFactor.  It is
11277     // possible to dig deeper under nested TokenFactors.
11278     if (ChainVal == LdVal)
11279       Ld = cast<LoadSDNode>(St->getChain());
11280     else if (St->getValue().hasOneUse() &&
11281              ChainVal->getOpcode() == ISD::TokenFactor) {
11282       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11283         if (ChainVal->getOperand(i).getNode() == LdVal) {
11284           TokenFactorIndex = i;
11285           Ld = cast<LoadSDNode>(St->getValue());
11286         } else
11287           Ops.push_back(ChainVal->getOperand(i));
11288       }
11289     }
11290
11291     if (!Ld || !ISD::isNormalLoad(Ld))
11292       return SDValue();
11293
11294     // If this is not the MMX case, i.e. we are just turning i64 load/store
11295     // into f64 load/store, avoid the transformation if there are multiple
11296     // uses of the loaded value.
11297     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11298       return SDValue();
11299
11300     DebugLoc LdDL = Ld->getDebugLoc();
11301     DebugLoc StDL = N->getDebugLoc();
11302     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11303     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11304     // pair instead.
11305     if (Subtarget->is64Bit() || F64IsLegal) {
11306       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11307       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11308                                   Ld->getPointerInfo(), Ld->isVolatile(),
11309                                   Ld->isNonTemporal(), Ld->getAlignment());
11310       SDValue NewChain = NewLd.getValue(1);
11311       if (TokenFactorIndex != -1) {
11312         Ops.push_back(NewChain);
11313         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11314                                Ops.size());
11315       }
11316       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11317                           St->getPointerInfo(),
11318                           St->isVolatile(), St->isNonTemporal(),
11319                           St->getAlignment());
11320     }
11321
11322     // Otherwise, lower to two pairs of 32-bit loads / stores.
11323     SDValue LoAddr = Ld->getBasePtr();
11324     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11325                                  DAG.getConstant(4, MVT::i32));
11326
11327     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11328                                Ld->getPointerInfo(),
11329                                Ld->isVolatile(), Ld->isNonTemporal(),
11330                                Ld->getAlignment());
11331     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11332                                Ld->getPointerInfo().getWithOffset(4),
11333                                Ld->isVolatile(), Ld->isNonTemporal(),
11334                                MinAlign(Ld->getAlignment(), 4));
11335
11336     SDValue NewChain = LoLd.getValue(1);
11337     if (TokenFactorIndex != -1) {
11338       Ops.push_back(LoLd);
11339       Ops.push_back(HiLd);
11340       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11341                              Ops.size());
11342     }
11343
11344     LoAddr = St->getBasePtr();
11345     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11346                          DAG.getConstant(4, MVT::i32));
11347
11348     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11349                                 St->getPointerInfo(),
11350                                 St->isVolatile(), St->isNonTemporal(),
11351                                 St->getAlignment());
11352     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11353                                 St->getPointerInfo().getWithOffset(4),
11354                                 St->isVolatile(),
11355                                 St->isNonTemporal(),
11356                                 MinAlign(St->getAlignment(), 4));
11357     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11358   }
11359   return SDValue();
11360 }
11361
11362 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11363 /// X86ISD::FXOR nodes.
11364 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11365   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11366   // F[X]OR(0.0, x) -> x
11367   // F[X]OR(x, 0.0) -> x
11368   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11369     if (C->getValueAPF().isPosZero())
11370       return N->getOperand(1);
11371   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11372     if (C->getValueAPF().isPosZero())
11373       return N->getOperand(0);
11374   return SDValue();
11375 }
11376
11377 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11378 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11379   // FAND(0.0, x) -> 0.0
11380   // FAND(x, 0.0) -> 0.0
11381   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11382     if (C->getValueAPF().isPosZero())
11383       return N->getOperand(0);
11384   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11385     if (C->getValueAPF().isPosZero())
11386       return N->getOperand(1);
11387   return SDValue();
11388 }
11389
11390 static SDValue PerformBTCombine(SDNode *N,
11391                                 SelectionDAG &DAG,
11392                                 TargetLowering::DAGCombinerInfo &DCI) {
11393   // BT ignores high bits in the bit index operand.
11394   SDValue Op1 = N->getOperand(1);
11395   if (Op1.hasOneUse()) {
11396     unsigned BitWidth = Op1.getValueSizeInBits();
11397     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11398     APInt KnownZero, KnownOne;
11399     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11400                                           !DCI.isBeforeLegalizeOps());
11401     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11402     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11403         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11404       DCI.CommitTargetLoweringOpt(TLO);
11405   }
11406   return SDValue();
11407 }
11408
11409 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11410   SDValue Op = N->getOperand(0);
11411   if (Op.getOpcode() == ISD::BITCAST)
11412     Op = Op.getOperand(0);
11413   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11414   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11415       VT.getVectorElementType().getSizeInBits() ==
11416       OpVT.getVectorElementType().getSizeInBits()) {
11417     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11418   }
11419   return SDValue();
11420 }
11421
11422 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11423   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11424   //           (and (i32 x86isd::setcc_carry), 1)
11425   // This eliminates the zext. This transformation is necessary because
11426   // ISD::SETCC is always legalized to i8.
11427   DebugLoc dl = N->getDebugLoc();
11428   SDValue N0 = N->getOperand(0);
11429   EVT VT = N->getValueType(0);
11430   if (N0.getOpcode() == ISD::AND &&
11431       N0.hasOneUse() &&
11432       N0.getOperand(0).hasOneUse()) {
11433     SDValue N00 = N0.getOperand(0);
11434     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11435       return SDValue();
11436     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11437     if (!C || C->getZExtValue() != 1)
11438       return SDValue();
11439     return DAG.getNode(ISD::AND, dl, VT,
11440                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11441                                    N00.getOperand(0), N00.getOperand(1)),
11442                        DAG.getConstant(1, VT));
11443   }
11444
11445   return SDValue();
11446 }
11447
11448 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11449                                              DAGCombinerInfo &DCI) const {
11450   SelectionDAG &DAG = DCI.DAG;
11451   switch (N->getOpcode()) {
11452   default: break;
11453   case ISD::EXTRACT_VECTOR_ELT:
11454                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11455   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11456   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11457   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11458   case ISD::SHL:
11459   case ISD::SRA:
11460   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11461   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11462   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11463   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11464   case X86ISD::FXOR:
11465   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11466   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11467   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11468   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11469   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11470   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11471   case X86ISD::SHUFPD:
11472   case X86ISD::PALIGN:
11473   case X86ISD::PUNPCKHBW:
11474   case X86ISD::PUNPCKHWD:
11475   case X86ISD::PUNPCKHDQ:
11476   case X86ISD::PUNPCKHQDQ:
11477   case X86ISD::UNPCKHPS:
11478   case X86ISD::UNPCKHPD:
11479   case X86ISD::PUNPCKLBW:
11480   case X86ISD::PUNPCKLWD:
11481   case X86ISD::PUNPCKLDQ:
11482   case X86ISD::PUNPCKLQDQ:
11483   case X86ISD::UNPCKLPS:
11484   case X86ISD::UNPCKLPD:
11485   case X86ISD::MOVHLPS:
11486   case X86ISD::MOVLHPS:
11487   case X86ISD::PSHUFD:
11488   case X86ISD::PSHUFHW:
11489   case X86ISD::PSHUFLW:
11490   case X86ISD::MOVSS:
11491   case X86ISD::MOVSD:
11492   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11493   }
11494
11495   return SDValue();
11496 }
11497
11498 /// isTypeDesirableForOp - Return true if the target has native support for
11499 /// the specified value type and it is 'desirable' to use the type for the
11500 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11501 /// instruction encodings are longer and some i16 instructions are slow.
11502 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11503   if (!isTypeLegal(VT))
11504     return false;
11505   if (VT != MVT::i16)
11506     return true;
11507
11508   switch (Opc) {
11509   default:
11510     return true;
11511   case ISD::LOAD:
11512   case ISD::SIGN_EXTEND:
11513   case ISD::ZERO_EXTEND:
11514   case ISD::ANY_EXTEND:
11515   case ISD::SHL:
11516   case ISD::SRL:
11517   case ISD::SUB:
11518   case ISD::ADD:
11519   case ISD::MUL:
11520   case ISD::AND:
11521   case ISD::OR:
11522   case ISD::XOR:
11523     return false;
11524   }
11525 }
11526
11527 /// IsDesirableToPromoteOp - This method query the target whether it is
11528 /// beneficial for dag combiner to promote the specified node. If true, it
11529 /// should return the desired promotion type by reference.
11530 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11531   EVT VT = Op.getValueType();
11532   if (VT != MVT::i16)
11533     return false;
11534
11535   bool Promote = false;
11536   bool Commute = false;
11537   switch (Op.getOpcode()) {
11538   default: break;
11539   case ISD::LOAD: {
11540     LoadSDNode *LD = cast<LoadSDNode>(Op);
11541     // If the non-extending load has a single use and it's not live out, then it
11542     // might be folded.
11543     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11544                                                      Op.hasOneUse()*/) {
11545       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11546              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11547         // The only case where we'd want to promote LOAD (rather then it being
11548         // promoted as an operand is when it's only use is liveout.
11549         if (UI->getOpcode() != ISD::CopyToReg)
11550           return false;
11551       }
11552     }
11553     Promote = true;
11554     break;
11555   }
11556   case ISD::SIGN_EXTEND:
11557   case ISD::ZERO_EXTEND:
11558   case ISD::ANY_EXTEND:
11559     Promote = true;
11560     break;
11561   case ISD::SHL:
11562   case ISD::SRL: {
11563     SDValue N0 = Op.getOperand(0);
11564     // Look out for (store (shl (load), x)).
11565     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11566       return false;
11567     Promote = true;
11568     break;
11569   }
11570   case ISD::ADD:
11571   case ISD::MUL:
11572   case ISD::AND:
11573   case ISD::OR:
11574   case ISD::XOR:
11575     Commute = true;
11576     // fallthrough
11577   case ISD::SUB: {
11578     SDValue N0 = Op.getOperand(0);
11579     SDValue N1 = Op.getOperand(1);
11580     if (!Commute && MayFoldLoad(N1))
11581       return false;
11582     // Avoid disabling potential load folding opportunities.
11583     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11584       return false;
11585     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11586       return false;
11587     Promote = true;
11588   }
11589   }
11590
11591   PVT = MVT::i32;
11592   return Promote;
11593 }
11594
11595 //===----------------------------------------------------------------------===//
11596 //                           X86 Inline Assembly Support
11597 //===----------------------------------------------------------------------===//
11598
11599 static bool LowerToBSwap(CallInst *CI) {
11600   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11601   // we will turn this bswap into something that will be lowered to logical ops
11602   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11603   // so don't worry about this.
11604
11605   // Verify this is a simple bswap.
11606   if (CI->getNumArgOperands() != 1 ||
11607       CI->getType() != CI->getArgOperand(0)->getType() ||
11608       !CI->getType()->isIntegerTy())
11609     return false;
11610
11611   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11612   if (!Ty || Ty->getBitWidth() % 16 != 0)
11613     return false;
11614
11615   // Okay, we can do this xform, do so now.
11616   const Type *Tys[] = { Ty };
11617   Module *M = CI->getParent()->getParent()->getParent();
11618   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11619
11620   Value *Op = CI->getArgOperand(0);
11621   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11622
11623   CI->replaceAllUsesWith(Op);
11624   CI->eraseFromParent();
11625   return true;
11626 }
11627
11628 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11629   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11630   InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11631
11632   std::string AsmStr = IA->getAsmString();
11633
11634   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11635   SmallVector<StringRef, 4> AsmPieces;
11636   SplitString(AsmStr, AsmPieces, ";\n");
11637
11638   switch (AsmPieces.size()) {
11639   default: return false;
11640   case 1:
11641     AsmStr = AsmPieces[0];
11642     AsmPieces.clear();
11643     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11644
11645     // bswap $0
11646     if (AsmPieces.size() == 2 &&
11647         (AsmPieces[0] == "bswap" ||
11648          AsmPieces[0] == "bswapq" ||
11649          AsmPieces[0] == "bswapl") &&
11650         (AsmPieces[1] == "$0" ||
11651          AsmPieces[1] == "${0:q}")) {
11652       // No need to check constraints, nothing other than the equivalent of
11653       // "=r,0" would be valid here.
11654       return LowerToBSwap(CI);
11655     }
11656     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11657     if (CI->getType()->isIntegerTy(16) &&
11658         AsmPieces.size() == 3 &&
11659         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11660         AsmPieces[1] == "$$8," &&
11661         AsmPieces[2] == "${0:w}" &&
11662         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11663       AsmPieces.clear();
11664       const std::string &Constraints = IA->getConstraintString();
11665       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11666       std::sort(AsmPieces.begin(), AsmPieces.end());
11667       if (AsmPieces.size() == 4 &&
11668           AsmPieces[0] == "~{cc}" &&
11669           AsmPieces[1] == "~{dirflag}" &&
11670           AsmPieces[2] == "~{flags}" &&
11671           AsmPieces[3] == "~{fpsr}") {
11672         return LowerToBSwap(CI);
11673       }
11674     }
11675     break;
11676   case 3:
11677     if (CI->getType()->isIntegerTy(32) &&
11678         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11679       SmallVector<StringRef, 4> Words;
11680       SplitString(AsmPieces[0], Words, " \t,");
11681       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11682           Words[2] == "${0:w}") {
11683         Words.clear();
11684         SplitString(AsmPieces[1], Words, " \t,");
11685         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11686             Words[2] == "$0") {
11687           Words.clear();
11688           SplitString(AsmPieces[2], Words, " \t,");
11689           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11690               Words[2] == "${0:w}") {
11691             AsmPieces.clear();
11692             const std::string &Constraints = IA->getConstraintString();
11693             SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11694             std::sort(AsmPieces.begin(), AsmPieces.end());
11695             if (AsmPieces.size() == 4 &&
11696                 AsmPieces[0] == "~{cc}" &&
11697                 AsmPieces[1] == "~{dirflag}" &&
11698                 AsmPieces[2] == "~{flags}" &&
11699                 AsmPieces[3] == "~{fpsr}") {
11700               return LowerToBSwap(CI);
11701             }
11702           }
11703         }
11704       }
11705     }
11706     if (CI->getType()->isIntegerTy(64) &&
11707         Constraints.size() >= 2 &&
11708         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11709         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11710       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11711       SmallVector<StringRef, 4> Words;
11712       SplitString(AsmPieces[0], Words, " \t");
11713       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11714         Words.clear();
11715         SplitString(AsmPieces[1], Words, " \t");
11716         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11717           Words.clear();
11718           SplitString(AsmPieces[2], Words, " \t,");
11719           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11720               Words[2] == "%edx") {
11721             return LowerToBSwap(CI);
11722           }
11723         }
11724       }
11725     }
11726     break;
11727   }
11728   return false;
11729 }
11730
11731
11732
11733 /// getConstraintType - Given a constraint letter, return the type of
11734 /// constraint it is for this target.
11735 X86TargetLowering::ConstraintType
11736 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11737   if (Constraint.size() == 1) {
11738     switch (Constraint[0]) {
11739     case 'R':
11740     case 'q':
11741     case 'Q':
11742     case 'f':
11743     case 't':
11744     case 'u':
11745     case 'y':
11746     case 'x':
11747     case 'Y':
11748       return C_RegisterClass;
11749     case 'a':
11750     case 'b':
11751     case 'c':
11752     case 'd':
11753     case 'S':
11754     case 'D':
11755     case 'A':
11756       return C_Register;
11757     case 'I':
11758     case 'J':
11759     case 'K':
11760     case 'L':
11761     case 'M':
11762     case 'N':
11763     case 'G':
11764     case 'C':
11765     case 'e':
11766     case 'Z':
11767       return C_Other;
11768     default:
11769       break;
11770     }
11771   }
11772   return TargetLowering::getConstraintType(Constraint);
11773 }
11774
11775 /// Examine constraint type and operand type and determine a weight value.
11776 /// This object must already have been set up with the operand type
11777 /// and the current alternative constraint selected.
11778 TargetLowering::ConstraintWeight
11779   X86TargetLowering::getSingleConstraintMatchWeight(
11780     AsmOperandInfo &info, const char *constraint) const {
11781   ConstraintWeight weight = CW_Invalid;
11782   Value *CallOperandVal = info.CallOperandVal;
11783     // If we don't have a value, we can't do a match,
11784     // but allow it at the lowest weight.
11785   if (CallOperandVal == NULL)
11786     return CW_Default;
11787   const Type *type = CallOperandVal->getType();
11788   // Look at the constraint type.
11789   switch (*constraint) {
11790   default:
11791     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11792   case 'R':
11793   case 'q':
11794   case 'Q':
11795   case 'a':
11796   case 'b':
11797   case 'c':
11798   case 'd':
11799   case 'S':
11800   case 'D':
11801   case 'A':
11802     if (CallOperandVal->getType()->isIntegerTy())
11803       weight = CW_SpecificReg;
11804     break;
11805   case 'f':
11806   case 't':
11807   case 'u':
11808       if (type->isFloatingPointTy())
11809         weight = CW_SpecificReg;
11810       break;
11811   case 'y':
11812       if (type->isX86_MMXTy() && !DisableMMX && Subtarget->hasMMX())
11813         weight = CW_SpecificReg;
11814       break;
11815   case 'x':
11816   case 'Y':
11817     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11818       weight = CW_Register;
11819     break;
11820   case 'I':
11821     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11822       if (C->getZExtValue() <= 31)
11823         weight = CW_Constant;
11824     }
11825     break;
11826   case 'J':
11827     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11828       if (C->getZExtValue() <= 63)
11829         weight = CW_Constant;
11830     }
11831     break;
11832   case 'K':
11833     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11834       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11835         weight = CW_Constant;
11836     }
11837     break;
11838   case 'L':
11839     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11840       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11841         weight = CW_Constant;
11842     }
11843     break;
11844   case 'M':
11845     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11846       if (C->getZExtValue() <= 3)
11847         weight = CW_Constant;
11848     }
11849     break;
11850   case 'N':
11851     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11852       if (C->getZExtValue() <= 0xff)
11853         weight = CW_Constant;
11854     }
11855     break;
11856   case 'G':
11857   case 'C':
11858     if (dyn_cast<ConstantFP>(CallOperandVal)) {
11859       weight = CW_Constant;
11860     }
11861     break;
11862   case 'e':
11863     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11864       if ((C->getSExtValue() >= -0x80000000LL) &&
11865           (C->getSExtValue() <= 0x7fffffffLL))
11866         weight = CW_Constant;
11867     }
11868     break;
11869   case 'Z':
11870     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11871       if (C->getZExtValue() <= 0xffffffff)
11872         weight = CW_Constant;
11873     }
11874     break;
11875   }
11876   return weight;
11877 }
11878
11879 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11880 /// with another that has more specific requirements based on the type of the
11881 /// corresponding operand.
11882 const char *X86TargetLowering::
11883 LowerXConstraint(EVT ConstraintVT) const {
11884   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11885   // 'f' like normal targets.
11886   if (ConstraintVT.isFloatingPoint()) {
11887     if (Subtarget->hasXMMInt())
11888       return "Y";
11889     if (Subtarget->hasXMM())
11890       return "x";
11891   }
11892
11893   return TargetLowering::LowerXConstraint(ConstraintVT);
11894 }
11895
11896 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11897 /// vector.  If it is invalid, don't add anything to Ops.
11898 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11899                                                      char Constraint,
11900                                                      std::vector<SDValue>&Ops,
11901                                                      SelectionDAG &DAG) const {
11902   SDValue Result(0, 0);
11903
11904   switch (Constraint) {
11905   default: break;
11906   case 'I':
11907     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11908       if (C->getZExtValue() <= 31) {
11909         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11910         break;
11911       }
11912     }
11913     return;
11914   case 'J':
11915     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11916       if (C->getZExtValue() <= 63) {
11917         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11918         break;
11919       }
11920     }
11921     return;
11922   case 'K':
11923     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11924       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11925         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11926         break;
11927       }
11928     }
11929     return;
11930   case 'N':
11931     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11932       if (C->getZExtValue() <= 255) {
11933         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11934         break;
11935       }
11936     }
11937     return;
11938   case 'e': {
11939     // 32-bit signed value
11940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11941       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11942                                            C->getSExtValue())) {
11943         // Widen to 64 bits here to get it sign extended.
11944         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11945         break;
11946       }
11947     // FIXME gcc accepts some relocatable values here too, but only in certain
11948     // memory models; it's complicated.
11949     }
11950     return;
11951   }
11952   case 'Z': {
11953     // 32-bit unsigned value
11954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11955       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11956                                            C->getZExtValue())) {
11957         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11958         break;
11959       }
11960     }
11961     // FIXME gcc accepts some relocatable values here too, but only in certain
11962     // memory models; it's complicated.
11963     return;
11964   }
11965   case 'i': {
11966     // Literal immediates are always ok.
11967     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11968       // Widen to 64 bits here to get it sign extended.
11969       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11970       break;
11971     }
11972
11973     // In any sort of PIC mode addresses need to be computed at runtime by
11974     // adding in a register or some sort of table lookup.  These can't
11975     // be used as immediates.
11976     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11977       return;
11978
11979     // If we are in non-pic codegen mode, we allow the address of a global (with
11980     // an optional displacement) to be used with 'i'.
11981     GlobalAddressSDNode *GA = 0;
11982     int64_t Offset = 0;
11983
11984     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11985     while (1) {
11986       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11987         Offset += GA->getOffset();
11988         break;
11989       } else if (Op.getOpcode() == ISD::ADD) {
11990         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11991           Offset += C->getZExtValue();
11992           Op = Op.getOperand(0);
11993           continue;
11994         }
11995       } else if (Op.getOpcode() == ISD::SUB) {
11996         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11997           Offset += -C->getZExtValue();
11998           Op = Op.getOperand(0);
11999           continue;
12000         }
12001       }
12002
12003       // Otherwise, this isn't something we can handle, reject it.
12004       return;
12005     }
12006
12007     const GlobalValue *GV = GA->getGlobal();
12008     // If we require an extra load to get this address, as in PIC mode, we
12009     // can't accept it.
12010     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12011                                                         getTargetMachine())))
12012       return;
12013
12014     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12015                                         GA->getValueType(0), Offset);
12016     break;
12017   }
12018   }
12019
12020   if (Result.getNode()) {
12021     Ops.push_back(Result);
12022     return;
12023   }
12024   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12025 }
12026
12027 std::vector<unsigned> X86TargetLowering::
12028 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12029                                   EVT VT) const {
12030   if (Constraint.size() == 1) {
12031     // FIXME: not handling fp-stack yet!
12032     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12033     default: break;  // Unknown constraint letter
12034     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12035       if (Subtarget->is64Bit()) {
12036         if (VT == MVT::i32)
12037           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12038                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12039                                        X86::R10D,X86::R11D,X86::R12D,
12040                                        X86::R13D,X86::R14D,X86::R15D,
12041                                        X86::EBP, X86::ESP, 0);
12042         else if (VT == MVT::i16)
12043           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12044                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12045                                        X86::R10W,X86::R11W,X86::R12W,
12046                                        X86::R13W,X86::R14W,X86::R15W,
12047                                        X86::BP,  X86::SP, 0);
12048         else if (VT == MVT::i8)
12049           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12050                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12051                                        X86::R10B,X86::R11B,X86::R12B,
12052                                        X86::R13B,X86::R14B,X86::R15B,
12053                                        X86::BPL, X86::SPL, 0);
12054
12055         else if (VT == MVT::i64)
12056           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12057                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12058                                        X86::R10, X86::R11, X86::R12,
12059                                        X86::R13, X86::R14, X86::R15,
12060                                        X86::RBP, X86::RSP, 0);
12061
12062         break;
12063       }
12064       // 32-bit fallthrough
12065     case 'Q':   // Q_REGS
12066       if (VT == MVT::i32)
12067         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12068       else if (VT == MVT::i16)
12069         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12070       else if (VT == MVT::i8)
12071         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12072       else if (VT == MVT::i64)
12073         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12074       break;
12075     }
12076   }
12077
12078   return std::vector<unsigned>();
12079 }
12080
12081 std::pair<unsigned, const TargetRegisterClass*>
12082 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12083                                                 EVT VT) const {
12084   // First, see if this is a constraint that directly corresponds to an LLVM
12085   // register class.
12086   if (Constraint.size() == 1) {
12087     // GCC Constraint Letters
12088     switch (Constraint[0]) {
12089     default: break;
12090     case 'r':   // GENERAL_REGS
12091     case 'l':   // INDEX_REGS
12092       if (VT == MVT::i8)
12093         return std::make_pair(0U, X86::GR8RegisterClass);
12094       if (VT == MVT::i16)
12095         return std::make_pair(0U, X86::GR16RegisterClass);
12096       if (VT == MVT::i32 || !Subtarget->is64Bit())
12097         return std::make_pair(0U, X86::GR32RegisterClass);
12098       return std::make_pair(0U, X86::GR64RegisterClass);
12099     case 'R':   // LEGACY_REGS
12100       if (VT == MVT::i8)
12101         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12102       if (VT == MVT::i16)
12103         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12104       if (VT == MVT::i32 || !Subtarget->is64Bit())
12105         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12106       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12107     case 'f':  // FP Stack registers.
12108       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12109       // value to the correct fpstack register class.
12110       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12111         return std::make_pair(0U, X86::RFP32RegisterClass);
12112       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12113         return std::make_pair(0U, X86::RFP64RegisterClass);
12114       return std::make_pair(0U, X86::RFP80RegisterClass);
12115     case 'y':   // MMX_REGS if MMX allowed.
12116       if (!Subtarget->hasMMX()) break;
12117       return std::make_pair(0U, X86::VR64RegisterClass);
12118     case 'Y':   // SSE_REGS if SSE2 allowed
12119       if (!Subtarget->hasXMMInt()) break;
12120       // FALL THROUGH.
12121     case 'x':   // SSE_REGS if SSE1 allowed
12122       if (!Subtarget->hasXMM()) break;
12123
12124       switch (VT.getSimpleVT().SimpleTy) {
12125       default: break;
12126       // Scalar SSE types.
12127       case MVT::f32:
12128       case MVT::i32:
12129         return std::make_pair(0U, X86::FR32RegisterClass);
12130       case MVT::f64:
12131       case MVT::i64:
12132         return std::make_pair(0U, X86::FR64RegisterClass);
12133       // Vector types.
12134       case MVT::v16i8:
12135       case MVT::v8i16:
12136       case MVT::v4i32:
12137       case MVT::v2i64:
12138       case MVT::v4f32:
12139       case MVT::v2f64:
12140         return std::make_pair(0U, X86::VR128RegisterClass);
12141       }
12142       break;
12143     }
12144   }
12145
12146   // Use the default implementation in TargetLowering to convert the register
12147   // constraint into a member of a register class.
12148   std::pair<unsigned, const TargetRegisterClass*> Res;
12149   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12150
12151   // Not found as a standard register?
12152   if (Res.second == 0) {
12153     // Map st(0) -> st(7) -> ST0
12154     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12155         tolower(Constraint[1]) == 's' &&
12156         tolower(Constraint[2]) == 't' &&
12157         Constraint[3] == '(' &&
12158         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12159         Constraint[5] == ')' &&
12160         Constraint[6] == '}') {
12161
12162       Res.first = X86::ST0+Constraint[4]-'0';
12163       Res.second = X86::RFP80RegisterClass;
12164       return Res;
12165     }
12166
12167     // GCC allows "st(0)" to be called just plain "st".
12168     if (StringRef("{st}").equals_lower(Constraint)) {
12169       Res.first = X86::ST0;
12170       Res.second = X86::RFP80RegisterClass;
12171       return Res;
12172     }
12173
12174     // flags -> EFLAGS
12175     if (StringRef("{flags}").equals_lower(Constraint)) {
12176       Res.first = X86::EFLAGS;
12177       Res.second = X86::CCRRegisterClass;
12178       return Res;
12179     }
12180
12181     // 'A' means EAX + EDX.
12182     if (Constraint == "A") {
12183       Res.first = X86::EAX;
12184       Res.second = X86::GR32_ADRegisterClass;
12185       return Res;
12186     }
12187     return Res;
12188   }
12189
12190   // Otherwise, check to see if this is a register class of the wrong value
12191   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12192   // turn into {ax},{dx}.
12193   if (Res.second->hasType(VT))
12194     return Res;   // Correct type already, nothing to do.
12195
12196   // All of the single-register GCC register classes map their values onto
12197   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12198   // really want an 8-bit or 32-bit register, map to the appropriate register
12199   // class and return the appropriate register.
12200   if (Res.second == X86::GR16RegisterClass) {
12201     if (VT == MVT::i8) {
12202       unsigned DestReg = 0;
12203       switch (Res.first) {
12204       default: break;
12205       case X86::AX: DestReg = X86::AL; break;
12206       case X86::DX: DestReg = X86::DL; break;
12207       case X86::CX: DestReg = X86::CL; break;
12208       case X86::BX: DestReg = X86::BL; break;
12209       }
12210       if (DestReg) {
12211         Res.first = DestReg;
12212         Res.second = X86::GR8RegisterClass;
12213       }
12214     } else if (VT == MVT::i32) {
12215       unsigned DestReg = 0;
12216       switch (Res.first) {
12217       default: break;
12218       case X86::AX: DestReg = X86::EAX; break;
12219       case X86::DX: DestReg = X86::EDX; break;
12220       case X86::CX: DestReg = X86::ECX; break;
12221       case X86::BX: DestReg = X86::EBX; break;
12222       case X86::SI: DestReg = X86::ESI; break;
12223       case X86::DI: DestReg = X86::EDI; break;
12224       case X86::BP: DestReg = X86::EBP; break;
12225       case X86::SP: DestReg = X86::ESP; break;
12226       }
12227       if (DestReg) {
12228         Res.first = DestReg;
12229         Res.second = X86::GR32RegisterClass;
12230       }
12231     } else if (VT == MVT::i64) {
12232       unsigned DestReg = 0;
12233       switch (Res.first) {
12234       default: break;
12235       case X86::AX: DestReg = X86::RAX; break;
12236       case X86::DX: DestReg = X86::RDX; break;
12237       case X86::CX: DestReg = X86::RCX; break;
12238       case X86::BX: DestReg = X86::RBX; break;
12239       case X86::SI: DestReg = X86::RSI; break;
12240       case X86::DI: DestReg = X86::RDI; break;
12241       case X86::BP: DestReg = X86::RBP; break;
12242       case X86::SP: DestReg = X86::RSP; break;
12243       }
12244       if (DestReg) {
12245         Res.first = DestReg;
12246         Res.second = X86::GR64RegisterClass;
12247       }
12248     }
12249   } else if (Res.second == X86::FR32RegisterClass ||
12250              Res.second == X86::FR64RegisterClass ||
12251              Res.second == X86::VR128RegisterClass) {
12252     // Handle references to XMM physical registers that got mapped into the
12253     // wrong class.  This can happen with constraints like {xmm0} where the
12254     // target independent register mapper will just pick the first match it can
12255     // find, ignoring the required type.
12256     if (VT == MVT::f32)
12257       Res.second = X86::FR32RegisterClass;
12258     else if (VT == MVT::f64)
12259       Res.second = X86::FR64RegisterClass;
12260     else if (X86::VR128RegisterClass->hasType(VT))
12261       Res.second = X86::VR128RegisterClass;
12262   }
12263
12264   return Res;
12265 }