[AVX] Add INSERT_SUBVECTOR and support it on x86. This provides a
[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/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
64
65   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
66
67   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
68     if (is64Bit)
69       return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   }
72
73   if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
74     if (is64Bit)
75       return new X8664_ELFTargetObjectFile(TM);
76     return new X8632_ELFTargetObjectFile(TM);
77   }
78   if (TM.getSubtarget<X86Subtarget>().isTargetCOFF())
79     return new TargetLoweringObjectFileCOFF();
80   llvm_unreachable("unknown subtarget type");
81 }
82
83 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
84   : TargetLowering(TM, createTLOF(TM)) {
85   Subtarget = &TM.getSubtarget<X86Subtarget>();
86   X86ScalarSSEf64 = Subtarget->hasXMMInt();
87   X86ScalarSSEf32 = Subtarget->hasXMM();
88   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89
90   RegInfo = TM.getRegisterInfo();
91   TD = getTargetData();
92
93   // Set up the TargetLowering object.
94   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
95
96   // X86 is weird, it always uses i8 for shift amounts and setcc results.
97   setShiftAmountType(MVT::i8);
98   setBooleanContents(ZeroOrOneBooleanContent);
99   setSchedulingPreference(Sched::RegPressure);
100   setStackPointerRegisterToSaveRestore(X86StackPtr);
101
102   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
103     // Setup Windows compiler runtime calls.
104     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
105     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
106     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
107     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
108     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
109     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
110     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
111     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
112   }
113
114   if (Subtarget->isTargetDarwin()) {
115     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
116     setUseUnderscoreSetJmp(false);
117     setUseUnderscoreLongJmp(false);
118   } else if (Subtarget->isTargetMingw()) {
119     // MS runtime is weird: it exports _setjmp, but longjmp!
120     setUseUnderscoreSetJmp(true);
121     setUseUnderscoreLongJmp(false);
122   } else {
123     setUseUnderscoreSetJmp(true);
124     setUseUnderscoreLongJmp(true);
125   }
126
127   // Set up the register classes.
128   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
129   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
130   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
131   if (Subtarget->is64Bit())
132     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
133
134   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
135
136   // We don't accept any truncstore of integer registers.
137   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
138   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
139   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
140   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
141   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
142   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
143
144   // SETOEQ and SETUNE require checking two conditions.
145   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
146   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
147   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
148   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
149   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
150   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
151
152   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
153   // operation.
154   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
155   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
156   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
157
158   if (Subtarget->is64Bit()) {
159     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
160     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
161   } else if (!UseSoftFloat) {
162     // We have an algorithm for SSE2->double, and we turn this into a
163     // 64-bit FILD followed by conditional FADD for other targets.
164     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
165     // We have an algorithm for SSE2, and we turn this into a 64-bit
166     // FILD for other targets.
167     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
168   }
169
170   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
171   // this operation.
172   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
173   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
174
175   if (!UseSoftFloat) {
176     // SSE has no i16 to fp conversion, only i32
177     if (X86ScalarSSEf32) {
178       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
179       // f32 and f64 cases are Legal, f80 case is not
180       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
181     } else {
182       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
183       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
184     }
185   } else {
186     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
187     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
188   }
189
190   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
191   // are Legal, f80 is custom lowered.
192   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
193   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
194
195   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
198   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
199
200   if (X86ScalarSSEf32) {
201     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
202     // f32 and f64 cases are Legal, f80 case is not
203     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
204   } else {
205     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
206     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
207   }
208
209   // Handle FP_TO_UINT by promoting the destination to a larger signed
210   // conversion.
211   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
212   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
213   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
214
215   if (Subtarget->is64Bit()) {
216     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
217     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
218   } else if (!UseSoftFloat) {
219     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
220       // Expand FP_TO_UINT into a select.
221       // FIXME: We would like to use a Custom expander here eventually to do
222       // the optimal thing for SSE vs. the default expansion in the legalizer.
223       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
224     else
225       // With SSE3 we can use fisttpll to convert to a signed i64; without
226       // SSE, we're stuck with a fistpll.
227       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
228   }
229
230   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
231   if (!X86ScalarSSEf64) {
232     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
233     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
234     if (Subtarget->is64Bit()) {
235       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
236       // Without SSE, i64->f64 goes through memory.
237       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
238     }
239   }
240
241   // Scalar integer divide and remainder are lowered to use operations that
242   // produce two results, to match the available instructions. This exposes
243   // the two-result form to trivial CSE, which is able to combine x/y and x%y
244   // into a single instruction.
245   //
246   // Scalar integer multiply-high is also lowered to use two-result
247   // operations, to match the available instructions. However, plain multiply
248   // (low) operations are left as Legal, as there are single-result
249   // instructions for this in x86. Using the two-result multiply instructions
250   // when both high and low results are needed must be arranged by dagcombine.
251   for (unsigned i = 0, e = 4; i != e; ++i) {
252     MVT VT = IntVTs[i];
253     setOperationAction(ISD::MULHS, VT, Expand);
254     setOperationAction(ISD::MULHU, VT, Expand);
255     setOperationAction(ISD::SDIV, VT, Expand);
256     setOperationAction(ISD::UDIV, VT, Expand);
257     setOperationAction(ISD::SREM, VT, Expand);
258     setOperationAction(ISD::UREM, VT, Expand);
259
260     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
261     setOperationAction(ISD::ADDC, VT, Custom);
262     setOperationAction(ISD::ADDE, VT, Custom);
263     setOperationAction(ISD::SUBC, VT, Custom);
264     setOperationAction(ISD::SUBE, VT, Custom);
265   }
266
267   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
268   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
269   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
270   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
271   if (Subtarget->is64Bit())
272     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
273   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
274   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
275   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
276   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
277   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
278   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
279   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
280   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
281
282   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
283   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
284   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
285   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
286   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
287   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
288   if (Subtarget->is64Bit()) {
289     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
290     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
291   }
292
293   if (Subtarget->hasPOPCNT()) {
294     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
295   } else {
296     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
297     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
298     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
299     if (Subtarget->is64Bit())
300       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
301   }
302
303   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
304   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
305
306   // These should be promoted to a larger select which is supported.
307   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
308   // X86 wants to expand cmov itself.
309   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
310   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
311   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
312   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
313   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
314   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
315   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
316   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
317   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
318   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
320   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
323     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
324   }
325   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
326
327   // Darwin ABI issue.
328   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
329   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
330   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
331   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
332   if (Subtarget->is64Bit())
333     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
335   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
338     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
339     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
340     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
341     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
342   }
343   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
345   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
346   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
349     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
350     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasXMM())
354     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
355
356   // We may not have a libcall for MEMBARRIER so we should lower this.
357   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
358
359   // On X86 and X86-64, atomic operations are lowered to locked instructions.
360   // Locked instructions, in turn, have implicit fence semantics (all memory
361   // operations are flushed before issuing the locked instruction, and they
362   // are not buffered), so we can fold away the common pattern of
363   // fence-atomic-fence.
364   setShouldFoldAtomicFences(true);
365
366   // Expand certain atomics
367   for (unsigned i = 0, e = 4; i != e; ++i) {
368     MVT VT = IntVTs[i];
369     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
370     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
371   }
372
373   if (!Subtarget->is64Bit()) {
374     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
375     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
376     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
377     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
378     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
379     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
380     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
381   }
382
383   // FIXME - use subtarget debug flags
384   if (!Subtarget->isTargetDarwin() &&
385       !Subtarget->isTargetELF() &&
386       !Subtarget->isTargetCygMing()) {
387     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
388   }
389
390   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
391   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
392   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
393   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
394   if (Subtarget->is64Bit()) {
395     setExceptionPointerRegister(X86::RAX);
396     setExceptionSelectorRegister(X86::RDX);
397   } else {
398     setExceptionPointerRegister(X86::EAX);
399     setExceptionSelectorRegister(X86::EDX);
400   }
401   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
402   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
403
404   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
405
406   setOperationAction(ISD::TRAP, MVT::Other, Legal);
407
408   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
409   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
410   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
411   if (Subtarget->is64Bit()) {
412     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
413     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
414   } else {
415     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
416     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
417   }
418
419   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
420   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
421   if (Subtarget->is64Bit())
422     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
423   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
424     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
425   else
426     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
427
428   if (!UseSoftFloat && X86ScalarSSEf64) {
429     // f32 and f64 use SSE.
430     // Set up the FP register classes.
431     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
432     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
433
434     // Use ANDPD to simulate FABS.
435     setOperationAction(ISD::FABS , MVT::f64, Custom);
436     setOperationAction(ISD::FABS , MVT::f32, Custom);
437
438     // Use XORP to simulate FNEG.
439     setOperationAction(ISD::FNEG , MVT::f64, Custom);
440     setOperationAction(ISD::FNEG , MVT::f32, Custom);
441
442     // Use ANDPD and ORPD to simulate FCOPYSIGN.
443     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
444     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
445
446     // We don't support sin/cos/fmod
447     setOperationAction(ISD::FSIN , MVT::f64, Expand);
448     setOperationAction(ISD::FCOS , MVT::f64, Expand);
449     setOperationAction(ISD::FSIN , MVT::f32, Expand);
450     setOperationAction(ISD::FCOS , MVT::f32, Expand);
451
452     // Expand FP immediates into loads from the stack, except for the special
453     // cases we handle.
454     addLegalFPImmediate(APFloat(+0.0)); // xorpd
455     addLegalFPImmediate(APFloat(+0.0f)); // xorps
456   } else if (!UseSoftFloat && X86ScalarSSEf32) {
457     // Use SSE for f32, x87 for f64.
458     // Set up the FP register classes.
459     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
460     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
461
462     // Use ANDPS to simulate FABS.
463     setOperationAction(ISD::FABS , MVT::f32, Custom);
464
465     // Use XORP to simulate FNEG.
466     setOperationAction(ISD::FNEG , MVT::f32, Custom);
467
468     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
469
470     // Use ANDPS and ORPS to simulate FCOPYSIGN.
471     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
472     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
473
474     // We don't support sin/cos/fmod
475     setOperationAction(ISD::FSIN , MVT::f32, Expand);
476     setOperationAction(ISD::FCOS , MVT::f32, Expand);
477
478     // Special cases we handle for FP constants.
479     addLegalFPImmediate(APFloat(+0.0f)); // xorps
480     addLegalFPImmediate(APFloat(+0.0)); // FLD0
481     addLegalFPImmediate(APFloat(+1.0)); // FLD1
482     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
483     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
484
485     if (!UnsafeFPMath) {
486       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
487       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
488     }
489   } else if (!UseSoftFloat) {
490     // f32 and f64 in x87.
491     // Set up the FP register classes.
492     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
493     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
494
495     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
496     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
497     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
498     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
499
500     if (!UnsafeFPMath) {
501       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
502       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
503     }
504     addLegalFPImmediate(APFloat(+0.0)); // FLD0
505     addLegalFPImmediate(APFloat(+1.0)); // FLD1
506     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
507     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
508     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
509     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
510     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
511     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
512   }
513
514   // Long double always uses X87.
515   if (!UseSoftFloat) {
516     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
517     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
518     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
519     {
520       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
521       addLegalFPImmediate(TmpFlt);  // FLD0
522       TmpFlt.changeSign();
523       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
524
525       bool ignored;
526       APFloat TmpFlt2(+1.0);
527       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
528                       &ignored);
529       addLegalFPImmediate(TmpFlt2);  // FLD1
530       TmpFlt2.changeSign();
531       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
532     }
533
534     if (!UnsafeFPMath) {
535       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
536       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
537     }
538   }
539
540   // Always use a library call for pow.
541   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
542   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
543   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
544
545   setOperationAction(ISD::FLOG, MVT::f80, Expand);
546   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
547   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
548   setOperationAction(ISD::FEXP, MVT::f80, Expand);
549   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
550
551   // First set operation action for all vector types to either promote
552   // (for widening) or expand (for scalarization). Then we will selectively
553   // turn on ones that can be effectively codegen'd.
554   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
555        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
556     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
571     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
573     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
574     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
606     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
610     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
611          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
612       setTruncStoreAction((MVT::SimpleValueType)VT,
613                           (MVT::SimpleValueType)InnerVT, Expand);
614     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
615     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
616     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
617   }
618
619   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
620   // with -msoft-float, disable use of MMX as well.
621   if (!UseSoftFloat && Subtarget->hasMMX()) {
622     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
623     // No operations on x86mmx supported, everything uses intrinsics.
624   }
625
626   // MMX-sized vectors (other than x86mmx) are expected to be expanded
627   // into smaller operations.
628   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
629   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
630   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
631   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
632   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
633   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
634   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
635   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
636   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
637   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
638   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
639   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
640   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
641   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
642   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
643   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
644   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
645   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
646   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
647   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
648   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
649   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
650   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
651   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
652   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
653   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
654   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
655   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
656   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
657
658   if (!UseSoftFloat && Subtarget->hasXMM()) {
659     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
660
661     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
662     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
663     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
664     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
665     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
666     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
667     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
668     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
669     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
670     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
671     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
672     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
673   }
674
675   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
676     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
677
678     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
679     // registers cannot be used even for integer operations.
680     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
681     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
682     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
683     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
684
685     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
686     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
687     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
688     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
689     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
690     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
691     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
692     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
693     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
694     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
695     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
696     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
697     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
698     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
699     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
700     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
701
702     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
703     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
704     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
705     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
706
707     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
708     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
709     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
710     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
711     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
712
713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
714     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
715     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
716     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
717     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
718
719     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
720     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
721       EVT VT = (MVT::SimpleValueType)i;
722       // Do not attempt to custom lower non-power-of-2 vectors
723       if (!isPowerOf2_32(VT.getVectorNumElements()))
724         continue;
725       // Do not attempt to custom lower non-128-bit vectors
726       if (!VT.is128BitVector())
727         continue;
728       setOperationAction(ISD::BUILD_VECTOR,
729                          VT.getSimpleVT().SimpleTy, Custom);
730       setOperationAction(ISD::VECTOR_SHUFFLE,
731                          VT.getSimpleVT().SimpleTy, Custom);
732       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
733                          VT.getSimpleVT().SimpleTy, Custom);
734     }
735
736     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
737     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
738     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
739     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
740     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
741     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
742
743     if (Subtarget->is64Bit()) {
744       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
745       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
746     }
747
748     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
749     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
750       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
751       EVT VT = SVT;
752
753       // Do not attempt to promote non-128-bit vectors
754       if (!VT.is128BitVector())
755         continue;
756
757       setOperationAction(ISD::AND,    SVT, Promote);
758       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
759       setOperationAction(ISD::OR,     SVT, Promote);
760       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
761       setOperationAction(ISD::XOR,    SVT, Promote);
762       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
763       setOperationAction(ISD::LOAD,   SVT, Promote);
764       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
765       setOperationAction(ISD::SELECT, SVT, Promote);
766       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
767     }
768
769     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
770
771     // Custom lower v2i64 and v2f64 selects.
772     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
773     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
774     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
775     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
776
777     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
778     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
779   }
780
781   if (Subtarget->hasSSE41()) {
782     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
783     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
784     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
785     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
786     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
787     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
788     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
789     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
790     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
791     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
792
793     // FIXME: Do we need to handle scalar-to-vector here?
794     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
795
796     // Can turn SHL into an integer multiply.
797     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
798     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
799
800     // i8 and i16 vectors are custom , because the source register and source
801     // source memory operand types are not the same width.  f32 vectors are
802     // custom since the immediate controlling the insert encodes additional
803     // information.
804     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
805     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
806     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
807     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
808
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
810     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
812     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
813
814     if (Subtarget->is64Bit()) {
815       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
816       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
817     }
818   }
819
820   if (Subtarget->hasSSE42())
821     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
822
823   if (!UseSoftFloat && Subtarget->hasAVX()) {
824     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
825     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
826     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
827     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
828     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
829
830     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
831     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
832     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
833     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
834     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
835     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
836     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
837     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
838     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
839     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
840     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
841     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
842     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
843     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
844     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
845
846     // Operations to consider commented out -v16i16 v32i8
847     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
848     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
849     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
850     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
851     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
852     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
853     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
854     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
855     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
856     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
857     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
858     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
859     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
860     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
861
862     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
863     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
864     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
865     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
866
867     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
868     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
869     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
872
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
874     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
876     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
877     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
878     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
879
880 #if 0
881     // Not sure we want to do this since there are no 256-bit integer
882     // operations in AVX
883
884     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
885     // This includes 256-bit vectors
886     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
887       EVT VT = (MVT::SimpleValueType)i;
888
889       // Do not attempt to custom lower non-power-of-2 vectors
890       if (!isPowerOf2_32(VT.getVectorNumElements()))
891         continue;
892
893       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
894       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
896     }
897
898     if (Subtarget->is64Bit()) {
899       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
900       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
901     }
902 #endif
903
904 #if 0
905     // Not sure we want to do this since there are no 256-bit integer
906     // operations in AVX
907
908     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
909     // Including 256-bit vectors
910     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
911       EVT VT = (MVT::SimpleValueType)i;
912
913       if (!VT.is256BitVector()) {
914         continue;
915       }
916       setOperationAction(ISD::AND,    VT, Promote);
917       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
918       setOperationAction(ISD::OR,     VT, Promote);
919       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
920       setOperationAction(ISD::XOR,    VT, Promote);
921       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
922       setOperationAction(ISD::LOAD,   VT, Promote);
923       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
924       setOperationAction(ISD::SELECT, VT, Promote);
925       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
926     }
927
928     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
929 #endif
930   }
931
932   // We want to custom lower some of our intrinsics.
933   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
934
935
936   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
937   // handle type legalization for these operations here.
938   //
939   // FIXME: We really should do custom legalization for addition and
940   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
941   // than generic legalization for 64-bit multiplication-with-overflow, though.
942   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
943     // Add/Sub/Mul with overflow operations are custom lowered.
944     MVT VT = IntVTs[i];
945     setOperationAction(ISD::SADDO, VT, Custom);
946     setOperationAction(ISD::UADDO, VT, Custom);
947     setOperationAction(ISD::SSUBO, VT, Custom);
948     setOperationAction(ISD::USUBO, VT, Custom);
949     setOperationAction(ISD::SMULO, VT, Custom);
950     setOperationAction(ISD::UMULO, VT, Custom);
951   }
952
953   // There are no 8-bit 3-address imul/mul instructions
954   setOperationAction(ISD::SMULO, MVT::i8, Expand);
955   setOperationAction(ISD::UMULO, MVT::i8, Expand);
956
957   if (!Subtarget->is64Bit()) {
958     // These libcalls are not available in 32-bit.
959     setLibcallName(RTLIB::SHL_I128, 0);
960     setLibcallName(RTLIB::SRL_I128, 0);
961     setLibcallName(RTLIB::SRA_I128, 0);
962   }
963
964   // We have target-specific dag combine patterns for the following nodes:
965   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
966   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
967   setTargetDAGCombine(ISD::BUILD_VECTOR);
968   setTargetDAGCombine(ISD::SELECT);
969   setTargetDAGCombine(ISD::SHL);
970   setTargetDAGCombine(ISD::SRA);
971   setTargetDAGCombine(ISD::SRL);
972   setTargetDAGCombine(ISD::OR);
973   setTargetDAGCombine(ISD::AND);
974   setTargetDAGCombine(ISD::ADD);
975   setTargetDAGCombine(ISD::SUB);
976   setTargetDAGCombine(ISD::STORE);
977   setTargetDAGCombine(ISD::ZERO_EXTEND);
978   if (Subtarget->is64Bit())
979     setTargetDAGCombine(ISD::MUL);
980
981   computeRegisterProperties();
982
983   // On Darwin, -Os means optimize for size without hurting performance,
984   // do not reduce the limit.
985   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
986   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
987   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
988   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
989   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
990   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
991   setPrefLoopAlignment(16);
992   benefitFromCodePlacementOpt = true;
993 }
994
995
996 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
997   return MVT::i8;
998 }
999
1000
1001 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1002 /// the desired ByVal argument alignment.
1003 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1004   if (MaxAlign == 16)
1005     return;
1006   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1007     if (VTy->getBitWidth() == 128)
1008       MaxAlign = 16;
1009   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1010     unsigned EltAlign = 0;
1011     getMaxByValAlign(ATy->getElementType(), EltAlign);
1012     if (EltAlign > MaxAlign)
1013       MaxAlign = EltAlign;
1014   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1015     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1016       unsigned EltAlign = 0;
1017       getMaxByValAlign(STy->getElementType(i), EltAlign);
1018       if (EltAlign > MaxAlign)
1019         MaxAlign = EltAlign;
1020       if (MaxAlign == 16)
1021         break;
1022     }
1023   }
1024   return;
1025 }
1026
1027 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1028 /// function arguments in the caller parameter area. For X86, aggregates
1029 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1030 /// are at 4-byte boundaries.
1031 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1032   if (Subtarget->is64Bit()) {
1033     // Max of 8 and alignment of type.
1034     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1035     if (TyAlign > 8)
1036       return TyAlign;
1037     return 8;
1038   }
1039
1040   unsigned Align = 4;
1041   if (Subtarget->hasXMM())
1042     getMaxByValAlign(Ty, Align);
1043   return Align;
1044 }
1045
1046 /// getOptimalMemOpType - Returns the target specific optimal type for load
1047 /// and store operations as a result of memset, memcpy, and memmove
1048 /// lowering. If DstAlign is zero that means it's safe to destination
1049 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1050 /// means there isn't a need to check it against alignment requirement,
1051 /// probably because the source does not need to be loaded. If
1052 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1053 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1054 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1055 /// constant so it does not need to be loaded.
1056 /// It returns EVT::Other if the type should be determined using generic
1057 /// target-independent logic.
1058 EVT
1059 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1060                                        unsigned DstAlign, unsigned SrcAlign,
1061                                        bool NonScalarIntSafe,
1062                                        bool MemcpyStrSrc,
1063                                        MachineFunction &MF) const {
1064   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1065   // linux.  This is because the stack realignment code can't handle certain
1066   // cases like PR2962.  This should be removed when PR2962 is fixed.
1067   const Function *F = MF.getFunction();
1068   if (NonScalarIntSafe &&
1069       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1070     if (Size >= 16 &&
1071         (Subtarget->isUnalignedMemAccessFast() ||
1072          ((DstAlign == 0 || DstAlign >= 16) &&
1073           (SrcAlign == 0 || SrcAlign >= 16))) &&
1074         Subtarget->getStackAlignment() >= 16) {
1075       if (Subtarget->hasSSE2())
1076         return MVT::v4i32;
1077       if (Subtarget->hasSSE1())
1078         return MVT::v4f32;
1079     } else if (!MemcpyStrSrc && Size >= 8 &&
1080                !Subtarget->is64Bit() &&
1081                Subtarget->getStackAlignment() >= 8 &&
1082                Subtarget->hasXMMInt()) {
1083       // Do not use f64 to lower memcpy if source is string constant. It's
1084       // better to use i32 to avoid the loads.
1085       return MVT::f64;
1086     }
1087   }
1088   if (Subtarget->is64Bit() && Size >= 8)
1089     return MVT::i64;
1090   return MVT::i32;
1091 }
1092
1093 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1094 /// current function.  The returned value is a member of the
1095 /// MachineJumpTableInfo::JTEntryKind enum.
1096 unsigned X86TargetLowering::getJumpTableEncoding() const {
1097   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1098   // symbol.
1099   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1100       Subtarget->isPICStyleGOT())
1101     return MachineJumpTableInfo::EK_Custom32;
1102
1103   // Otherwise, use the normal jump table encoding heuristics.
1104   return TargetLowering::getJumpTableEncoding();
1105 }
1106
1107 const MCExpr *
1108 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1109                                              const MachineBasicBlock *MBB,
1110                                              unsigned uid,MCContext &Ctx) const{
1111   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1112          Subtarget->isPICStyleGOT());
1113   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1114   // entries.
1115   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1116                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1117 }
1118
1119 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1120 /// jumptable.
1121 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1122                                                     SelectionDAG &DAG) const {
1123   if (!Subtarget->is64Bit())
1124     // This doesn't have DebugLoc associated with it, but is not really the
1125     // same as a Register.
1126     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1127   return Table;
1128 }
1129
1130 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1131 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1132 /// MCExpr.
1133 const MCExpr *X86TargetLowering::
1134 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1135                              MCContext &Ctx) const {
1136   // X86-64 uses RIP relative addressing based on the jump table label.
1137   if (Subtarget->isPICStyleRIPRel())
1138     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1139
1140   // Otherwise, the reference is relative to the PIC base.
1141   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1142 }
1143
1144 /// getFunctionAlignment - Return the Log2 alignment of this function.
1145 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1146   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1147 }
1148
1149 // FIXME: Why this routine is here? Move to RegInfo!
1150 std::pair<const TargetRegisterClass*, uint8_t>
1151 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1152   const TargetRegisterClass *RRC = 0;
1153   uint8_t Cost = 1;
1154   switch (VT.getSimpleVT().SimpleTy) {
1155   default:
1156     return TargetLowering::findRepresentativeClass(VT);
1157   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1158     RRC = (Subtarget->is64Bit()
1159            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1160     break;
1161   case MVT::x86mmx:
1162     RRC = X86::VR64RegisterClass;
1163     break;
1164   case MVT::f32: case MVT::f64:
1165   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1166   case MVT::v4f32: case MVT::v2f64:
1167   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1168   case MVT::v4f64:
1169     RRC = X86::VR128RegisterClass;
1170     break;
1171   }
1172   return std::make_pair(RRC, Cost);
1173 }
1174
1175 // FIXME: Why this routine is here? Move to RegInfo!
1176 unsigned
1177 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1178                                        MachineFunction &MF) const {
1179   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1180
1181   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1182   switch (RC->getID()) {
1183   default:
1184     return 0;
1185   case X86::GR32RegClassID:
1186     return 4 - FPDiff;
1187   case X86::GR64RegClassID:
1188     return 8 - FPDiff;
1189   case X86::VR128RegClassID:
1190     return Subtarget->is64Bit() ? 10 : 4;
1191   case X86::VR64RegClassID:
1192     return 4;
1193   }
1194 }
1195
1196 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1197                                                unsigned &Offset) const {
1198   if (!Subtarget->isTargetLinux())
1199     return false;
1200
1201   if (Subtarget->is64Bit()) {
1202     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1203     Offset = 0x28;
1204     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1205       AddressSpace = 256;
1206     else
1207       AddressSpace = 257;
1208   } else {
1209     // %gs:0x14 on i386
1210     Offset = 0x14;
1211     AddressSpace = 256;
1212   }
1213   return true;
1214 }
1215
1216
1217 //===----------------------------------------------------------------------===//
1218 //               Return Value Calling Convention Implementation
1219 //===----------------------------------------------------------------------===//
1220
1221 #include "X86GenCallingConv.inc"
1222
1223 bool
1224 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1225                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1226                         LLVMContext &Context) const {
1227   SmallVector<CCValAssign, 16> RVLocs;
1228   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1229                  RVLocs, Context);
1230   return CCInfo.CheckReturn(Outs, RetCC_X86);
1231 }
1232
1233 SDValue
1234 X86TargetLowering::LowerReturn(SDValue Chain,
1235                                CallingConv::ID CallConv, bool isVarArg,
1236                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1237                                const SmallVectorImpl<SDValue> &OutVals,
1238                                DebugLoc dl, SelectionDAG &DAG) const {
1239   MachineFunction &MF = DAG.getMachineFunction();
1240   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1241
1242   SmallVector<CCValAssign, 16> RVLocs;
1243   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1244                  RVLocs, *DAG.getContext());
1245   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1246
1247   // Add the regs to the liveout set for the function.
1248   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1249   for (unsigned i = 0; i != RVLocs.size(); ++i)
1250     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1251       MRI.addLiveOut(RVLocs[i].getLocReg());
1252
1253   SDValue Flag;
1254
1255   SmallVector<SDValue, 6> RetOps;
1256   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1257   // Operand #1 = Bytes To Pop
1258   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1259                    MVT::i16));
1260
1261   // Copy the result values into the output registers.
1262   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1263     CCValAssign &VA = RVLocs[i];
1264     assert(VA.isRegLoc() && "Can only return in registers!");
1265     SDValue ValToCopy = OutVals[i];
1266     EVT ValVT = ValToCopy.getValueType();
1267
1268     // If this is x86-64, and we disabled SSE, we can't return FP values,
1269     // or SSE or MMX vectors.
1270     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1271          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1272           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1273       report_fatal_error("SSE register return with SSE disabled");
1274     }
1275     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1276     // llvm-gcc has never done it right and no one has noticed, so this
1277     // should be OK for now.
1278     if (ValVT == MVT::f64 &&
1279         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1280       report_fatal_error("SSE2 register return with SSE2 disabled");
1281
1282     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1283     // the RET instruction and handled by the FP Stackifier.
1284     if (VA.getLocReg() == X86::ST0 ||
1285         VA.getLocReg() == X86::ST1) {
1286       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1287       // change the value to the FP stack register class.
1288       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1289         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1290       RetOps.push_back(ValToCopy);
1291       // Don't emit a copytoreg.
1292       continue;
1293     }
1294
1295     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1296     // which is returned in RAX / RDX.
1297     if (Subtarget->is64Bit()) {
1298       if (ValVT == MVT::x86mmx) {
1299         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1300           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1301           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1302                                   ValToCopy);
1303           // If we don't have SSE2 available, convert to v4f32 so the generated
1304           // register is legal.
1305           if (!Subtarget->hasSSE2())
1306             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1307         }
1308       }
1309     }
1310
1311     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1312     Flag = Chain.getValue(1);
1313   }
1314
1315   // The x86-64 ABI for returning structs by value requires that we copy
1316   // the sret argument into %rax for the return. We saved the argument into
1317   // a virtual register in the entry block, so now we copy the value out
1318   // and into %rax.
1319   if (Subtarget->is64Bit() &&
1320       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1321     MachineFunction &MF = DAG.getMachineFunction();
1322     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1323     unsigned Reg = FuncInfo->getSRetReturnReg();
1324     assert(Reg &&
1325            "SRetReturnReg should have been set in LowerFormalArguments().");
1326     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1327
1328     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1329     Flag = Chain.getValue(1);
1330
1331     // RAX now acts like a return value.
1332     MRI.addLiveOut(X86::RAX);
1333   }
1334
1335   RetOps[0] = Chain;  // Update chain.
1336
1337   // Add the flag if we have it.
1338   if (Flag.getNode())
1339     RetOps.push_back(Flag);
1340
1341   return DAG.getNode(X86ISD::RET_FLAG, dl,
1342                      MVT::Other, &RetOps[0], RetOps.size());
1343 }
1344
1345 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1346   if (N->getNumValues() != 1)
1347     return false;
1348   if (!N->hasNUsesOfValue(1, 0))
1349     return false;
1350
1351   SDNode *Copy = *N->use_begin();
1352   if (Copy->getOpcode() != ISD::CopyToReg &&
1353       Copy->getOpcode() != ISD::FP_EXTEND)
1354     return false;
1355
1356   bool HasRet = false;
1357   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1358        UI != UE; ++UI) {
1359     if (UI->getOpcode() != X86ISD::RET_FLAG)
1360       return false;
1361     HasRet = true;
1362   }
1363
1364   return HasRet;
1365 }
1366
1367 /// LowerCallResult - Lower the result values of a call into the
1368 /// appropriate copies out of appropriate physical registers.
1369 ///
1370 SDValue
1371 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1372                                    CallingConv::ID CallConv, bool isVarArg,
1373                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1374                                    DebugLoc dl, SelectionDAG &DAG,
1375                                    SmallVectorImpl<SDValue> &InVals) const {
1376
1377   // Assign locations to each value returned by this call.
1378   SmallVector<CCValAssign, 16> RVLocs;
1379   bool Is64Bit = Subtarget->is64Bit();
1380   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1381                  RVLocs, *DAG.getContext());
1382   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1383
1384   // Copy all of the result registers out of their specified physreg.
1385   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1386     CCValAssign &VA = RVLocs[i];
1387     EVT CopyVT = VA.getValVT();
1388
1389     // If this is x86-64, and we disabled SSE, we can't return FP values
1390     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1391         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1392       report_fatal_error("SSE register return with SSE disabled");
1393     }
1394
1395     SDValue Val;
1396
1397     // If this is a call to a function that returns an fp value on the floating
1398     // point stack, we must guarantee the the value is popped from the stack, so
1399     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1400     // if the return value is not used. We use the FpGET_ST0 instructions
1401     // instead.
1402     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1403       // If we prefer to use the value in xmm registers, copy it out as f80 and
1404       // use a truncate to move it from fp stack reg to xmm reg.
1405       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1406       bool isST0 = VA.getLocReg() == X86::ST0;
1407       unsigned Opc = 0;
1408       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1409       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1410       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1411       SDValue Ops[] = { Chain, InFlag };
1412       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1413                                          Ops, 2), 1);
1414       Val = Chain.getValue(0);
1415
1416       // Round the f80 to the right size, which also moves it to the appropriate
1417       // xmm register.
1418       if (CopyVT != VA.getValVT())
1419         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1420                           // This truncation won't change the value.
1421                           DAG.getIntPtrConstant(1));
1422     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1423       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1424       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1425         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1426                                    MVT::v2i64, InFlag).getValue(1);
1427         Val = Chain.getValue(0);
1428         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1429                           Val, DAG.getConstant(0, MVT::i64));
1430       } else {
1431         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1432                                    MVT::i64, InFlag).getValue(1);
1433         Val = Chain.getValue(0);
1434       }
1435       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1436     } else {
1437       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1438                                  CopyVT, InFlag).getValue(1);
1439       Val = Chain.getValue(0);
1440     }
1441     InFlag = Chain.getValue(2);
1442     InVals.push_back(Val);
1443   }
1444
1445   return Chain;
1446 }
1447
1448
1449 //===----------------------------------------------------------------------===//
1450 //                C & StdCall & Fast Calling Convention implementation
1451 //===----------------------------------------------------------------------===//
1452 //  StdCall calling convention seems to be standard for many Windows' API
1453 //  routines and around. It differs from C calling convention just a little:
1454 //  callee should clean up the stack, not caller. Symbols should be also
1455 //  decorated in some fancy way :) It doesn't support any vector arguments.
1456 //  For info on fast calling convention see Fast Calling Convention (tail call)
1457 //  implementation LowerX86_32FastCCCallTo.
1458
1459 /// CallIsStructReturn - Determines whether a call uses struct return
1460 /// semantics.
1461 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1462   if (Outs.empty())
1463     return false;
1464
1465   return Outs[0].Flags.isSRet();
1466 }
1467
1468 /// ArgsAreStructReturn - Determines whether a function uses struct
1469 /// return semantics.
1470 static bool
1471 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1472   if (Ins.empty())
1473     return false;
1474
1475   return Ins[0].Flags.isSRet();
1476 }
1477
1478 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1479 /// by "Src" to address "Dst" with size and alignment information specified by
1480 /// the specific parameter attribute. The copy will be passed as a byval
1481 /// function parameter.
1482 static SDValue
1483 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1484                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1485                           DebugLoc dl) {
1486   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1487
1488   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1489                        /*isVolatile*/false, /*AlwaysInline=*/true,
1490                        MachinePointerInfo(), MachinePointerInfo());
1491 }
1492
1493 /// IsTailCallConvention - Return true if the calling convention is one that
1494 /// supports tail call optimization.
1495 static bool IsTailCallConvention(CallingConv::ID CC) {
1496   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1497 }
1498
1499 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1500 /// a tailcall target by changing its ABI.
1501 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1502   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1503 }
1504
1505 SDValue
1506 X86TargetLowering::LowerMemArgument(SDValue Chain,
1507                                     CallingConv::ID CallConv,
1508                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1509                                     DebugLoc dl, SelectionDAG &DAG,
1510                                     const CCValAssign &VA,
1511                                     MachineFrameInfo *MFI,
1512                                     unsigned i) const {
1513   // Create the nodes corresponding to a load from this parameter slot.
1514   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1515   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1516   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1517   EVT ValVT;
1518
1519   // If value is passed by pointer we have address passed instead of the value
1520   // itself.
1521   if (VA.getLocInfo() == CCValAssign::Indirect)
1522     ValVT = VA.getLocVT();
1523   else
1524     ValVT = VA.getValVT();
1525
1526   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1527   // changed with more analysis.
1528   // In case of tail call optimization mark all arguments mutable. Since they
1529   // could be overwritten by lowering of arguments in case of a tail call.
1530   if (Flags.isByVal()) {
1531     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1532                                     VA.getLocMemOffset(), isImmutable);
1533     return DAG.getFrameIndex(FI, getPointerTy());
1534   } else {
1535     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1536                                     VA.getLocMemOffset(), isImmutable);
1537     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1538     return DAG.getLoad(ValVT, dl, Chain, FIN,
1539                        MachinePointerInfo::getFixedStack(FI),
1540                        false, false, 0);
1541   }
1542 }
1543
1544 SDValue
1545 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1546                                         CallingConv::ID CallConv,
1547                                         bool isVarArg,
1548                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1549                                         DebugLoc dl,
1550                                         SelectionDAG &DAG,
1551                                         SmallVectorImpl<SDValue> &InVals)
1552                                           const {
1553   MachineFunction &MF = DAG.getMachineFunction();
1554   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1555
1556   const Function* Fn = MF.getFunction();
1557   if (Fn->hasExternalLinkage() &&
1558       Subtarget->isTargetCygMing() &&
1559       Fn->getName() == "main")
1560     FuncInfo->setForceFramePointer(true);
1561
1562   MachineFrameInfo *MFI = MF.getFrameInfo();
1563   bool Is64Bit = Subtarget->is64Bit();
1564   bool IsWin64 = Subtarget->isTargetWin64();
1565
1566   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1567          "Var args not supported with calling convention fastcc or ghc");
1568
1569   // Assign locations to all of the incoming arguments.
1570   SmallVector<CCValAssign, 16> ArgLocs;
1571   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1572                  ArgLocs, *DAG.getContext());
1573   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1574
1575   unsigned LastVal = ~0U;
1576   SDValue ArgValue;
1577   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1578     CCValAssign &VA = ArgLocs[i];
1579     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1580     // places.
1581     assert(VA.getValNo() != LastVal &&
1582            "Don't support value assigned to multiple locs yet");
1583     LastVal = VA.getValNo();
1584
1585     if (VA.isRegLoc()) {
1586       EVT RegVT = VA.getLocVT();
1587       TargetRegisterClass *RC = NULL;
1588       if (RegVT == MVT::i32)
1589         RC = X86::GR32RegisterClass;
1590       else if (Is64Bit && RegVT == MVT::i64)
1591         RC = X86::GR64RegisterClass;
1592       else if (RegVT == MVT::f32)
1593         RC = X86::FR32RegisterClass;
1594       else if (RegVT == MVT::f64)
1595         RC = X86::FR64RegisterClass;
1596       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1597         RC = X86::VR256RegisterClass;
1598       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1599         RC = X86::VR128RegisterClass;
1600       else if (RegVT == MVT::x86mmx)
1601         RC = X86::VR64RegisterClass;
1602       else
1603         llvm_unreachable("Unknown argument type!");
1604
1605       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1606       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1607
1608       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1609       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1610       // right size.
1611       if (VA.getLocInfo() == CCValAssign::SExt)
1612         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1613                                DAG.getValueType(VA.getValVT()));
1614       else if (VA.getLocInfo() == CCValAssign::ZExt)
1615         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1616                                DAG.getValueType(VA.getValVT()));
1617       else if (VA.getLocInfo() == CCValAssign::BCvt)
1618         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1619
1620       if (VA.isExtInLoc()) {
1621         // Handle MMX values passed in XMM regs.
1622         if (RegVT.isVector()) {
1623           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1624                                  ArgValue);
1625         } else
1626           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1627       }
1628     } else {
1629       assert(VA.isMemLoc());
1630       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1631     }
1632
1633     // If value is passed via pointer - do a load.
1634     if (VA.getLocInfo() == CCValAssign::Indirect)
1635       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1636                              MachinePointerInfo(), false, false, 0);
1637
1638     InVals.push_back(ArgValue);
1639   }
1640
1641   // The x86-64 ABI for returning structs by value requires that we copy
1642   // the sret argument into %rax for the return. Save the argument into
1643   // a virtual register so that we can access it from the return points.
1644   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1645     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1646     unsigned Reg = FuncInfo->getSRetReturnReg();
1647     if (!Reg) {
1648       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1649       FuncInfo->setSRetReturnReg(Reg);
1650     }
1651     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1652     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1653   }
1654
1655   unsigned StackSize = CCInfo.getNextStackOffset();
1656   // Align stack specially for tail calls.
1657   if (FuncIsMadeTailCallSafe(CallConv))
1658     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1659
1660   // If the function takes variable number of arguments, make a frame index for
1661   // the start of the first vararg value... for expansion of llvm.va_start.
1662   if (isVarArg) {
1663     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1664                     CallConv != CallingConv::X86_ThisCall))) {
1665       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1666     }
1667     if (Is64Bit) {
1668       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1669
1670       // FIXME: We should really autogenerate these arrays
1671       static const unsigned GPR64ArgRegsWin64[] = {
1672         X86::RCX, X86::RDX, X86::R8,  X86::R9
1673       };
1674       static const unsigned GPR64ArgRegs64Bit[] = {
1675         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1676       };
1677       static const unsigned XMMArgRegs64Bit[] = {
1678         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1679         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1680       };
1681       const unsigned *GPR64ArgRegs;
1682       unsigned NumXMMRegs = 0;
1683
1684       if (IsWin64) {
1685         // The XMM registers which might contain var arg parameters are shadowed
1686         // in their paired GPR.  So we only need to save the GPR to their home
1687         // slots.
1688         TotalNumIntRegs = 4;
1689         GPR64ArgRegs = GPR64ArgRegsWin64;
1690       } else {
1691         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1692         GPR64ArgRegs = GPR64ArgRegs64Bit;
1693
1694         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1695       }
1696       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1697                                                        TotalNumIntRegs);
1698
1699       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1700       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1701              "SSE register cannot be used when SSE is disabled!");
1702       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1703              "SSE register cannot be used when SSE is disabled!");
1704       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1705         // Kernel mode asks for SSE to be disabled, so don't push them
1706         // on the stack.
1707         TotalNumXMMRegs = 0;
1708
1709       if (IsWin64) {
1710         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1711         // Get to the caller-allocated home save location.  Add 8 to account
1712         // for the return address.
1713         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1714         FuncInfo->setRegSaveFrameIndex(
1715           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1716         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1717       } else {
1718         // For X86-64, if there are vararg parameters that are passed via
1719         // registers, then we must store them to their spots on the stack so they
1720         // may be loaded by deferencing the result of va_next.
1721         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1722         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1723         FuncInfo->setRegSaveFrameIndex(
1724           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1725                                false));
1726       }
1727
1728       // Store the integer parameter registers.
1729       SmallVector<SDValue, 8> MemOps;
1730       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1731                                         getPointerTy());
1732       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1733       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1734         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1735                                   DAG.getIntPtrConstant(Offset));
1736         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1737                                      X86::GR64RegisterClass);
1738         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1739         SDValue Store =
1740           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1741                        MachinePointerInfo::getFixedStack(
1742                          FuncInfo->getRegSaveFrameIndex(), Offset),
1743                        false, false, 0);
1744         MemOps.push_back(Store);
1745         Offset += 8;
1746       }
1747
1748       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1749         // Now store the XMM (fp + vector) parameter registers.
1750         SmallVector<SDValue, 11> SaveXMMOps;
1751         SaveXMMOps.push_back(Chain);
1752
1753         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1754         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1755         SaveXMMOps.push_back(ALVal);
1756
1757         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1758                                FuncInfo->getRegSaveFrameIndex()));
1759         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1760                                FuncInfo->getVarArgsFPOffset()));
1761
1762         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1763           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1764                                        X86::VR128RegisterClass);
1765           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1766           SaveXMMOps.push_back(Val);
1767         }
1768         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1769                                      MVT::Other,
1770                                      &SaveXMMOps[0], SaveXMMOps.size()));
1771       }
1772
1773       if (!MemOps.empty())
1774         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1775                             &MemOps[0], MemOps.size());
1776     }
1777   }
1778
1779   // Some CCs need callee pop.
1780   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1781     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1782   } else {
1783     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1784     // If this is an sret function, the return should pop the hidden pointer.
1785     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1786       FuncInfo->setBytesToPopOnReturn(4);
1787   }
1788
1789   if (!Is64Bit) {
1790     // RegSaveFrameIndex is X86-64 only.
1791     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1792     if (CallConv == CallingConv::X86_FastCall ||
1793         CallConv == CallingConv::X86_ThisCall)
1794       // fastcc functions can't have varargs.
1795       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1796   }
1797
1798   return Chain;
1799 }
1800
1801 SDValue
1802 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1803                                     SDValue StackPtr, SDValue Arg,
1804                                     DebugLoc dl, SelectionDAG &DAG,
1805                                     const CCValAssign &VA,
1806                                     ISD::ArgFlagsTy Flags) const {
1807   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1808   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1809   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1810   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1811   if (Flags.isByVal())
1812     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1813
1814   return DAG.getStore(Chain, dl, Arg, PtrOff,
1815                       MachinePointerInfo::getStack(LocMemOffset),
1816                       false, false, 0);
1817 }
1818
1819 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1820 /// optimization is performed and it is required.
1821 SDValue
1822 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1823                                            SDValue &OutRetAddr, SDValue Chain,
1824                                            bool IsTailCall, bool Is64Bit,
1825                                            int FPDiff, DebugLoc dl) const {
1826   // Adjust the Return address stack slot.
1827   EVT VT = getPointerTy();
1828   OutRetAddr = getReturnAddressFrameIndex(DAG);
1829
1830   // Load the "old" Return address.
1831   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1832                            false, false, 0);
1833   return SDValue(OutRetAddr.getNode(), 1);
1834 }
1835
1836 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1837 /// optimization is performed and it is required (FPDiff!=0).
1838 static SDValue
1839 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1840                          SDValue Chain, SDValue RetAddrFrIdx,
1841                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1842   // Store the return address to the appropriate stack slot.
1843   if (!FPDiff) return Chain;
1844   // Calculate the new stack slot for the return address.
1845   int SlotSize = Is64Bit ? 8 : 4;
1846   int NewReturnAddrFI =
1847     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1848   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1849   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1850   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1851                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1852                        false, false, 0);
1853   return Chain;
1854 }
1855
1856 SDValue
1857 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1858                              CallingConv::ID CallConv, bool isVarArg,
1859                              bool &isTailCall,
1860                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1861                              const SmallVectorImpl<SDValue> &OutVals,
1862                              const SmallVectorImpl<ISD::InputArg> &Ins,
1863                              DebugLoc dl, SelectionDAG &DAG,
1864                              SmallVectorImpl<SDValue> &InVals) const {
1865   MachineFunction &MF = DAG.getMachineFunction();
1866   bool Is64Bit        = Subtarget->is64Bit();
1867   bool IsStructRet    = CallIsStructReturn(Outs);
1868   bool IsSibcall      = false;
1869
1870   if (isTailCall) {
1871     // Check if it's really possible to do a tail call.
1872     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1873                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1874                                                    Outs, OutVals, Ins, DAG);
1875
1876     // Sibcalls are automatically detected tailcalls which do not require
1877     // ABI changes.
1878     if (!GuaranteedTailCallOpt && isTailCall)
1879       IsSibcall = true;
1880
1881     if (isTailCall)
1882       ++NumTailCalls;
1883   }
1884
1885   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1886          "Var args not supported with calling convention fastcc or ghc");
1887
1888   // Analyze operands of the call, assigning locations to each operand.
1889   SmallVector<CCValAssign, 16> ArgLocs;
1890   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1891                  ArgLocs, *DAG.getContext());
1892   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1893
1894   // Get a count of how many bytes are to be pushed on the stack.
1895   unsigned NumBytes = CCInfo.getNextStackOffset();
1896   if (IsSibcall)
1897     // This is a sibcall. The memory operands are available in caller's
1898     // own caller's stack.
1899     NumBytes = 0;
1900   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1901     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1902
1903   int FPDiff = 0;
1904   if (isTailCall && !IsSibcall) {
1905     // Lower arguments at fp - stackoffset + fpdiff.
1906     unsigned NumBytesCallerPushed =
1907       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1908     FPDiff = NumBytesCallerPushed - NumBytes;
1909
1910     // Set the delta of movement of the returnaddr stackslot.
1911     // But only set if delta is greater than previous delta.
1912     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1913       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1914   }
1915
1916   if (!IsSibcall)
1917     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1918
1919   SDValue RetAddrFrIdx;
1920   // Load return adress for tail calls.
1921   if (isTailCall && FPDiff)
1922     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1923                                     Is64Bit, FPDiff, dl);
1924
1925   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1926   SmallVector<SDValue, 8> MemOpChains;
1927   SDValue StackPtr;
1928
1929   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1930   // of tail call optimization arguments are handle later.
1931   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1932     CCValAssign &VA = ArgLocs[i];
1933     EVT RegVT = VA.getLocVT();
1934     SDValue Arg = OutVals[i];
1935     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1936     bool isByVal = Flags.isByVal();
1937
1938     // Promote the value if needed.
1939     switch (VA.getLocInfo()) {
1940     default: llvm_unreachable("Unknown loc info!");
1941     case CCValAssign::Full: break;
1942     case CCValAssign::SExt:
1943       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1944       break;
1945     case CCValAssign::ZExt:
1946       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1947       break;
1948     case CCValAssign::AExt:
1949       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1950         // Special case: passing MMX values in XMM registers.
1951         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1952         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1953         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1954       } else
1955         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1956       break;
1957     case CCValAssign::BCvt:
1958       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1959       break;
1960     case CCValAssign::Indirect: {
1961       // Store the argument.
1962       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1963       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1964       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1965                            MachinePointerInfo::getFixedStack(FI),
1966                            false, false, 0);
1967       Arg = SpillSlot;
1968       break;
1969     }
1970     }
1971
1972     if (VA.isRegLoc()) {
1973       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1974       if (isVarArg && Subtarget->isTargetWin64()) {
1975         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1976         // shadow reg if callee is a varargs function.
1977         unsigned ShadowReg = 0;
1978         switch (VA.getLocReg()) {
1979         case X86::XMM0: ShadowReg = X86::RCX; break;
1980         case X86::XMM1: ShadowReg = X86::RDX; break;
1981         case X86::XMM2: ShadowReg = X86::R8; break;
1982         case X86::XMM3: ShadowReg = X86::R9; break;
1983         }
1984         if (ShadowReg)
1985           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1986       }
1987     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1988       assert(VA.isMemLoc());
1989       if (StackPtr.getNode() == 0)
1990         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1991       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1992                                              dl, DAG, VA, Flags));
1993     }
1994   }
1995
1996   if (!MemOpChains.empty())
1997     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1998                         &MemOpChains[0], MemOpChains.size());
1999
2000   // Build a sequence of copy-to-reg nodes chained together with token chain
2001   // and flag operands which copy the outgoing args into registers.
2002   SDValue InFlag;
2003   // Tail call byval lowering might overwrite argument registers so in case of
2004   // tail call optimization the copies to registers are lowered later.
2005   if (!isTailCall)
2006     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2007       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2008                                RegsToPass[i].second, InFlag);
2009       InFlag = Chain.getValue(1);
2010     }
2011
2012   if (Subtarget->isPICStyleGOT()) {
2013     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2014     // GOT pointer.
2015     if (!isTailCall) {
2016       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2017                                DAG.getNode(X86ISD::GlobalBaseReg,
2018                                            DebugLoc(), getPointerTy()),
2019                                InFlag);
2020       InFlag = Chain.getValue(1);
2021     } else {
2022       // If we are tail calling and generating PIC/GOT style code load the
2023       // address of the callee into ECX. The value in ecx is used as target of
2024       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2025       // for tail calls on PIC/GOT architectures. Normally we would just put the
2026       // address of GOT into ebx and then call target@PLT. But for tail calls
2027       // ebx would be restored (since ebx is callee saved) before jumping to the
2028       // target@PLT.
2029
2030       // Note: The actual moving to ECX is done further down.
2031       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2032       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2033           !G->getGlobal()->hasProtectedVisibility())
2034         Callee = LowerGlobalAddress(Callee, DAG);
2035       else if (isa<ExternalSymbolSDNode>(Callee))
2036         Callee = LowerExternalSymbol(Callee, DAG);
2037     }
2038   }
2039
2040   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2041     // From AMD64 ABI document:
2042     // For calls that may call functions that use varargs or stdargs
2043     // (prototype-less calls or calls to functions containing ellipsis (...) in
2044     // the declaration) %al is used as hidden argument to specify the number
2045     // of SSE registers used. The contents of %al do not need to match exactly
2046     // the number of registers, but must be an ubound on the number of SSE
2047     // registers used and is in the range 0 - 8 inclusive.
2048
2049     // Count the number of XMM registers allocated.
2050     static const unsigned XMMArgRegs[] = {
2051       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2052       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2053     };
2054     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2055     assert((Subtarget->hasXMM() || !NumXMMRegs)
2056            && "SSE registers cannot be used when SSE is disabled");
2057
2058     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2059                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2060     InFlag = Chain.getValue(1);
2061   }
2062
2063
2064   // For tail calls lower the arguments to the 'real' stack slot.
2065   if (isTailCall) {
2066     // Force all the incoming stack arguments to be loaded from the stack
2067     // before any new outgoing arguments are stored to the stack, because the
2068     // outgoing stack slots may alias the incoming argument stack slots, and
2069     // the alias isn't otherwise explicit. This is slightly more conservative
2070     // than necessary, because it means that each store effectively depends
2071     // on every argument instead of just those arguments it would clobber.
2072     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2073
2074     SmallVector<SDValue, 8> MemOpChains2;
2075     SDValue FIN;
2076     int FI = 0;
2077     // Do not flag preceeding copytoreg stuff together with the following stuff.
2078     InFlag = SDValue();
2079     if (GuaranteedTailCallOpt) {
2080       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2081         CCValAssign &VA = ArgLocs[i];
2082         if (VA.isRegLoc())
2083           continue;
2084         assert(VA.isMemLoc());
2085         SDValue Arg = OutVals[i];
2086         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2087         // Create frame index.
2088         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2089         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2090         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2091         FIN = DAG.getFrameIndex(FI, getPointerTy());
2092
2093         if (Flags.isByVal()) {
2094           // Copy relative to framepointer.
2095           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2096           if (StackPtr.getNode() == 0)
2097             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2098                                           getPointerTy());
2099           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2100
2101           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2102                                                            ArgChain,
2103                                                            Flags, DAG, dl));
2104         } else {
2105           // Store relative to framepointer.
2106           MemOpChains2.push_back(
2107             DAG.getStore(ArgChain, dl, Arg, FIN,
2108                          MachinePointerInfo::getFixedStack(FI),
2109                          false, false, 0));
2110         }
2111       }
2112     }
2113
2114     if (!MemOpChains2.empty())
2115       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2116                           &MemOpChains2[0], MemOpChains2.size());
2117
2118     // Copy arguments to their registers.
2119     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2120       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2121                                RegsToPass[i].second, InFlag);
2122       InFlag = Chain.getValue(1);
2123     }
2124     InFlag =SDValue();
2125
2126     // Store the return address to the appropriate stack slot.
2127     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2128                                      FPDiff, dl);
2129   }
2130
2131   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2132     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2133     // In the 64-bit large code model, we have to make all calls
2134     // through a register, since the call instruction's 32-bit
2135     // pc-relative offset may not be large enough to hold the whole
2136     // address.
2137   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2138     // If the callee is a GlobalAddress node (quite common, every direct call
2139     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2140     // it.
2141
2142     // We should use extra load for direct calls to dllimported functions in
2143     // non-JIT mode.
2144     const GlobalValue *GV = G->getGlobal();
2145     if (!GV->hasDLLImportLinkage()) {
2146       unsigned char OpFlags = 0;
2147
2148       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2149       // external symbols most go through the PLT in PIC mode.  If the symbol
2150       // has hidden or protected visibility, or if it is static or local, then
2151       // we don't need to use the PLT - we can directly call it.
2152       if (Subtarget->isTargetELF() &&
2153           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2154           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2155         OpFlags = X86II::MO_PLT;
2156       } else if (Subtarget->isPICStyleStubAny() &&
2157                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2158                  Subtarget->getDarwinVers() < 9) {
2159         // PC-relative references to external symbols should go through $stub,
2160         // unless we're building with the leopard linker or later, which
2161         // automatically synthesizes these stubs.
2162         OpFlags = X86II::MO_DARWIN_STUB;
2163       }
2164
2165       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2166                                           G->getOffset(), OpFlags);
2167     }
2168   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2169     unsigned char OpFlags = 0;
2170
2171     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2172     // external symbols should go through the PLT.
2173     if (Subtarget->isTargetELF() &&
2174         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2175       OpFlags = X86II::MO_PLT;
2176     } else if (Subtarget->isPICStyleStubAny() &&
2177                Subtarget->getDarwinVers() < 9) {
2178       // PC-relative references to external symbols should go through $stub,
2179       // unless we're building with the leopard linker or later, which
2180       // automatically synthesizes these stubs.
2181       OpFlags = X86II::MO_DARWIN_STUB;
2182     }
2183
2184     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2185                                          OpFlags);
2186   }
2187
2188   // Returns a chain & a flag for retval copy to use.
2189   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2190   SmallVector<SDValue, 8> Ops;
2191
2192   if (!IsSibcall && isTailCall) {
2193     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2194                            DAG.getIntPtrConstant(0, true), InFlag);
2195     InFlag = Chain.getValue(1);
2196   }
2197
2198   Ops.push_back(Chain);
2199   Ops.push_back(Callee);
2200
2201   if (isTailCall)
2202     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2203
2204   // Add argument registers to the end of the list so that they are known live
2205   // into the call.
2206   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2207     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2208                                   RegsToPass[i].second.getValueType()));
2209
2210   // Add an implicit use GOT pointer in EBX.
2211   if (!isTailCall && Subtarget->isPICStyleGOT())
2212     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2213
2214   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2215   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2216     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2217
2218   if (InFlag.getNode())
2219     Ops.push_back(InFlag);
2220
2221   if (isTailCall) {
2222     // We used to do:
2223     //// If this is the first return lowered for this function, add the regs
2224     //// to the liveout set for the function.
2225     // This isn't right, although it's probably harmless on x86; liveouts
2226     // should be computed from returns not tail calls.  Consider a void
2227     // function making a tail call to a function returning int.
2228     return DAG.getNode(X86ISD::TC_RETURN, dl,
2229                        NodeTys, &Ops[0], Ops.size());
2230   }
2231
2232   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2233   InFlag = Chain.getValue(1);
2234
2235   // Create the CALLSEQ_END node.
2236   unsigned NumBytesForCalleeToPush;
2237   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2238     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2239   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2240     // If this is a call to a struct-return function, the callee
2241     // pops the hidden struct pointer, so we have to push it back.
2242     // This is common for Darwin/X86, Linux & Mingw32 targets.
2243     NumBytesForCalleeToPush = 4;
2244   else
2245     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2246
2247   // Returns a flag for retval copy to use.
2248   if (!IsSibcall) {
2249     Chain = DAG.getCALLSEQ_END(Chain,
2250                                DAG.getIntPtrConstant(NumBytes, true),
2251                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2252                                                      true),
2253                                InFlag);
2254     InFlag = Chain.getValue(1);
2255   }
2256
2257   // Handle result values, copying them out of physregs into vregs that we
2258   // return.
2259   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2260                          Ins, dl, DAG, InVals);
2261 }
2262
2263
2264 //===----------------------------------------------------------------------===//
2265 //                Fast Calling Convention (tail call) implementation
2266 //===----------------------------------------------------------------------===//
2267
2268 //  Like std call, callee cleans arguments, convention except that ECX is
2269 //  reserved for storing the tail called function address. Only 2 registers are
2270 //  free for argument passing (inreg). Tail call optimization is performed
2271 //  provided:
2272 //                * tailcallopt is enabled
2273 //                * caller/callee are fastcc
2274 //  On X86_64 architecture with GOT-style position independent code only local
2275 //  (within module) calls are supported at the moment.
2276 //  To keep the stack aligned according to platform abi the function
2277 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2278 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2279 //  If a tail called function callee has more arguments than the caller the
2280 //  caller needs to make sure that there is room to move the RETADDR to. This is
2281 //  achieved by reserving an area the size of the argument delta right after the
2282 //  original REtADDR, but before the saved framepointer or the spilled registers
2283 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2284 //  stack layout:
2285 //    arg1
2286 //    arg2
2287 //    RETADDR
2288 //    [ new RETADDR
2289 //      move area ]
2290 //    (possible EBP)
2291 //    ESI
2292 //    EDI
2293 //    local1 ..
2294
2295 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2296 /// for a 16 byte align requirement.
2297 unsigned
2298 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2299                                                SelectionDAG& DAG) const {
2300   MachineFunction &MF = DAG.getMachineFunction();
2301   const TargetMachine &TM = MF.getTarget();
2302   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2303   unsigned StackAlignment = TFI.getStackAlignment();
2304   uint64_t AlignMask = StackAlignment - 1;
2305   int64_t Offset = StackSize;
2306   uint64_t SlotSize = TD->getPointerSize();
2307   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2308     // Number smaller than 12 so just add the difference.
2309     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2310   } else {
2311     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2312     Offset = ((~AlignMask) & Offset) + StackAlignment +
2313       (StackAlignment-SlotSize);
2314   }
2315   return Offset;
2316 }
2317
2318 /// MatchingStackOffset - Return true if the given stack call argument is
2319 /// already available in the same position (relatively) of the caller's
2320 /// incoming argument stack.
2321 static
2322 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2323                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2324                          const X86InstrInfo *TII) {
2325   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2326   int FI = INT_MAX;
2327   if (Arg.getOpcode() == ISD::CopyFromReg) {
2328     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2329     if (!TargetRegisterInfo::isVirtualRegister(VR))
2330       return false;
2331     MachineInstr *Def = MRI->getVRegDef(VR);
2332     if (!Def)
2333       return false;
2334     if (!Flags.isByVal()) {
2335       if (!TII->isLoadFromStackSlot(Def, FI))
2336         return false;
2337     } else {
2338       unsigned Opcode = Def->getOpcode();
2339       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2340           Def->getOperand(1).isFI()) {
2341         FI = Def->getOperand(1).getIndex();
2342         Bytes = Flags.getByValSize();
2343       } else
2344         return false;
2345     }
2346   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2347     if (Flags.isByVal())
2348       // ByVal argument is passed in as a pointer but it's now being
2349       // dereferenced. e.g.
2350       // define @foo(%struct.X* %A) {
2351       //   tail call @bar(%struct.X* byval %A)
2352       // }
2353       return false;
2354     SDValue Ptr = Ld->getBasePtr();
2355     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2356     if (!FINode)
2357       return false;
2358     FI = FINode->getIndex();
2359   } else
2360     return false;
2361
2362   assert(FI != INT_MAX);
2363   if (!MFI->isFixedObjectIndex(FI))
2364     return false;
2365   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2366 }
2367
2368 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2369 /// for tail call optimization. Targets which want to do tail call
2370 /// optimization should implement this function.
2371 bool
2372 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2373                                                      CallingConv::ID CalleeCC,
2374                                                      bool isVarArg,
2375                                                      bool isCalleeStructRet,
2376                                                      bool isCallerStructRet,
2377                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2378                                     const SmallVectorImpl<SDValue> &OutVals,
2379                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2380                                                      SelectionDAG& DAG) const {
2381   if (!IsTailCallConvention(CalleeCC) &&
2382       CalleeCC != CallingConv::C)
2383     return false;
2384
2385   // If -tailcallopt is specified, make fastcc functions tail-callable.
2386   const MachineFunction &MF = DAG.getMachineFunction();
2387   const Function *CallerF = DAG.getMachineFunction().getFunction();
2388   CallingConv::ID CallerCC = CallerF->getCallingConv();
2389   bool CCMatch = CallerCC == CalleeCC;
2390
2391   if (GuaranteedTailCallOpt) {
2392     if (IsTailCallConvention(CalleeCC) && CCMatch)
2393       return true;
2394     return false;
2395   }
2396
2397   // Look for obvious safe cases to perform tail call optimization that do not
2398   // require ABI changes. This is what gcc calls sibcall.
2399
2400   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2401   // emit a special epilogue.
2402   if (RegInfo->needsStackRealignment(MF))
2403     return false;
2404
2405   // Do not sibcall optimize vararg calls unless the call site is not passing
2406   // any arguments.
2407   if (isVarArg && !Outs.empty())
2408     return false;
2409
2410   // Also avoid sibcall optimization if either caller or callee uses struct
2411   // return semantics.
2412   if (isCalleeStructRet || isCallerStructRet)
2413     return false;
2414
2415   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2416   // Therefore if it's not used by the call it is not safe to optimize this into
2417   // a sibcall.
2418   bool Unused = false;
2419   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2420     if (!Ins[i].Used) {
2421       Unused = true;
2422       break;
2423     }
2424   }
2425   if (Unused) {
2426     SmallVector<CCValAssign, 16> RVLocs;
2427     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2428                    RVLocs, *DAG.getContext());
2429     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2430     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2431       CCValAssign &VA = RVLocs[i];
2432       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2433         return false;
2434     }
2435   }
2436
2437   // If the calling conventions do not match, then we'd better make sure the
2438   // results are returned in the same way as what the caller expects.
2439   if (!CCMatch) {
2440     SmallVector<CCValAssign, 16> RVLocs1;
2441     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2442                     RVLocs1, *DAG.getContext());
2443     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2444
2445     SmallVector<CCValAssign, 16> RVLocs2;
2446     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2447                     RVLocs2, *DAG.getContext());
2448     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2449
2450     if (RVLocs1.size() != RVLocs2.size())
2451       return false;
2452     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2453       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2454         return false;
2455       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2456         return false;
2457       if (RVLocs1[i].isRegLoc()) {
2458         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2459           return false;
2460       } else {
2461         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2462           return false;
2463       }
2464     }
2465   }
2466
2467   // If the callee takes no arguments then go on to check the results of the
2468   // call.
2469   if (!Outs.empty()) {
2470     // Check if stack adjustment is needed. For now, do not do this if any
2471     // argument is passed on the stack.
2472     SmallVector<CCValAssign, 16> ArgLocs;
2473     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2474                    ArgLocs, *DAG.getContext());
2475     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2476     if (CCInfo.getNextStackOffset()) {
2477       MachineFunction &MF = DAG.getMachineFunction();
2478       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2479         return false;
2480
2481       // Check if the arguments are already laid out in the right way as
2482       // the caller's fixed stack objects.
2483       MachineFrameInfo *MFI = MF.getFrameInfo();
2484       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2485       const X86InstrInfo *TII =
2486         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2487       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2488         CCValAssign &VA = ArgLocs[i];
2489         SDValue Arg = OutVals[i];
2490         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2491         if (VA.getLocInfo() == CCValAssign::Indirect)
2492           return false;
2493         if (!VA.isRegLoc()) {
2494           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2495                                    MFI, MRI, TII))
2496             return false;
2497         }
2498       }
2499     }
2500
2501     // If the tailcall address may be in a register, then make sure it's
2502     // possible to register allocate for it. In 32-bit, the call address can
2503     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2504     // callee-saved registers are restored. These happen to be the same
2505     // registers used to pass 'inreg' arguments so watch out for those.
2506     if (!Subtarget->is64Bit() &&
2507         !isa<GlobalAddressSDNode>(Callee) &&
2508         !isa<ExternalSymbolSDNode>(Callee)) {
2509       unsigned NumInRegs = 0;
2510       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511         CCValAssign &VA = ArgLocs[i];
2512         if (!VA.isRegLoc())
2513           continue;
2514         unsigned Reg = VA.getLocReg();
2515         switch (Reg) {
2516         default: break;
2517         case X86::EAX: case X86::EDX: case X86::ECX:
2518           if (++NumInRegs == 3)
2519             return false;
2520           break;
2521         }
2522       }
2523     }
2524   }
2525
2526   // An stdcall caller is expected to clean up its arguments; the callee
2527   // isn't going to do that.
2528   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2529     return false;
2530
2531   return true;
2532 }
2533
2534 FastISel *
2535 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2536   return X86::createFastISel(funcInfo);
2537 }
2538
2539
2540 //===----------------------------------------------------------------------===//
2541 //                           Other Lowering Hooks
2542 //===----------------------------------------------------------------------===//
2543
2544 static bool MayFoldLoad(SDValue Op) {
2545   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2546 }
2547
2548 static bool MayFoldIntoStore(SDValue Op) {
2549   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2550 }
2551
2552 static bool isTargetShuffle(unsigned Opcode) {
2553   switch(Opcode) {
2554   default: return false;
2555   case X86ISD::PSHUFD:
2556   case X86ISD::PSHUFHW:
2557   case X86ISD::PSHUFLW:
2558   case X86ISD::SHUFPD:
2559   case X86ISD::PALIGN:
2560   case X86ISD::SHUFPS:
2561   case X86ISD::MOVLHPS:
2562   case X86ISD::MOVLHPD:
2563   case X86ISD::MOVHLPS:
2564   case X86ISD::MOVLPS:
2565   case X86ISD::MOVLPD:
2566   case X86ISD::MOVSHDUP:
2567   case X86ISD::MOVSLDUP:
2568   case X86ISD::MOVDDUP:
2569   case X86ISD::MOVSS:
2570   case X86ISD::MOVSD:
2571   case X86ISD::UNPCKLPS:
2572   case X86ISD::UNPCKLPD:
2573   case X86ISD::PUNPCKLWD:
2574   case X86ISD::PUNPCKLBW:
2575   case X86ISD::PUNPCKLDQ:
2576   case X86ISD::PUNPCKLQDQ:
2577   case X86ISD::UNPCKHPS:
2578   case X86ISD::UNPCKHPD:
2579   case X86ISD::PUNPCKHWD:
2580   case X86ISD::PUNPCKHBW:
2581   case X86ISD::PUNPCKHDQ:
2582   case X86ISD::PUNPCKHQDQ:
2583     return true;
2584   }
2585   return false;
2586 }
2587
2588 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2589                                                SDValue V1, SelectionDAG &DAG) {
2590   switch(Opc) {
2591   default: llvm_unreachable("Unknown x86 shuffle node");
2592   case X86ISD::MOVSHDUP:
2593   case X86ISD::MOVSLDUP:
2594   case X86ISD::MOVDDUP:
2595     return DAG.getNode(Opc, dl, VT, V1);
2596   }
2597
2598   return SDValue();
2599 }
2600
2601 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2602                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2603   switch(Opc) {
2604   default: llvm_unreachable("Unknown x86 shuffle node");
2605   case X86ISD::PSHUFD:
2606   case X86ISD::PSHUFHW:
2607   case X86ISD::PSHUFLW:
2608     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2609   }
2610
2611   return SDValue();
2612 }
2613
2614 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2615                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2616   switch(Opc) {
2617   default: llvm_unreachable("Unknown x86 shuffle node");
2618   case X86ISD::PALIGN:
2619   case X86ISD::SHUFPD:
2620   case X86ISD::SHUFPS:
2621     return DAG.getNode(Opc, dl, VT, V1, V2,
2622                        DAG.getConstant(TargetMask, MVT::i8));
2623   }
2624   return SDValue();
2625 }
2626
2627 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2628                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2629   switch(Opc) {
2630   default: llvm_unreachable("Unknown x86 shuffle node");
2631   case X86ISD::MOVLHPS:
2632   case X86ISD::MOVLHPD:
2633   case X86ISD::MOVHLPS:
2634   case X86ISD::MOVLPS:
2635   case X86ISD::MOVLPD:
2636   case X86ISD::MOVSS:
2637   case X86ISD::MOVSD:
2638   case X86ISD::UNPCKLPS:
2639   case X86ISD::UNPCKLPD:
2640   case X86ISD::PUNPCKLWD:
2641   case X86ISD::PUNPCKLBW:
2642   case X86ISD::PUNPCKLDQ:
2643   case X86ISD::PUNPCKLQDQ:
2644   case X86ISD::UNPCKHPS:
2645   case X86ISD::UNPCKHPD:
2646   case X86ISD::PUNPCKHWD:
2647   case X86ISD::PUNPCKHBW:
2648   case X86ISD::PUNPCKHDQ:
2649   case X86ISD::PUNPCKHQDQ:
2650     return DAG.getNode(Opc, dl, VT, V1, V2);
2651   }
2652   return SDValue();
2653 }
2654
2655 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2656   MachineFunction &MF = DAG.getMachineFunction();
2657   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2658   int ReturnAddrIndex = FuncInfo->getRAIndex();
2659
2660   if (ReturnAddrIndex == 0) {
2661     // Set up a frame object for the return address.
2662     uint64_t SlotSize = TD->getPointerSize();
2663     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2664                                                            false);
2665     FuncInfo->setRAIndex(ReturnAddrIndex);
2666   }
2667
2668   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2669 }
2670
2671
2672 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2673                                        bool hasSymbolicDisplacement) {
2674   // Offset should fit into 32 bit immediate field.
2675   if (!isInt<32>(Offset))
2676     return false;
2677
2678   // If we don't have a symbolic displacement - we don't have any extra
2679   // restrictions.
2680   if (!hasSymbolicDisplacement)
2681     return true;
2682
2683   // FIXME: Some tweaks might be needed for medium code model.
2684   if (M != CodeModel::Small && M != CodeModel::Kernel)
2685     return false;
2686
2687   // For small code model we assume that latest object is 16MB before end of 31
2688   // bits boundary. We may also accept pretty large negative constants knowing
2689   // that all objects are in the positive half of address space.
2690   if (M == CodeModel::Small && Offset < 16*1024*1024)
2691     return true;
2692
2693   // For kernel code model we know that all object resist in the negative half
2694   // of 32bits address space. We may not accept negative offsets, since they may
2695   // be just off and we may accept pretty large positive ones.
2696   if (M == CodeModel::Kernel && Offset > 0)
2697     return true;
2698
2699   return false;
2700 }
2701
2702 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2703 /// specific condition code, returning the condition code and the LHS/RHS of the
2704 /// comparison to make.
2705 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2706                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2707   if (!isFP) {
2708     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2709       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2710         // X > -1   -> X == 0, jump !sign.
2711         RHS = DAG.getConstant(0, RHS.getValueType());
2712         return X86::COND_NS;
2713       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2714         // X < 0   -> X == 0, jump on sign.
2715         return X86::COND_S;
2716       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2717         // X < 1   -> X <= 0
2718         RHS = DAG.getConstant(0, RHS.getValueType());
2719         return X86::COND_LE;
2720       }
2721     }
2722
2723     switch (SetCCOpcode) {
2724     default: llvm_unreachable("Invalid integer condition!");
2725     case ISD::SETEQ:  return X86::COND_E;
2726     case ISD::SETGT:  return X86::COND_G;
2727     case ISD::SETGE:  return X86::COND_GE;
2728     case ISD::SETLT:  return X86::COND_L;
2729     case ISD::SETLE:  return X86::COND_LE;
2730     case ISD::SETNE:  return X86::COND_NE;
2731     case ISD::SETULT: return X86::COND_B;
2732     case ISD::SETUGT: return X86::COND_A;
2733     case ISD::SETULE: return X86::COND_BE;
2734     case ISD::SETUGE: return X86::COND_AE;
2735     }
2736   }
2737
2738   // First determine if it is required or is profitable to flip the operands.
2739
2740   // If LHS is a foldable load, but RHS is not, flip the condition.
2741   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2742       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2743     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2744     std::swap(LHS, RHS);
2745   }
2746
2747   switch (SetCCOpcode) {
2748   default: break;
2749   case ISD::SETOLT:
2750   case ISD::SETOLE:
2751   case ISD::SETUGT:
2752   case ISD::SETUGE:
2753     std::swap(LHS, RHS);
2754     break;
2755   }
2756
2757   // On a floating point condition, the flags are set as follows:
2758   // ZF  PF  CF   op
2759   //  0 | 0 | 0 | X > Y
2760   //  0 | 0 | 1 | X < Y
2761   //  1 | 0 | 0 | X == Y
2762   //  1 | 1 | 1 | unordered
2763   switch (SetCCOpcode) {
2764   default: llvm_unreachable("Condcode should be pre-legalized away");
2765   case ISD::SETUEQ:
2766   case ISD::SETEQ:   return X86::COND_E;
2767   case ISD::SETOLT:              // flipped
2768   case ISD::SETOGT:
2769   case ISD::SETGT:   return X86::COND_A;
2770   case ISD::SETOLE:              // flipped
2771   case ISD::SETOGE:
2772   case ISD::SETGE:   return X86::COND_AE;
2773   case ISD::SETUGT:              // flipped
2774   case ISD::SETULT:
2775   case ISD::SETLT:   return X86::COND_B;
2776   case ISD::SETUGE:              // flipped
2777   case ISD::SETULE:
2778   case ISD::SETLE:   return X86::COND_BE;
2779   case ISD::SETONE:
2780   case ISD::SETNE:   return X86::COND_NE;
2781   case ISD::SETUO:   return X86::COND_P;
2782   case ISD::SETO:    return X86::COND_NP;
2783   case ISD::SETOEQ:
2784   case ISD::SETUNE:  return X86::COND_INVALID;
2785   }
2786 }
2787
2788 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2789 /// code. Current x86 isa includes the following FP cmov instructions:
2790 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2791 static bool hasFPCMov(unsigned X86CC) {
2792   switch (X86CC) {
2793   default:
2794     return false;
2795   case X86::COND_B:
2796   case X86::COND_BE:
2797   case X86::COND_E:
2798   case X86::COND_P:
2799   case X86::COND_A:
2800   case X86::COND_AE:
2801   case X86::COND_NE:
2802   case X86::COND_NP:
2803     return true;
2804   }
2805 }
2806
2807 /// isFPImmLegal - Returns true if the target can instruction select the
2808 /// specified FP immediate natively. If false, the legalizer will
2809 /// materialize the FP immediate as a load from a constant pool.
2810 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2811   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2812     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2813       return true;
2814   }
2815   return false;
2816 }
2817
2818 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2819 /// the specified range (L, H].
2820 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2821   return (Val < 0) || (Val >= Low && Val < Hi);
2822 }
2823
2824 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2825 /// specified value.
2826 static bool isUndefOrEqual(int Val, int CmpVal) {
2827   if (Val < 0 || Val == CmpVal)
2828     return true;
2829   return false;
2830 }
2831
2832 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2833 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2834 /// the second operand.
2835 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2836   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2837     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2838   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2839     return (Mask[0] < 2 && Mask[1] < 2);
2840   return false;
2841 }
2842
2843 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2844   SmallVector<int, 8> M;
2845   N->getMask(M);
2846   return ::isPSHUFDMask(M, N->getValueType(0));
2847 }
2848
2849 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2850 /// is suitable for input to PSHUFHW.
2851 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2852   if (VT != MVT::v8i16)
2853     return false;
2854
2855   // Lower quadword copied in order or undef.
2856   for (int i = 0; i != 4; ++i)
2857     if (Mask[i] >= 0 && Mask[i] != i)
2858       return false;
2859
2860   // Upper quadword shuffled.
2861   for (int i = 4; i != 8; ++i)
2862     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2863       return false;
2864
2865   return true;
2866 }
2867
2868 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2869   SmallVector<int, 8> M;
2870   N->getMask(M);
2871   return ::isPSHUFHWMask(M, N->getValueType(0));
2872 }
2873
2874 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2875 /// is suitable for input to PSHUFLW.
2876 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2877   if (VT != MVT::v8i16)
2878     return false;
2879
2880   // Upper quadword copied in order.
2881   for (int i = 4; i != 8; ++i)
2882     if (Mask[i] >= 0 && Mask[i] != i)
2883       return false;
2884
2885   // Lower quadword shuffled.
2886   for (int i = 0; i != 4; ++i)
2887     if (Mask[i] >= 4)
2888       return false;
2889
2890   return true;
2891 }
2892
2893 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2894   SmallVector<int, 8> M;
2895   N->getMask(M);
2896   return ::isPSHUFLWMask(M, N->getValueType(0));
2897 }
2898
2899 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2900 /// is suitable for input to PALIGNR.
2901 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2902                           bool hasSSSE3) {
2903   int i, e = VT.getVectorNumElements();
2904
2905   // Do not handle v2i64 / v2f64 shuffles with palignr.
2906   if (e < 4 || !hasSSSE3)
2907     return false;
2908
2909   for (i = 0; i != e; ++i)
2910     if (Mask[i] >= 0)
2911       break;
2912
2913   // All undef, not a palignr.
2914   if (i == e)
2915     return false;
2916
2917   // Determine if it's ok to perform a palignr with only the LHS, since we
2918   // don't have access to the actual shuffle elements to see if RHS is undef.
2919   bool Unary = Mask[i] < (int)e;
2920   bool NeedsUnary = false;
2921
2922   int s = Mask[i] - i;
2923
2924   // Check the rest of the elements to see if they are consecutive.
2925   for (++i; i != e; ++i) {
2926     int m = Mask[i];
2927     if (m < 0)
2928       continue;
2929
2930     Unary = Unary && (m < (int)e);
2931     NeedsUnary = NeedsUnary || (m < s);
2932
2933     if (NeedsUnary && !Unary)
2934       return false;
2935     if (Unary && m != ((s+i) & (e-1)))
2936       return false;
2937     if (!Unary && m != (s+i))
2938       return false;
2939   }
2940   return true;
2941 }
2942
2943 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2944   SmallVector<int, 8> M;
2945   N->getMask(M);
2946   return ::isPALIGNRMask(M, N->getValueType(0), true);
2947 }
2948
2949 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2950 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2951 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2952   int NumElems = VT.getVectorNumElements();
2953   if (NumElems != 2 && NumElems != 4)
2954     return false;
2955
2956   int Half = NumElems / 2;
2957   for (int i = 0; i < Half; ++i)
2958     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2959       return false;
2960   for (int i = Half; i < NumElems; ++i)
2961     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2962       return false;
2963
2964   return true;
2965 }
2966
2967 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2968   SmallVector<int, 8> M;
2969   N->getMask(M);
2970   return ::isSHUFPMask(M, N->getValueType(0));
2971 }
2972
2973 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2974 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2975 /// half elements to come from vector 1 (which would equal the dest.) and
2976 /// the upper half to come from vector 2.
2977 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2978   int NumElems = VT.getVectorNumElements();
2979
2980   if (NumElems != 2 && NumElems != 4)
2981     return false;
2982
2983   int Half = NumElems / 2;
2984   for (int i = 0; i < Half; ++i)
2985     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2986       return false;
2987   for (int i = Half; i < NumElems; ++i)
2988     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2989       return false;
2990   return true;
2991 }
2992
2993 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2994   SmallVector<int, 8> M;
2995   N->getMask(M);
2996   return isCommutedSHUFPMask(M, N->getValueType(0));
2997 }
2998
2999 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3000 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3001 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3002   if (N->getValueType(0).getVectorNumElements() != 4)
3003     return false;
3004
3005   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3006   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3007          isUndefOrEqual(N->getMaskElt(1), 7) &&
3008          isUndefOrEqual(N->getMaskElt(2), 2) &&
3009          isUndefOrEqual(N->getMaskElt(3), 3);
3010 }
3011
3012 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3013 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3014 /// <2, 3, 2, 3>
3015 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3016   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3017
3018   if (NumElems != 4)
3019     return false;
3020
3021   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3022   isUndefOrEqual(N->getMaskElt(1), 3) &&
3023   isUndefOrEqual(N->getMaskElt(2), 2) &&
3024   isUndefOrEqual(N->getMaskElt(3), 3);
3025 }
3026
3027 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3028 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3029 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3030   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3031
3032   if (NumElems != 2 && NumElems != 4)
3033     return false;
3034
3035   for (unsigned i = 0; i < NumElems/2; ++i)
3036     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3037       return false;
3038
3039   for (unsigned i = NumElems/2; i < NumElems; ++i)
3040     if (!isUndefOrEqual(N->getMaskElt(i), i))
3041       return false;
3042
3043   return true;
3044 }
3045
3046 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3047 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3048 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3049   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3050
3051   if (NumElems != 2 && NumElems != 4)
3052     return false;
3053
3054   for (unsigned i = 0; i < NumElems/2; ++i)
3055     if (!isUndefOrEqual(N->getMaskElt(i), i))
3056       return false;
3057
3058   for (unsigned i = 0; i < NumElems/2; ++i)
3059     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3060       return false;
3061
3062   return true;
3063 }
3064
3065 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3066 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3067 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3068                          bool V2IsSplat = false) {
3069   int NumElts = VT.getVectorNumElements();
3070   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3071     return false;
3072
3073   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3074     int BitI  = Mask[i];
3075     int BitI1 = Mask[i+1];
3076     if (!isUndefOrEqual(BitI, j))
3077       return false;
3078     if (V2IsSplat) {
3079       if (!isUndefOrEqual(BitI1, NumElts))
3080         return false;
3081     } else {
3082       if (!isUndefOrEqual(BitI1, j + NumElts))
3083         return false;
3084     }
3085   }
3086   return true;
3087 }
3088
3089 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3090   SmallVector<int, 8> M;
3091   N->getMask(M);
3092   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3093 }
3094
3095 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3096 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3097 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3098                          bool V2IsSplat = false) {
3099   int NumElts = VT.getVectorNumElements();
3100   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3101     return false;
3102
3103   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3104     int BitI  = Mask[i];
3105     int BitI1 = Mask[i+1];
3106     if (!isUndefOrEqual(BitI, j + NumElts/2))
3107       return false;
3108     if (V2IsSplat) {
3109       if (isUndefOrEqual(BitI1, NumElts))
3110         return false;
3111     } else {
3112       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3113         return false;
3114     }
3115   }
3116   return true;
3117 }
3118
3119 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3120   SmallVector<int, 8> M;
3121   N->getMask(M);
3122   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3123 }
3124
3125 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3126 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3127 /// <0, 0, 1, 1>
3128 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3129   int NumElems = VT.getVectorNumElements();
3130   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3131     return false;
3132
3133   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3134     int BitI  = Mask[i];
3135     int BitI1 = Mask[i+1];
3136     if (!isUndefOrEqual(BitI, j))
3137       return false;
3138     if (!isUndefOrEqual(BitI1, j))
3139       return false;
3140   }
3141   return true;
3142 }
3143
3144 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3145   SmallVector<int, 8> M;
3146   N->getMask(M);
3147   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3148 }
3149
3150 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3151 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3152 /// <2, 2, 3, 3>
3153 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3154   int NumElems = VT.getVectorNumElements();
3155   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3156     return false;
3157
3158   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3159     int BitI  = Mask[i];
3160     int BitI1 = Mask[i+1];
3161     if (!isUndefOrEqual(BitI, j))
3162       return false;
3163     if (!isUndefOrEqual(BitI1, j))
3164       return false;
3165   }
3166   return true;
3167 }
3168
3169 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3170   SmallVector<int, 8> M;
3171   N->getMask(M);
3172   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3173 }
3174
3175 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3176 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3177 /// MOVSD, and MOVD, i.e. setting the lowest element.
3178 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3179   if (VT.getVectorElementType().getSizeInBits() < 32)
3180     return false;
3181
3182   int NumElts = VT.getVectorNumElements();
3183
3184   if (!isUndefOrEqual(Mask[0], NumElts))
3185     return false;
3186
3187   for (int i = 1; i < NumElts; ++i)
3188     if (!isUndefOrEqual(Mask[i], i))
3189       return false;
3190
3191   return true;
3192 }
3193
3194 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3195   SmallVector<int, 8> M;
3196   N->getMask(M);
3197   return ::isMOVLMask(M, N->getValueType(0));
3198 }
3199
3200 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3201 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3202 /// element of vector 2 and the other elements to come from vector 1 in order.
3203 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3204                                bool V2IsSplat = false, bool V2IsUndef = false) {
3205   int NumOps = VT.getVectorNumElements();
3206   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3207     return false;
3208
3209   if (!isUndefOrEqual(Mask[0], 0))
3210     return false;
3211
3212   for (int i = 1; i < NumOps; ++i)
3213     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3214           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3215           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3216       return false;
3217
3218   return true;
3219 }
3220
3221 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3222                            bool V2IsUndef = false) {
3223   SmallVector<int, 8> M;
3224   N->getMask(M);
3225   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3226 }
3227
3228 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3229 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3230 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3231   if (N->getValueType(0).getVectorNumElements() != 4)
3232     return false;
3233
3234   // Expect 1, 1, 3, 3
3235   for (unsigned i = 0; i < 2; ++i) {
3236     int Elt = N->getMaskElt(i);
3237     if (Elt >= 0 && Elt != 1)
3238       return false;
3239   }
3240
3241   bool HasHi = false;
3242   for (unsigned i = 2; i < 4; ++i) {
3243     int Elt = N->getMaskElt(i);
3244     if (Elt >= 0 && Elt != 3)
3245       return false;
3246     if (Elt == 3)
3247       HasHi = true;
3248   }
3249   // Don't use movshdup if it can be done with a shufps.
3250   // FIXME: verify that matching u, u, 3, 3 is what we want.
3251   return HasHi;
3252 }
3253
3254 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3255 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3256 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3257   if (N->getValueType(0).getVectorNumElements() != 4)
3258     return false;
3259
3260   // Expect 0, 0, 2, 2
3261   for (unsigned i = 0; i < 2; ++i)
3262     if (N->getMaskElt(i) > 0)
3263       return false;
3264
3265   bool HasHi = false;
3266   for (unsigned i = 2; i < 4; ++i) {
3267     int Elt = N->getMaskElt(i);
3268     if (Elt >= 0 && Elt != 2)
3269       return false;
3270     if (Elt == 2)
3271       HasHi = true;
3272   }
3273   // Don't use movsldup if it can be done with a shufps.
3274   return HasHi;
3275 }
3276
3277 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3278 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3279 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3280   int e = N->getValueType(0).getVectorNumElements() / 2;
3281
3282   for (int i = 0; i < e; ++i)
3283     if (!isUndefOrEqual(N->getMaskElt(i), i))
3284       return false;
3285   for (int i = 0; i < e; ++i)
3286     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3287       return false;
3288   return true;
3289 }
3290
3291 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3292 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3293 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3295   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3296
3297   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3298   unsigned Mask = 0;
3299   for (int i = 0; i < NumOperands; ++i) {
3300     int Val = SVOp->getMaskElt(NumOperands-i-1);
3301     if (Val < 0) Val = 0;
3302     if (Val >= NumOperands) Val -= NumOperands;
3303     Mask |= Val;
3304     if (i != NumOperands - 1)
3305       Mask <<= Shift;
3306   }
3307   return Mask;
3308 }
3309
3310 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3311 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3312 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3314   unsigned Mask = 0;
3315   // 8 nodes, but we only care about the last 4.
3316   for (unsigned i = 7; i >= 4; --i) {
3317     int Val = SVOp->getMaskElt(i);
3318     if (Val >= 0)
3319       Mask |= (Val - 4);
3320     if (i != 4)
3321       Mask <<= 2;
3322   }
3323   return Mask;
3324 }
3325
3326 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3327 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3328 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3329   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3330   unsigned Mask = 0;
3331   // 8 nodes, but we only care about the first 4.
3332   for (int i = 3; i >= 0; --i) {
3333     int Val = SVOp->getMaskElt(i);
3334     if (Val >= 0)
3335       Mask |= Val;
3336     if (i != 0)
3337       Mask <<= 2;
3338   }
3339   return Mask;
3340 }
3341
3342 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3343 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3344 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3345   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3346   EVT VVT = N->getValueType(0);
3347   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3348   int Val = 0;
3349
3350   unsigned i, e;
3351   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3352     Val = SVOp->getMaskElt(i);
3353     if (Val >= 0)
3354       break;
3355   }
3356   return (Val - i) * EltSize;
3357 }
3358
3359 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3360 /// constant +0.0.
3361 bool X86::isZeroNode(SDValue Elt) {
3362   return ((isa<ConstantSDNode>(Elt) &&
3363            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3364           (isa<ConstantFPSDNode>(Elt) &&
3365            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3366 }
3367
3368 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3369 /// their permute mask.
3370 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3371                                     SelectionDAG &DAG) {
3372   EVT VT = SVOp->getValueType(0);
3373   unsigned NumElems = VT.getVectorNumElements();
3374   SmallVector<int, 8> MaskVec;
3375
3376   for (unsigned i = 0; i != NumElems; ++i) {
3377     int idx = SVOp->getMaskElt(i);
3378     if (idx < 0)
3379       MaskVec.push_back(idx);
3380     else if (idx < (int)NumElems)
3381       MaskVec.push_back(idx + NumElems);
3382     else
3383       MaskVec.push_back(idx - NumElems);
3384   }
3385   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3386                               SVOp->getOperand(0), &MaskVec[0]);
3387 }
3388
3389 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3390 /// the two vector operands have swapped position.
3391 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3392   unsigned NumElems = VT.getVectorNumElements();
3393   for (unsigned i = 0; i != NumElems; ++i) {
3394     int idx = Mask[i];
3395     if (idx < 0)
3396       continue;
3397     else if (idx < (int)NumElems)
3398       Mask[i] = idx + NumElems;
3399     else
3400       Mask[i] = idx - NumElems;
3401   }
3402 }
3403
3404 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3405 /// match movhlps. The lower half elements should come from upper half of
3406 /// V1 (and in order), and the upper half elements should come from the upper
3407 /// half of V2 (and in order).
3408 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3409   if (Op->getValueType(0).getVectorNumElements() != 4)
3410     return false;
3411   for (unsigned i = 0, e = 2; i != e; ++i)
3412     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3413       return false;
3414   for (unsigned i = 2; i != 4; ++i)
3415     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3416       return false;
3417   return true;
3418 }
3419
3420 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3421 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3422 /// required.
3423 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3424   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3425     return false;
3426   N = N->getOperand(0).getNode();
3427   if (!ISD::isNON_EXTLoad(N))
3428     return false;
3429   if (LD)
3430     *LD = cast<LoadSDNode>(N);
3431   return true;
3432 }
3433
3434 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3435 /// match movlp{s|d}. The lower half elements should come from lower half of
3436 /// V1 (and in order), and the upper half elements should come from the upper
3437 /// half of V2 (and in order). And since V1 will become the source of the
3438 /// MOVLP, it must be either a vector load or a scalar load to vector.
3439 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3440                                ShuffleVectorSDNode *Op) {
3441   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3442     return false;
3443   // Is V2 is a vector load, don't do this transformation. We will try to use
3444   // load folding shufps op.
3445   if (ISD::isNON_EXTLoad(V2))
3446     return false;
3447
3448   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3449
3450   if (NumElems != 2 && NumElems != 4)
3451     return false;
3452   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3453     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3454       return false;
3455   for (unsigned i = NumElems/2; i != NumElems; ++i)
3456     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3457       return false;
3458   return true;
3459 }
3460
3461 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3462 /// all the same.
3463 static bool isSplatVector(SDNode *N) {
3464   if (N->getOpcode() != ISD::BUILD_VECTOR)
3465     return false;
3466
3467   SDValue SplatValue = N->getOperand(0);
3468   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3469     if (N->getOperand(i) != SplatValue)
3470       return false;
3471   return true;
3472 }
3473
3474 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3475 /// to an zero vector.
3476 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3477 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3478   SDValue V1 = N->getOperand(0);
3479   SDValue V2 = N->getOperand(1);
3480   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3481   for (unsigned i = 0; i != NumElems; ++i) {
3482     int Idx = N->getMaskElt(i);
3483     if (Idx >= (int)NumElems) {
3484       unsigned Opc = V2.getOpcode();
3485       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3486         continue;
3487       if (Opc != ISD::BUILD_VECTOR ||
3488           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3489         return false;
3490     } else if (Idx >= 0) {
3491       unsigned Opc = V1.getOpcode();
3492       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3493         continue;
3494       if (Opc != ISD::BUILD_VECTOR ||
3495           !X86::isZeroNode(V1.getOperand(Idx)))
3496         return false;
3497     }
3498   }
3499   return true;
3500 }
3501
3502 /// getZeroVector - Returns a vector of specified type with all zero elements.
3503 ///
3504 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3505                              DebugLoc dl) {
3506   assert(VT.isVector() && "Expected a vector type");
3507
3508   // Always build SSE zero vectors as <4 x i32> bitcasted
3509   // to their dest type. This ensures they get CSE'd.
3510   SDValue Vec;
3511   if (VT.getSizeInBits() == 128) {  // SSE
3512     if (HasSSE2) {  // SSE2
3513       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3514       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3515     } else { // SSE1
3516       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3517       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3518     }
3519   } else if (VT.getSizeInBits() == 256) { // AVX
3520     // 256-bit logic and arithmetic instructions in AVX are
3521     // all floating-point, no support for integer ops. Default
3522     // to emitting fp zeroed vectors then.
3523     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3524     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3525     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3526   }
3527   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3528 }
3529
3530 /// getOnesVector - Returns a vector of specified type with all bits set.
3531 ///
3532 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3533   assert(VT.isVector() && "Expected a vector type");
3534
3535   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3536   // type.  This ensures they get CSE'd.
3537   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3538   SDValue Vec;
3539   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3540   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3541 }
3542
3543
3544 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3545 /// that point to V2 points to its first element.
3546 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3547   EVT VT = SVOp->getValueType(0);
3548   unsigned NumElems = VT.getVectorNumElements();
3549
3550   bool Changed = false;
3551   SmallVector<int, 8> MaskVec;
3552   SVOp->getMask(MaskVec);
3553
3554   for (unsigned i = 0; i != NumElems; ++i) {
3555     if (MaskVec[i] > (int)NumElems) {
3556       MaskVec[i] = NumElems;
3557       Changed = true;
3558     }
3559   }
3560   if (Changed)
3561     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3562                                 SVOp->getOperand(1), &MaskVec[0]);
3563   return SDValue(SVOp, 0);
3564 }
3565
3566 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3567 /// operation of specified width.
3568 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3569                        SDValue V2) {
3570   unsigned NumElems = VT.getVectorNumElements();
3571   SmallVector<int, 8> Mask;
3572   Mask.push_back(NumElems);
3573   for (unsigned i = 1; i != NumElems; ++i)
3574     Mask.push_back(i);
3575   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3576 }
3577
3578 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3579 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3580                           SDValue V2) {
3581   unsigned NumElems = VT.getVectorNumElements();
3582   SmallVector<int, 8> Mask;
3583   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3584     Mask.push_back(i);
3585     Mask.push_back(i + NumElems);
3586   }
3587   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3588 }
3589
3590 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3591 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3592                           SDValue V2) {
3593   unsigned NumElems = VT.getVectorNumElements();
3594   unsigned Half = NumElems/2;
3595   SmallVector<int, 8> Mask;
3596   for (unsigned i = 0; i != Half; ++i) {
3597     Mask.push_back(i + Half);
3598     Mask.push_back(i + NumElems + Half);
3599   }
3600   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3601 }
3602
3603 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3604 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3605   EVT PVT = MVT::v4f32;
3606   EVT VT = SV->getValueType(0);
3607   DebugLoc dl = SV->getDebugLoc();
3608   SDValue V1 = SV->getOperand(0);
3609   int NumElems = VT.getVectorNumElements();
3610   int EltNo = SV->getSplatIndex();
3611
3612   // unpack elements to the correct location
3613   while (NumElems > 4) {
3614     if (EltNo < NumElems/2) {
3615       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3616     } else {
3617       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3618       EltNo -= NumElems/2;
3619     }
3620     NumElems >>= 1;
3621   }
3622
3623   // Perform the splat.
3624   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3625   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3626   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3627   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3628 }
3629
3630 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3631 /// vector of zero or undef vector.  This produces a shuffle where the low
3632 /// element of V2 is swizzled into the zero/undef vector, landing at element
3633 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3634 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3635                                              bool isZero, bool HasSSE2,
3636                                              SelectionDAG &DAG) {
3637   EVT VT = V2.getValueType();
3638   SDValue V1 = isZero
3639     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3640   unsigned NumElems = VT.getVectorNumElements();
3641   SmallVector<int, 16> MaskVec;
3642   for (unsigned i = 0; i != NumElems; ++i)
3643     // If this is the insertion idx, put the low elt of V2 here.
3644     MaskVec.push_back(i == Idx ? NumElems : i);
3645   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3646 }
3647
3648 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3649 /// element of the result of the vector shuffle.
3650 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3651                             unsigned Depth) {
3652   if (Depth == 6)
3653     return SDValue();  // Limit search depth.
3654
3655   SDValue V = SDValue(N, 0);
3656   EVT VT = V.getValueType();
3657   unsigned Opcode = V.getOpcode();
3658
3659   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3660   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3661     Index = SV->getMaskElt(Index);
3662
3663     if (Index < 0)
3664       return DAG.getUNDEF(VT.getVectorElementType());
3665
3666     int NumElems = VT.getVectorNumElements();
3667     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3668     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3669   }
3670
3671   // Recurse into target specific vector shuffles to find scalars.
3672   if (isTargetShuffle(Opcode)) {
3673     int NumElems = VT.getVectorNumElements();
3674     SmallVector<unsigned, 16> ShuffleMask;
3675     SDValue ImmN;
3676
3677     switch(Opcode) {
3678     case X86ISD::SHUFPS:
3679     case X86ISD::SHUFPD:
3680       ImmN = N->getOperand(N->getNumOperands()-1);
3681       DecodeSHUFPSMask(NumElems,
3682                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3683                        ShuffleMask);
3684       break;
3685     case X86ISD::PUNPCKHBW:
3686     case X86ISD::PUNPCKHWD:
3687     case X86ISD::PUNPCKHDQ:
3688     case X86ISD::PUNPCKHQDQ:
3689       DecodePUNPCKHMask(NumElems, ShuffleMask);
3690       break;
3691     case X86ISD::UNPCKHPS:
3692     case X86ISD::UNPCKHPD:
3693       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3694       break;
3695     case X86ISD::PUNPCKLBW:
3696     case X86ISD::PUNPCKLWD:
3697     case X86ISD::PUNPCKLDQ:
3698     case X86ISD::PUNPCKLQDQ:
3699       DecodePUNPCKLMask(NumElems, ShuffleMask);
3700       break;
3701     case X86ISD::UNPCKLPS:
3702     case X86ISD::UNPCKLPD:
3703       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3704       break;
3705     case X86ISD::MOVHLPS:
3706       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3707       break;
3708     case X86ISD::MOVLHPS:
3709       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3710       break;
3711     case X86ISD::PSHUFD:
3712       ImmN = N->getOperand(N->getNumOperands()-1);
3713       DecodePSHUFMask(NumElems,
3714                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3715                       ShuffleMask);
3716       break;
3717     case X86ISD::PSHUFHW:
3718       ImmN = N->getOperand(N->getNumOperands()-1);
3719       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3720                         ShuffleMask);
3721       break;
3722     case X86ISD::PSHUFLW:
3723       ImmN = N->getOperand(N->getNumOperands()-1);
3724       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3725                         ShuffleMask);
3726       break;
3727     case X86ISD::MOVSS:
3728     case X86ISD::MOVSD: {
3729       // The index 0 always comes from the first element of the second source,
3730       // this is why MOVSS and MOVSD are used in the first place. The other
3731       // elements come from the other positions of the first source vector.
3732       unsigned OpNum = (Index == 0) ? 1 : 0;
3733       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3734                                  Depth+1);
3735     }
3736     default:
3737       assert("not implemented for target shuffle node");
3738       return SDValue();
3739     }
3740
3741     Index = ShuffleMask[Index];
3742     if (Index < 0)
3743       return DAG.getUNDEF(VT.getVectorElementType());
3744
3745     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3746     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3747                                Depth+1);
3748   }
3749
3750   // Actual nodes that may contain scalar elements
3751   if (Opcode == ISD::BITCAST) {
3752     V = V.getOperand(0);
3753     EVT SrcVT = V.getValueType();
3754     unsigned NumElems = VT.getVectorNumElements();
3755
3756     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3757       return SDValue();
3758   }
3759
3760   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3761     return (Index == 0) ? V.getOperand(0)
3762                           : DAG.getUNDEF(VT.getVectorElementType());
3763
3764   if (V.getOpcode() == ISD::BUILD_VECTOR)
3765     return V.getOperand(Index);
3766
3767   return SDValue();
3768 }
3769
3770 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3771 /// shuffle operation which come from a consecutively from a zero. The
3772 /// search can start in two diferent directions, from left or right.
3773 static
3774 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3775                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3776   int i = 0;
3777
3778   while (i < NumElems) {
3779     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3780     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3781     if (!(Elt.getNode() &&
3782          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3783       break;
3784     ++i;
3785   }
3786
3787   return i;
3788 }
3789
3790 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3791 /// MaskE correspond consecutively to elements from one of the vector operands,
3792 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3793 static
3794 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3795                               int OpIdx, int NumElems, unsigned &OpNum) {
3796   bool SeenV1 = false;
3797   bool SeenV2 = false;
3798
3799   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3800     int Idx = SVOp->getMaskElt(i);
3801     // Ignore undef indicies
3802     if (Idx < 0)
3803       continue;
3804
3805     if (Idx < NumElems)
3806       SeenV1 = true;
3807     else
3808       SeenV2 = true;
3809
3810     // Only accept consecutive elements from the same vector
3811     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3812       return false;
3813   }
3814
3815   OpNum = SeenV1 ? 0 : 1;
3816   return true;
3817 }
3818
3819 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3820 /// logical left shift of a vector.
3821 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3822                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3823   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3824   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3825               false /* check zeros from right */, DAG);
3826   unsigned OpSrc;
3827
3828   if (!NumZeros)
3829     return false;
3830
3831   // Considering the elements in the mask that are not consecutive zeros,
3832   // check if they consecutively come from only one of the source vectors.
3833   //
3834   //               V1 = {X, A, B, C}     0
3835   //                         \  \  \    /
3836   //   vector_shuffle V1, V2 <1, 2, 3, X>
3837   //
3838   if (!isShuffleMaskConsecutive(SVOp,
3839             0,                   // Mask Start Index
3840             NumElems-NumZeros-1, // Mask End Index
3841             NumZeros,            // Where to start looking in the src vector
3842             NumElems,            // Number of elements in vector
3843             OpSrc))              // Which source operand ?
3844     return false;
3845
3846   isLeft = false;
3847   ShAmt = NumZeros;
3848   ShVal = SVOp->getOperand(OpSrc);
3849   return true;
3850 }
3851
3852 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3853 /// logical left shift of a vector.
3854 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3855                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3856   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3857   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3858               true /* check zeros from left */, DAG);
3859   unsigned OpSrc;
3860
3861   if (!NumZeros)
3862     return false;
3863
3864   // Considering the elements in the mask that are not consecutive zeros,
3865   // check if they consecutively come from only one of the source vectors.
3866   //
3867   //                           0    { A, B, X, X } = V2
3868   //                          / \    /  /
3869   //   vector_shuffle V1, V2 <X, X, 4, 5>
3870   //
3871   if (!isShuffleMaskConsecutive(SVOp,
3872             NumZeros,     // Mask Start Index
3873             NumElems-1,   // Mask End Index
3874             0,            // Where to start looking in the src vector
3875             NumElems,     // Number of elements in vector
3876             OpSrc))       // Which source operand ?
3877     return false;
3878
3879   isLeft = true;
3880   ShAmt = NumZeros;
3881   ShVal = SVOp->getOperand(OpSrc);
3882   return true;
3883 }
3884
3885 /// isVectorShift - Returns true if the shuffle can be implemented as a
3886 /// logical left or right shift of a vector.
3887 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3888                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3889   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3890       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3891     return true;
3892
3893   return false;
3894 }
3895
3896 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3897 ///
3898 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3899                                        unsigned NumNonZero, unsigned NumZero,
3900                                        SelectionDAG &DAG,
3901                                        const TargetLowering &TLI) {
3902   if (NumNonZero > 8)
3903     return SDValue();
3904
3905   DebugLoc dl = Op.getDebugLoc();
3906   SDValue V(0, 0);
3907   bool First = true;
3908   for (unsigned i = 0; i < 16; ++i) {
3909     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3910     if (ThisIsNonZero && First) {
3911       if (NumZero)
3912         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3913       else
3914         V = DAG.getUNDEF(MVT::v8i16);
3915       First = false;
3916     }
3917
3918     if ((i & 1) != 0) {
3919       SDValue ThisElt(0, 0), LastElt(0, 0);
3920       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3921       if (LastIsNonZero) {
3922         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3923                               MVT::i16, Op.getOperand(i-1));
3924       }
3925       if (ThisIsNonZero) {
3926         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3927         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3928                               ThisElt, DAG.getConstant(8, MVT::i8));
3929         if (LastIsNonZero)
3930           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3931       } else
3932         ThisElt = LastElt;
3933
3934       if (ThisElt.getNode())
3935         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3936                         DAG.getIntPtrConstant(i/2));
3937     }
3938   }
3939
3940   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3941 }
3942
3943 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3944 ///
3945 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3946                                      unsigned NumNonZero, unsigned NumZero,
3947                                      SelectionDAG &DAG,
3948                                      const TargetLowering &TLI) {
3949   if (NumNonZero > 4)
3950     return SDValue();
3951
3952   DebugLoc dl = Op.getDebugLoc();
3953   SDValue V(0, 0);
3954   bool First = true;
3955   for (unsigned i = 0; i < 8; ++i) {
3956     bool isNonZero = (NonZeros & (1 << i)) != 0;
3957     if (isNonZero) {
3958       if (First) {
3959         if (NumZero)
3960           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3961         else
3962           V = DAG.getUNDEF(MVT::v8i16);
3963         First = false;
3964       }
3965       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3966                       MVT::v8i16, V, Op.getOperand(i),
3967                       DAG.getIntPtrConstant(i));
3968     }
3969   }
3970
3971   return V;
3972 }
3973
3974 /// getVShift - Return a vector logical shift node.
3975 ///
3976 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3977                          unsigned NumBits, SelectionDAG &DAG,
3978                          const TargetLowering &TLI, DebugLoc dl) {
3979   EVT ShVT = MVT::v2i64;
3980   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3981   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3982   return DAG.getNode(ISD::BITCAST, dl, VT,
3983                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3984                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3985 }
3986
3987 SDValue
3988 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3989                                           SelectionDAG &DAG) const {
3990
3991   // Check if the scalar load can be widened into a vector load. And if
3992   // the address is "base + cst" see if the cst can be "absorbed" into
3993   // the shuffle mask.
3994   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3995     SDValue Ptr = LD->getBasePtr();
3996     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3997       return SDValue();
3998     EVT PVT = LD->getValueType(0);
3999     if (PVT != MVT::i32 && PVT != MVT::f32)
4000       return SDValue();
4001
4002     int FI = -1;
4003     int64_t Offset = 0;
4004     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4005       FI = FINode->getIndex();
4006       Offset = 0;
4007     } else if (Ptr.getOpcode() == ISD::ADD &&
4008                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4009                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4010       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4011       Offset = Ptr.getConstantOperandVal(1);
4012       Ptr = Ptr.getOperand(0);
4013     } else {
4014       return SDValue();
4015     }
4016
4017     SDValue Chain = LD->getChain();
4018     // Make sure the stack object alignment is at least 16.
4019     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4020     if (DAG.InferPtrAlignment(Ptr) < 16) {
4021       if (MFI->isFixedObjectIndex(FI)) {
4022         // Can't change the alignment. FIXME: It's possible to compute
4023         // the exact stack offset and reference FI + adjust offset instead.
4024         // If someone *really* cares about this. That's the way to implement it.
4025         return SDValue();
4026       } else {
4027         MFI->setObjectAlignment(FI, 16);
4028       }
4029     }
4030
4031     // (Offset % 16) must be multiple of 4. Then address is then
4032     // Ptr + (Offset & ~15).
4033     if (Offset < 0)
4034       return SDValue();
4035     if ((Offset % 16) & 3)
4036       return SDValue();
4037     int64_t StartOffset = Offset & ~15;
4038     if (StartOffset)
4039       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4040                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4041
4042     int EltNo = (Offset - StartOffset) >> 2;
4043     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4044     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4045     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4046                              LD->getPointerInfo().getWithOffset(StartOffset),
4047                              false, false, 0);
4048     // Canonicalize it to a v4i32 shuffle.
4049     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4050     return DAG.getNode(ISD::BITCAST, dl, VT,
4051                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4052                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4053   }
4054
4055   return SDValue();
4056 }
4057
4058 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4059 /// vector of type 'VT', see if the elements can be replaced by a single large
4060 /// load which has the same value as a build_vector whose operands are 'elts'.
4061 ///
4062 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4063 ///
4064 /// FIXME: we'd also like to handle the case where the last elements are zero
4065 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4066 /// There's even a handy isZeroNode for that purpose.
4067 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4068                                         DebugLoc &DL, SelectionDAG &DAG) {
4069   EVT EltVT = VT.getVectorElementType();
4070   unsigned NumElems = Elts.size();
4071
4072   LoadSDNode *LDBase = NULL;
4073   unsigned LastLoadedElt = -1U;
4074
4075   // For each element in the initializer, see if we've found a load or an undef.
4076   // If we don't find an initial load element, or later load elements are
4077   // non-consecutive, bail out.
4078   for (unsigned i = 0; i < NumElems; ++i) {
4079     SDValue Elt = Elts[i];
4080
4081     if (!Elt.getNode() ||
4082         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4083       return SDValue();
4084     if (!LDBase) {
4085       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4086         return SDValue();
4087       LDBase = cast<LoadSDNode>(Elt.getNode());
4088       LastLoadedElt = i;
4089       continue;
4090     }
4091     if (Elt.getOpcode() == ISD::UNDEF)
4092       continue;
4093
4094     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4095     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4096       return SDValue();
4097     LastLoadedElt = i;
4098   }
4099
4100   // If we have found an entire vector of loads and undefs, then return a large
4101   // load of the entire vector width starting at the base pointer.  If we found
4102   // consecutive loads for the low half, generate a vzext_load node.
4103   if (LastLoadedElt == NumElems - 1) {
4104     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4105       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4106                          LDBase->getPointerInfo(),
4107                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4108     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4109                        LDBase->getPointerInfo(),
4110                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4111                        LDBase->getAlignment());
4112   } else if (NumElems == 4 && LastLoadedElt == 1) {
4113     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4114     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4115     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4116                                               Ops, 2, MVT::i32,
4117                                               LDBase->getMemOperand());
4118     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4119   }
4120   return SDValue();
4121 }
4122
4123 SDValue
4124 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4125   DebugLoc dl = Op.getDebugLoc();
4126   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4127   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4128   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4129   // is present, so AllOnes is ignored.
4130   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4131       (Op.getValueType().getSizeInBits() != 256 &&
4132        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4133     // Canonicalize this to <4 x i32> (SSE) to
4134     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4135     // eliminated on x86-32 hosts.
4136     if (Op.getValueType() == MVT::v4i32)
4137       return Op;
4138
4139     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4140       return getOnesVector(Op.getValueType(), DAG, dl);
4141     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4142   }
4143
4144   EVT VT = Op.getValueType();
4145   EVT ExtVT = VT.getVectorElementType();
4146   unsigned EVTBits = ExtVT.getSizeInBits();
4147
4148   unsigned NumElems = Op.getNumOperands();
4149   unsigned NumZero  = 0;
4150   unsigned NumNonZero = 0;
4151   unsigned NonZeros = 0;
4152   bool IsAllConstants = true;
4153   SmallSet<SDValue, 8> Values;
4154   for (unsigned i = 0; i < NumElems; ++i) {
4155     SDValue Elt = Op.getOperand(i);
4156     if (Elt.getOpcode() == ISD::UNDEF)
4157       continue;
4158     Values.insert(Elt);
4159     if (Elt.getOpcode() != ISD::Constant &&
4160         Elt.getOpcode() != ISD::ConstantFP)
4161       IsAllConstants = false;
4162     if (X86::isZeroNode(Elt))
4163       NumZero++;
4164     else {
4165       NonZeros |= (1 << i);
4166       NumNonZero++;
4167     }
4168   }
4169
4170   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4171   if (NumNonZero == 0)
4172     return DAG.getUNDEF(VT);
4173
4174   // Special case for single non-zero, non-undef, element.
4175   if (NumNonZero == 1) {
4176     unsigned Idx = CountTrailingZeros_32(NonZeros);
4177     SDValue Item = Op.getOperand(Idx);
4178
4179     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4180     // the value are obviously zero, truncate the value to i32 and do the
4181     // insertion that way.  Only do this if the value is non-constant or if the
4182     // value is a constant being inserted into element 0.  It is cheaper to do
4183     // a constant pool load than it is to do a movd + shuffle.
4184     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4185         (!IsAllConstants || Idx == 0)) {
4186       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4187         // Handle SSE only.
4188         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4189         EVT VecVT = MVT::v4i32;
4190         unsigned VecElts = 4;
4191
4192         // Truncate the value (which may itself be a constant) to i32, and
4193         // convert it to a vector with movd (S2V+shuffle to zero extend).
4194         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4195         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4196         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4197                                            Subtarget->hasSSE2(), DAG);
4198
4199         // Now we have our 32-bit value zero extended in the low element of
4200         // a vector.  If Idx != 0, swizzle it into place.
4201         if (Idx != 0) {
4202           SmallVector<int, 4> Mask;
4203           Mask.push_back(Idx);
4204           for (unsigned i = 1; i != VecElts; ++i)
4205             Mask.push_back(i);
4206           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4207                                       DAG.getUNDEF(Item.getValueType()),
4208                                       &Mask[0]);
4209         }
4210         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4211       }
4212     }
4213
4214     // If we have a constant or non-constant insertion into the low element of
4215     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4216     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4217     // depending on what the source datatype is.
4218     if (Idx == 0) {
4219       if (NumZero == 0) {
4220         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4221       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4222           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4223         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4224         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4225         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4226                                            DAG);
4227       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4228         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4229         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4230         EVT MiddleVT = MVT::v4i32;
4231         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4232         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4233                                            Subtarget->hasSSE2(), DAG);
4234         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4235       }
4236     }
4237
4238     // Is it a vector logical left shift?
4239     if (NumElems == 2 && Idx == 1 &&
4240         X86::isZeroNode(Op.getOperand(0)) &&
4241         !X86::isZeroNode(Op.getOperand(1))) {
4242       unsigned NumBits = VT.getSizeInBits();
4243       return getVShift(true, VT,
4244                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4245                                    VT, Op.getOperand(1)),
4246                        NumBits/2, DAG, *this, dl);
4247     }
4248
4249     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4250       return SDValue();
4251
4252     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4253     // is a non-constant being inserted into an element other than the low one,
4254     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4255     // movd/movss) to move this into the low element, then shuffle it into
4256     // place.
4257     if (EVTBits == 32) {
4258       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4259
4260       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4261       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4262                                          Subtarget->hasSSE2(), DAG);
4263       SmallVector<int, 8> MaskVec;
4264       for (unsigned i = 0; i < NumElems; i++)
4265         MaskVec.push_back(i == Idx ? 0 : 1);
4266       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4267     }
4268   }
4269
4270   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4271   if (Values.size() == 1) {
4272     if (EVTBits == 32) {
4273       // Instead of a shuffle like this:
4274       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4275       // Check if it's possible to issue this instead.
4276       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4277       unsigned Idx = CountTrailingZeros_32(NonZeros);
4278       SDValue Item = Op.getOperand(Idx);
4279       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4280         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4281     }
4282     return SDValue();
4283   }
4284
4285   // A vector full of immediates; various special cases are already
4286   // handled, so this is best done with a single constant-pool load.
4287   if (IsAllConstants)
4288     return SDValue();
4289
4290   // Let legalizer expand 2-wide build_vectors.
4291   if (EVTBits == 64) {
4292     if (NumNonZero == 1) {
4293       // One half is zero or undef.
4294       unsigned Idx = CountTrailingZeros_32(NonZeros);
4295       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4296                                  Op.getOperand(Idx));
4297       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4298                                          Subtarget->hasSSE2(), DAG);
4299     }
4300     return SDValue();
4301   }
4302
4303   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4304   if (EVTBits == 8 && NumElems == 16) {
4305     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4306                                         *this);
4307     if (V.getNode()) return V;
4308   }
4309
4310   if (EVTBits == 16 && NumElems == 8) {
4311     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4312                                       *this);
4313     if (V.getNode()) return V;
4314   }
4315
4316   // If element VT is == 32 bits, turn it into a number of shuffles.
4317   SmallVector<SDValue, 8> V;
4318   V.resize(NumElems);
4319   if (NumElems == 4 && NumZero > 0) {
4320     for (unsigned i = 0; i < 4; ++i) {
4321       bool isZero = !(NonZeros & (1 << i));
4322       if (isZero)
4323         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4324       else
4325         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4326     }
4327
4328     for (unsigned i = 0; i < 2; ++i) {
4329       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4330         default: break;
4331         case 0:
4332           V[i] = V[i*2];  // Must be a zero vector.
4333           break;
4334         case 1:
4335           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4336           break;
4337         case 2:
4338           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4339           break;
4340         case 3:
4341           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4342           break;
4343       }
4344     }
4345
4346     SmallVector<int, 8> MaskVec;
4347     bool Reverse = (NonZeros & 0x3) == 2;
4348     for (unsigned i = 0; i < 2; ++i)
4349       MaskVec.push_back(Reverse ? 1-i : i);
4350     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4351     for (unsigned i = 0; i < 2; ++i)
4352       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4353     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4354   }
4355
4356   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4357     // Check for a build vector of consecutive loads.
4358     for (unsigned i = 0; i < NumElems; ++i)
4359       V[i] = Op.getOperand(i);
4360
4361     // Check for elements which are consecutive loads.
4362     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4363     if (LD.getNode())
4364       return LD;
4365
4366     // For SSE 4.1, use insertps to put the high elements into the low element.
4367     if (getSubtarget()->hasSSE41()) {
4368       SDValue Result;
4369       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4370         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4371       else
4372         Result = DAG.getUNDEF(VT);
4373
4374       for (unsigned i = 1; i < NumElems; ++i) {
4375         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4376         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4377                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4378       }
4379       return Result;
4380     }
4381
4382     // Otherwise, expand into a number of unpckl*, start by extending each of
4383     // our (non-undef) elements to the full vector width with the element in the
4384     // bottom slot of the vector (which generates no code for SSE).
4385     for (unsigned i = 0; i < NumElems; ++i) {
4386       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4387         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4388       else
4389         V[i] = DAG.getUNDEF(VT);
4390     }
4391
4392     // Next, we iteratively mix elements, e.g. for v4f32:
4393     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4394     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4395     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4396     unsigned EltStride = NumElems >> 1;
4397     while (EltStride != 0) {
4398       for (unsigned i = 0; i < EltStride; ++i) {
4399         // If V[i+EltStride] is undef and this is the first round of mixing,
4400         // then it is safe to just drop this shuffle: V[i] is already in the
4401         // right place, the one element (since it's the first round) being
4402         // inserted as undef can be dropped.  This isn't safe for successive
4403         // rounds because they will permute elements within both vectors.
4404         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4405             EltStride == NumElems/2)
4406           continue;
4407
4408         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4409       }
4410       EltStride >>= 1;
4411     }
4412     return V[0];
4413   }
4414   return SDValue();
4415 }
4416
4417 SDValue
4418 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4419   // We support concatenate two MMX registers and place them in a MMX
4420   // register.  This is better than doing a stack convert.
4421   DebugLoc dl = Op.getDebugLoc();
4422   EVT ResVT = Op.getValueType();
4423   assert(Op.getNumOperands() == 2);
4424   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4425          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4426   int Mask[2];
4427   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4428   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4429   InVec = Op.getOperand(1);
4430   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4431     unsigned NumElts = ResVT.getVectorNumElements();
4432     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4433     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4434                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4435   } else {
4436     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4437     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4438     Mask[0] = 0; Mask[1] = 2;
4439     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4440   }
4441   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4442 }
4443
4444 // v8i16 shuffles - Prefer shuffles in the following order:
4445 // 1. [all]   pshuflw, pshufhw, optional move
4446 // 2. [ssse3] 1 x pshufb
4447 // 3. [ssse3] 2 x pshufb + 1 x por
4448 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4449 SDValue
4450 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4451                                             SelectionDAG &DAG) const {
4452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4453   SDValue V1 = SVOp->getOperand(0);
4454   SDValue V2 = SVOp->getOperand(1);
4455   DebugLoc dl = SVOp->getDebugLoc();
4456   SmallVector<int, 8> MaskVals;
4457
4458   // Determine if more than 1 of the words in each of the low and high quadwords
4459   // of the result come from the same quadword of one of the two inputs.  Undef
4460   // mask values count as coming from any quadword, for better codegen.
4461   SmallVector<unsigned, 4> LoQuad(4);
4462   SmallVector<unsigned, 4> HiQuad(4);
4463   BitVector InputQuads(4);
4464   for (unsigned i = 0; i < 8; ++i) {
4465     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4466     int EltIdx = SVOp->getMaskElt(i);
4467     MaskVals.push_back(EltIdx);
4468     if (EltIdx < 0) {
4469       ++Quad[0];
4470       ++Quad[1];
4471       ++Quad[2];
4472       ++Quad[3];
4473       continue;
4474     }
4475     ++Quad[EltIdx / 4];
4476     InputQuads.set(EltIdx / 4);
4477   }
4478
4479   int BestLoQuad = -1;
4480   unsigned MaxQuad = 1;
4481   for (unsigned i = 0; i < 4; ++i) {
4482     if (LoQuad[i] > MaxQuad) {
4483       BestLoQuad = i;
4484       MaxQuad = LoQuad[i];
4485     }
4486   }
4487
4488   int BestHiQuad = -1;
4489   MaxQuad = 1;
4490   for (unsigned i = 0; i < 4; ++i) {
4491     if (HiQuad[i] > MaxQuad) {
4492       BestHiQuad = i;
4493       MaxQuad = HiQuad[i];
4494     }
4495   }
4496
4497   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4498   // of the two input vectors, shuffle them into one input vector so only a
4499   // single pshufb instruction is necessary. If There are more than 2 input
4500   // quads, disable the next transformation since it does not help SSSE3.
4501   bool V1Used = InputQuads[0] || InputQuads[1];
4502   bool V2Used = InputQuads[2] || InputQuads[3];
4503   if (Subtarget->hasSSSE3()) {
4504     if (InputQuads.count() == 2 && V1Used && V2Used) {
4505       BestLoQuad = InputQuads.find_first();
4506       BestHiQuad = InputQuads.find_next(BestLoQuad);
4507     }
4508     if (InputQuads.count() > 2) {
4509       BestLoQuad = -1;
4510       BestHiQuad = -1;
4511     }
4512   }
4513
4514   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4515   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4516   // words from all 4 input quadwords.
4517   SDValue NewV;
4518   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4519     SmallVector<int, 8> MaskV;
4520     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4521     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4522     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4523                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4524                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4525     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4526
4527     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4528     // source words for the shuffle, to aid later transformations.
4529     bool AllWordsInNewV = true;
4530     bool InOrder[2] = { true, true };
4531     for (unsigned i = 0; i != 8; ++i) {
4532       int idx = MaskVals[i];
4533       if (idx != (int)i)
4534         InOrder[i/4] = false;
4535       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4536         continue;
4537       AllWordsInNewV = false;
4538       break;
4539     }
4540
4541     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4542     if (AllWordsInNewV) {
4543       for (int i = 0; i != 8; ++i) {
4544         int idx = MaskVals[i];
4545         if (idx < 0)
4546           continue;
4547         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4548         if ((idx != i) && idx < 4)
4549           pshufhw = false;
4550         if ((idx != i) && idx > 3)
4551           pshuflw = false;
4552       }
4553       V1 = NewV;
4554       V2Used = false;
4555       BestLoQuad = 0;
4556       BestHiQuad = 1;
4557     }
4558
4559     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4560     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4561     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4562       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4563       unsigned TargetMask = 0;
4564       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4565                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4566       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4567                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4568       V1 = NewV.getOperand(0);
4569       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4570     }
4571   }
4572
4573   // If we have SSSE3, and all words of the result are from 1 input vector,
4574   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4575   // is present, fall back to case 4.
4576   if (Subtarget->hasSSSE3()) {
4577     SmallVector<SDValue,16> pshufbMask;
4578
4579     // If we have elements from both input vectors, set the high bit of the
4580     // shuffle mask element to zero out elements that come from V2 in the V1
4581     // mask, and elements that come from V1 in the V2 mask, so that the two
4582     // results can be OR'd together.
4583     bool TwoInputs = V1Used && V2Used;
4584     for (unsigned i = 0; i != 8; ++i) {
4585       int EltIdx = MaskVals[i] * 2;
4586       if (TwoInputs && (EltIdx >= 16)) {
4587         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4588         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4589         continue;
4590       }
4591       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4592       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4593     }
4594     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4595     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4596                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4597                                  MVT::v16i8, &pshufbMask[0], 16));
4598     if (!TwoInputs)
4599       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4600
4601     // Calculate the shuffle mask for the second input, shuffle it, and
4602     // OR it with the first shuffled input.
4603     pshufbMask.clear();
4604     for (unsigned i = 0; i != 8; ++i) {
4605       int EltIdx = MaskVals[i] * 2;
4606       if (EltIdx < 16) {
4607         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4608         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4609         continue;
4610       }
4611       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4612       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4613     }
4614     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4615     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4616                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4617                                  MVT::v16i8, &pshufbMask[0], 16));
4618     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4619     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4620   }
4621
4622   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4623   // and update MaskVals with new element order.
4624   BitVector InOrder(8);
4625   if (BestLoQuad >= 0) {
4626     SmallVector<int, 8> MaskV;
4627     for (int i = 0; i != 4; ++i) {
4628       int idx = MaskVals[i];
4629       if (idx < 0) {
4630         MaskV.push_back(-1);
4631         InOrder.set(i);
4632       } else if ((idx / 4) == BestLoQuad) {
4633         MaskV.push_back(idx & 3);
4634         InOrder.set(i);
4635       } else {
4636         MaskV.push_back(-1);
4637       }
4638     }
4639     for (unsigned i = 4; i != 8; ++i)
4640       MaskV.push_back(i);
4641     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4642                                 &MaskV[0]);
4643
4644     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4645       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4646                                NewV.getOperand(0),
4647                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4648                                DAG);
4649   }
4650
4651   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4652   // and update MaskVals with the new element order.
4653   if (BestHiQuad >= 0) {
4654     SmallVector<int, 8> MaskV;
4655     for (unsigned i = 0; i != 4; ++i)
4656       MaskV.push_back(i);
4657     for (unsigned i = 4; i != 8; ++i) {
4658       int idx = MaskVals[i];
4659       if (idx < 0) {
4660         MaskV.push_back(-1);
4661         InOrder.set(i);
4662       } else if ((idx / 4) == BestHiQuad) {
4663         MaskV.push_back((idx & 3) + 4);
4664         InOrder.set(i);
4665       } else {
4666         MaskV.push_back(-1);
4667       }
4668     }
4669     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4670                                 &MaskV[0]);
4671
4672     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4673       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4674                               NewV.getOperand(0),
4675                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4676                               DAG);
4677   }
4678
4679   // In case BestHi & BestLo were both -1, which means each quadword has a word
4680   // from each of the four input quadwords, calculate the InOrder bitvector now
4681   // before falling through to the insert/extract cleanup.
4682   if (BestLoQuad == -1 && BestHiQuad == -1) {
4683     NewV = V1;
4684     for (int i = 0; i != 8; ++i)
4685       if (MaskVals[i] < 0 || MaskVals[i] == i)
4686         InOrder.set(i);
4687   }
4688
4689   // The other elements are put in the right place using pextrw and pinsrw.
4690   for (unsigned i = 0; i != 8; ++i) {
4691     if (InOrder[i])
4692       continue;
4693     int EltIdx = MaskVals[i];
4694     if (EltIdx < 0)
4695       continue;
4696     SDValue ExtOp = (EltIdx < 8)
4697     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4698                   DAG.getIntPtrConstant(EltIdx))
4699     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4700                   DAG.getIntPtrConstant(EltIdx - 8));
4701     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4702                        DAG.getIntPtrConstant(i));
4703   }
4704   return NewV;
4705 }
4706
4707 // v16i8 shuffles - Prefer shuffles in the following order:
4708 // 1. [ssse3] 1 x pshufb
4709 // 2. [ssse3] 2 x pshufb + 1 x por
4710 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4711 static
4712 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4713                                  SelectionDAG &DAG,
4714                                  const X86TargetLowering &TLI) {
4715   SDValue V1 = SVOp->getOperand(0);
4716   SDValue V2 = SVOp->getOperand(1);
4717   DebugLoc dl = SVOp->getDebugLoc();
4718   SmallVector<int, 16> MaskVals;
4719   SVOp->getMask(MaskVals);
4720
4721   // If we have SSSE3, case 1 is generated when all result bytes come from
4722   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4723   // present, fall back to case 3.
4724   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4725   bool V1Only = true;
4726   bool V2Only = true;
4727   for (unsigned i = 0; i < 16; ++i) {
4728     int EltIdx = MaskVals[i];
4729     if (EltIdx < 0)
4730       continue;
4731     if (EltIdx < 16)
4732       V2Only = false;
4733     else
4734       V1Only = false;
4735   }
4736
4737   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4738   if (TLI.getSubtarget()->hasSSSE3()) {
4739     SmallVector<SDValue,16> pshufbMask;
4740
4741     // If all result elements are from one input vector, then only translate
4742     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4743     //
4744     // Otherwise, we have elements from both input vectors, and must zero out
4745     // elements that come from V2 in the first mask, and V1 in the second mask
4746     // so that we can OR them together.
4747     bool TwoInputs = !(V1Only || V2Only);
4748     for (unsigned i = 0; i != 16; ++i) {
4749       int EltIdx = MaskVals[i];
4750       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4751         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4752         continue;
4753       }
4754       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4755     }
4756     // If all the elements are from V2, assign it to V1 and return after
4757     // building the first pshufb.
4758     if (V2Only)
4759       V1 = V2;
4760     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4761                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4762                                  MVT::v16i8, &pshufbMask[0], 16));
4763     if (!TwoInputs)
4764       return V1;
4765
4766     // Calculate the shuffle mask for the second input, shuffle it, and
4767     // OR it with the first shuffled input.
4768     pshufbMask.clear();
4769     for (unsigned i = 0; i != 16; ++i) {
4770       int EltIdx = MaskVals[i];
4771       if (EltIdx < 16) {
4772         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4773         continue;
4774       }
4775       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4776     }
4777     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4778                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4779                                  MVT::v16i8, &pshufbMask[0], 16));
4780     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4781   }
4782
4783   // No SSSE3 - Calculate in place words and then fix all out of place words
4784   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4785   // the 16 different words that comprise the two doublequadword input vectors.
4786   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4787   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4788   SDValue NewV = V2Only ? V2 : V1;
4789   for (int i = 0; i != 8; ++i) {
4790     int Elt0 = MaskVals[i*2];
4791     int Elt1 = MaskVals[i*2+1];
4792
4793     // This word of the result is all undef, skip it.
4794     if (Elt0 < 0 && Elt1 < 0)
4795       continue;
4796
4797     // This word of the result is already in the correct place, skip it.
4798     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4799       continue;
4800     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4801       continue;
4802
4803     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4804     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4805     SDValue InsElt;
4806
4807     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4808     // using a single extract together, load it and store it.
4809     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4810       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4811                            DAG.getIntPtrConstant(Elt1 / 2));
4812       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4813                         DAG.getIntPtrConstant(i));
4814       continue;
4815     }
4816
4817     // If Elt1 is defined, extract it from the appropriate source.  If the
4818     // source byte is not also odd, shift the extracted word left 8 bits
4819     // otherwise clear the bottom 8 bits if we need to do an or.
4820     if (Elt1 >= 0) {
4821       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4822                            DAG.getIntPtrConstant(Elt1 / 2));
4823       if ((Elt1 & 1) == 0)
4824         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4825                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4826       else if (Elt0 >= 0)
4827         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4828                              DAG.getConstant(0xFF00, MVT::i16));
4829     }
4830     // If Elt0 is defined, extract it from the appropriate source.  If the
4831     // source byte is not also even, shift the extracted word right 8 bits. If
4832     // Elt1 was also defined, OR the extracted values together before
4833     // inserting them in the result.
4834     if (Elt0 >= 0) {
4835       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4836                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4837       if ((Elt0 & 1) != 0)
4838         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4839                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4840       else if (Elt1 >= 0)
4841         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4842                              DAG.getConstant(0x00FF, MVT::i16));
4843       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4844                          : InsElt0;
4845     }
4846     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4847                        DAG.getIntPtrConstant(i));
4848   }
4849   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4850 }
4851
4852 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4853 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4854 /// done when every pair / quad of shuffle mask elements point to elements in
4855 /// the right sequence. e.g.
4856 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4857 static
4858 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4859                                  SelectionDAG &DAG, DebugLoc dl) {
4860   EVT VT = SVOp->getValueType(0);
4861   SDValue V1 = SVOp->getOperand(0);
4862   SDValue V2 = SVOp->getOperand(1);
4863   unsigned NumElems = VT.getVectorNumElements();
4864   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4865   EVT NewVT;
4866   switch (VT.getSimpleVT().SimpleTy) {
4867   default: assert(false && "Unexpected!");
4868   case MVT::v4f32: NewVT = MVT::v2f64; break;
4869   case MVT::v4i32: NewVT = MVT::v2i64; break;
4870   case MVT::v8i16: NewVT = MVT::v4i32; break;
4871   case MVT::v16i8: NewVT = MVT::v4i32; break;
4872   }
4873
4874   int Scale = NumElems / NewWidth;
4875   SmallVector<int, 8> MaskVec;
4876   for (unsigned i = 0; i < NumElems; i += Scale) {
4877     int StartIdx = -1;
4878     for (int j = 0; j < Scale; ++j) {
4879       int EltIdx = SVOp->getMaskElt(i+j);
4880       if (EltIdx < 0)
4881         continue;
4882       if (StartIdx == -1)
4883         StartIdx = EltIdx - (EltIdx % Scale);
4884       if (EltIdx != StartIdx + j)
4885         return SDValue();
4886     }
4887     if (StartIdx == -1)
4888       MaskVec.push_back(-1);
4889     else
4890       MaskVec.push_back(StartIdx / Scale);
4891   }
4892
4893   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4894   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4895   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4896 }
4897
4898 /// getVZextMovL - Return a zero-extending vector move low node.
4899 ///
4900 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4901                             SDValue SrcOp, SelectionDAG &DAG,
4902                             const X86Subtarget *Subtarget, DebugLoc dl) {
4903   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4904     LoadSDNode *LD = NULL;
4905     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4906       LD = dyn_cast<LoadSDNode>(SrcOp);
4907     if (!LD) {
4908       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4909       // instead.
4910       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4911       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4912           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4913           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4914           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4915         // PR2108
4916         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4917         return DAG.getNode(ISD::BITCAST, dl, VT,
4918                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4919                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4920                                                    OpVT,
4921                                                    SrcOp.getOperand(0)
4922                                                           .getOperand(0))));
4923       }
4924     }
4925   }
4926
4927   return DAG.getNode(ISD::BITCAST, dl, VT,
4928                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4929                                  DAG.getNode(ISD::BITCAST, dl,
4930                                              OpVT, SrcOp)));
4931 }
4932
4933 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4934 /// shuffles.
4935 static SDValue
4936 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4937   SDValue V1 = SVOp->getOperand(0);
4938   SDValue V2 = SVOp->getOperand(1);
4939   DebugLoc dl = SVOp->getDebugLoc();
4940   EVT VT = SVOp->getValueType(0);
4941
4942   SmallVector<std::pair<int, int>, 8> Locs;
4943   Locs.resize(4);
4944   SmallVector<int, 8> Mask1(4U, -1);
4945   SmallVector<int, 8> PermMask;
4946   SVOp->getMask(PermMask);
4947
4948   unsigned NumHi = 0;
4949   unsigned NumLo = 0;
4950   for (unsigned i = 0; i != 4; ++i) {
4951     int Idx = PermMask[i];
4952     if (Idx < 0) {
4953       Locs[i] = std::make_pair(-1, -1);
4954     } else {
4955       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4956       if (Idx < 4) {
4957         Locs[i] = std::make_pair(0, NumLo);
4958         Mask1[NumLo] = Idx;
4959         NumLo++;
4960       } else {
4961         Locs[i] = std::make_pair(1, NumHi);
4962         if (2+NumHi < 4)
4963           Mask1[2+NumHi] = Idx;
4964         NumHi++;
4965       }
4966     }
4967   }
4968
4969   if (NumLo <= 2 && NumHi <= 2) {
4970     // If no more than two elements come from either vector. This can be
4971     // implemented with two shuffles. First shuffle gather the elements.
4972     // The second shuffle, which takes the first shuffle as both of its
4973     // vector operands, put the elements into the right order.
4974     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4975
4976     SmallVector<int, 8> Mask2(4U, -1);
4977
4978     for (unsigned i = 0; i != 4; ++i) {
4979       if (Locs[i].first == -1)
4980         continue;
4981       else {
4982         unsigned Idx = (i < 2) ? 0 : 4;
4983         Idx += Locs[i].first * 2 + Locs[i].second;
4984         Mask2[i] = Idx;
4985       }
4986     }
4987
4988     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4989   } else if (NumLo == 3 || NumHi == 3) {
4990     // Otherwise, we must have three elements from one vector, call it X, and
4991     // one element from the other, call it Y.  First, use a shufps to build an
4992     // intermediate vector with the one element from Y and the element from X
4993     // that will be in the same half in the final destination (the indexes don't
4994     // matter). Then, use a shufps to build the final vector, taking the half
4995     // containing the element from Y from the intermediate, and the other half
4996     // from X.
4997     if (NumHi == 3) {
4998       // Normalize it so the 3 elements come from V1.
4999       CommuteVectorShuffleMask(PermMask, VT);
5000       std::swap(V1, V2);
5001     }
5002
5003     // Find the element from V2.
5004     unsigned HiIndex;
5005     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5006       int Val = PermMask[HiIndex];
5007       if (Val < 0)
5008         continue;
5009       if (Val >= 4)
5010         break;
5011     }
5012
5013     Mask1[0] = PermMask[HiIndex];
5014     Mask1[1] = -1;
5015     Mask1[2] = PermMask[HiIndex^1];
5016     Mask1[3] = -1;
5017     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5018
5019     if (HiIndex >= 2) {
5020       Mask1[0] = PermMask[0];
5021       Mask1[1] = PermMask[1];
5022       Mask1[2] = HiIndex & 1 ? 6 : 4;
5023       Mask1[3] = HiIndex & 1 ? 4 : 6;
5024       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5025     } else {
5026       Mask1[0] = HiIndex & 1 ? 2 : 0;
5027       Mask1[1] = HiIndex & 1 ? 0 : 2;
5028       Mask1[2] = PermMask[2];
5029       Mask1[3] = PermMask[3];
5030       if (Mask1[2] >= 0)
5031         Mask1[2] += 4;
5032       if (Mask1[3] >= 0)
5033         Mask1[3] += 4;
5034       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5035     }
5036   }
5037
5038   // Break it into (shuffle shuffle_hi, shuffle_lo).
5039   Locs.clear();
5040   SmallVector<int,8> LoMask(4U, -1);
5041   SmallVector<int,8> HiMask(4U, -1);
5042
5043   SmallVector<int,8> *MaskPtr = &LoMask;
5044   unsigned MaskIdx = 0;
5045   unsigned LoIdx = 0;
5046   unsigned HiIdx = 2;
5047   for (unsigned i = 0; i != 4; ++i) {
5048     if (i == 2) {
5049       MaskPtr = &HiMask;
5050       MaskIdx = 1;
5051       LoIdx = 0;
5052       HiIdx = 2;
5053     }
5054     int Idx = PermMask[i];
5055     if (Idx < 0) {
5056       Locs[i] = std::make_pair(-1, -1);
5057     } else if (Idx < 4) {
5058       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5059       (*MaskPtr)[LoIdx] = Idx;
5060       LoIdx++;
5061     } else {
5062       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5063       (*MaskPtr)[HiIdx] = Idx;
5064       HiIdx++;
5065     }
5066   }
5067
5068   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5069   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5070   SmallVector<int, 8> MaskOps;
5071   for (unsigned i = 0; i != 4; ++i) {
5072     if (Locs[i].first == -1) {
5073       MaskOps.push_back(-1);
5074     } else {
5075       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5076       MaskOps.push_back(Idx);
5077     }
5078   }
5079   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5080 }
5081
5082 static bool MayFoldVectorLoad(SDValue V) {
5083   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5084     V = V.getOperand(0);
5085   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5086     V = V.getOperand(0);
5087   if (MayFoldLoad(V))
5088     return true;
5089   return false;
5090 }
5091
5092 // FIXME: the version above should always be used. Since there's
5093 // a bug where several vector shuffles can't be folded because the
5094 // DAG is not updated during lowering and a node claims to have two
5095 // uses while it only has one, use this version, and let isel match
5096 // another instruction if the load really happens to have more than
5097 // one use. Remove this version after this bug get fixed.
5098 // rdar://8434668, PR8156
5099 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5100   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5101     V = V.getOperand(0);
5102   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5103     V = V.getOperand(0);
5104   if (ISD::isNormalLoad(V.getNode()))
5105     return true;
5106   return false;
5107 }
5108
5109 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5110 /// a vector extract, and if both can be later optimized into a single load.
5111 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5112 /// here because otherwise a target specific shuffle node is going to be
5113 /// emitted for this shuffle, and the optimization not done.
5114 /// FIXME: This is probably not the best approach, but fix the problem
5115 /// until the right path is decided.
5116 static
5117 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5118                                          const TargetLowering &TLI) {
5119   EVT VT = V.getValueType();
5120   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5121
5122   // Be sure that the vector shuffle is present in a pattern like this:
5123   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5124   if (!V.hasOneUse())
5125     return false;
5126
5127   SDNode *N = *V.getNode()->use_begin();
5128   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5129     return false;
5130
5131   SDValue EltNo = N->getOperand(1);
5132   if (!isa<ConstantSDNode>(EltNo))
5133     return false;
5134
5135   // If the bit convert changed the number of elements, it is unsafe
5136   // to examine the mask.
5137   bool HasShuffleIntoBitcast = false;
5138   if (V.getOpcode() == ISD::BITCAST) {
5139     EVT SrcVT = V.getOperand(0).getValueType();
5140     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5141       return false;
5142     V = V.getOperand(0);
5143     HasShuffleIntoBitcast = true;
5144   }
5145
5146   // Select the input vector, guarding against out of range extract vector.
5147   unsigned NumElems = VT.getVectorNumElements();
5148   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5149   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5150   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5151
5152   // Skip one more bit_convert if necessary
5153   if (V.getOpcode() == ISD::BITCAST)
5154     V = V.getOperand(0);
5155
5156   if (ISD::isNormalLoad(V.getNode())) {
5157     // Is the original load suitable?
5158     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5159
5160     // FIXME: avoid the multi-use bug that is preventing lots of
5161     // of foldings to be detected, this is still wrong of course, but
5162     // give the temporary desired behavior, and if it happens that
5163     // the load has real more uses, during isel it will not fold, and
5164     // will generate poor code.
5165     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5166       return false;
5167
5168     if (!HasShuffleIntoBitcast)
5169       return true;
5170
5171     // If there's a bitcast before the shuffle, check if the load type and
5172     // alignment is valid.
5173     unsigned Align = LN0->getAlignment();
5174     unsigned NewAlign =
5175       TLI.getTargetData()->getABITypeAlignment(
5176                                     VT.getTypeForEVT(*DAG.getContext()));
5177
5178     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5179       return false;
5180   }
5181
5182   return true;
5183 }
5184
5185 static
5186 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5187   EVT VT = Op.getValueType();
5188
5189   // Canonizalize to v2f64.
5190   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5191   return DAG.getNode(ISD::BITCAST, dl, VT,
5192                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5193                                           V1, DAG));
5194 }
5195
5196 static
5197 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5198                         bool HasSSE2) {
5199   SDValue V1 = Op.getOperand(0);
5200   SDValue V2 = Op.getOperand(1);
5201   EVT VT = Op.getValueType();
5202
5203   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5204
5205   if (HasSSE2 && VT == MVT::v2f64)
5206     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5207
5208   // v4f32 or v4i32
5209   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5210 }
5211
5212 static
5213 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5214   SDValue V1 = Op.getOperand(0);
5215   SDValue V2 = Op.getOperand(1);
5216   EVT VT = Op.getValueType();
5217
5218   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5219          "unsupported shuffle type");
5220
5221   if (V2.getOpcode() == ISD::UNDEF)
5222     V2 = V1;
5223
5224   // v4i32 or v4f32
5225   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5226 }
5227
5228 static
5229 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5230   SDValue V1 = Op.getOperand(0);
5231   SDValue V2 = Op.getOperand(1);
5232   EVT VT = Op.getValueType();
5233   unsigned NumElems = VT.getVectorNumElements();
5234
5235   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5236   // operand of these instructions is only memory, so check if there's a
5237   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5238   // same masks.
5239   bool CanFoldLoad = false;
5240
5241   // Trivial case, when V2 comes from a load.
5242   if (MayFoldVectorLoad(V2))
5243     CanFoldLoad = true;
5244
5245   // When V1 is a load, it can be folded later into a store in isel, example:
5246   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5247   //    turns into:
5248   //  (MOVLPSmr addr:$src1, VR128:$src2)
5249   // So, recognize this potential and also use MOVLPS or MOVLPD
5250   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5251     CanFoldLoad = true;
5252
5253   if (CanFoldLoad) {
5254     if (HasSSE2 && NumElems == 2)
5255       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5256
5257     if (NumElems == 4)
5258       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5259   }
5260
5261   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5262   // movl and movlp will both match v2i64, but v2i64 is never matched by
5263   // movl earlier because we make it strict to avoid messing with the movlp load
5264   // folding logic (see the code above getMOVLP call). Match it here then,
5265   // this is horrible, but will stay like this until we move all shuffle
5266   // matching to x86 specific nodes. Note that for the 1st condition all
5267   // types are matched with movsd.
5268   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5269     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5270   else if (HasSSE2)
5271     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5272
5273
5274   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5275
5276   // Invert the operand order and use SHUFPS to match it.
5277   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5278                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5279 }
5280
5281 static inline unsigned getUNPCKLOpcode(EVT VT) {
5282   switch(VT.getSimpleVT().SimpleTy) {
5283   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5284   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5285   case MVT::v4f32: return X86ISD::UNPCKLPS;
5286   case MVT::v2f64: return X86ISD::UNPCKLPD;
5287   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5288   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5289   default:
5290     llvm_unreachable("Unknow type for unpckl");
5291   }
5292   return 0;
5293 }
5294
5295 static inline unsigned getUNPCKHOpcode(EVT VT) {
5296   switch(VT.getSimpleVT().SimpleTy) {
5297   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5298   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5299   case MVT::v4f32: return X86ISD::UNPCKHPS;
5300   case MVT::v2f64: return X86ISD::UNPCKHPD;
5301   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5302   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5303   default:
5304     llvm_unreachable("Unknow type for unpckh");
5305   }
5306   return 0;
5307 }
5308
5309 static
5310 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5311                                const TargetLowering &TLI,
5312                                const X86Subtarget *Subtarget) {
5313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5314   EVT VT = Op.getValueType();
5315   DebugLoc dl = Op.getDebugLoc();
5316   SDValue V1 = Op.getOperand(0);
5317   SDValue V2 = Op.getOperand(1);
5318
5319   if (isZeroShuffle(SVOp))
5320     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5321
5322   // Handle splat operations
5323   if (SVOp->isSplat()) {
5324     // Special case, this is the only place now where it's
5325     // allowed to return a vector_shuffle operation without
5326     // using a target specific node, because *hopefully* it
5327     // will be optimized away by the dag combiner.
5328     if (VT.getVectorNumElements() <= 4 &&
5329         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5330       return Op;
5331
5332     // Handle splats by matching through known masks
5333     if (VT.getVectorNumElements() <= 4)
5334       return SDValue();
5335
5336     // Canonicalize all of the remaining to v4f32.
5337     return PromoteSplat(SVOp, DAG);
5338   }
5339
5340   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5341   // do it!
5342   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5343     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5344     if (NewOp.getNode())
5345       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5346   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5347     // FIXME: Figure out a cleaner way to do this.
5348     // Try to make use of movq to zero out the top part.
5349     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5350       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5351       if (NewOp.getNode()) {
5352         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5353           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5354                               DAG, Subtarget, dl);
5355       }
5356     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5357       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5358       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5359         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5360                             DAG, Subtarget, dl);
5361     }
5362   }
5363   return SDValue();
5364 }
5365
5366 SDValue
5367 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5369   SDValue V1 = Op.getOperand(0);
5370   SDValue V2 = Op.getOperand(1);
5371   EVT VT = Op.getValueType();
5372   DebugLoc dl = Op.getDebugLoc();
5373   unsigned NumElems = VT.getVectorNumElements();
5374   bool isMMX = VT.getSizeInBits() == 64;
5375   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5376   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5377   bool V1IsSplat = false;
5378   bool V2IsSplat = false;
5379   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5380   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5381   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5382   MachineFunction &MF = DAG.getMachineFunction();
5383   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5384
5385   // Shuffle operations on MMX not supported.
5386   if (isMMX)
5387     return Op;
5388
5389   // Vector shuffle lowering takes 3 steps:
5390   //
5391   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5392   //    narrowing and commutation of operands should be handled.
5393   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5394   //    shuffle nodes.
5395   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5396   //    so the shuffle can be broken into other shuffles and the legalizer can
5397   //    try the lowering again.
5398   //
5399   // The general ideia is that no vector_shuffle operation should be left to
5400   // be matched during isel, all of them must be converted to a target specific
5401   // node here.
5402
5403   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5404   // narrowing and commutation of operands should be handled. The actual code
5405   // doesn't include all of those, work in progress...
5406   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5407   if (NewOp.getNode())
5408     return NewOp;
5409
5410   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5411   // unpckh_undef). Only use pshufd if speed is more important than size.
5412   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5413     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5414       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5415   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5416     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5417       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5418
5419   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5420       RelaxedMayFoldVectorLoad(V1))
5421     return getMOVDDup(Op, dl, V1, DAG);
5422
5423   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5424     return getMOVHighToLow(Op, dl, DAG);
5425
5426   // Use to match splats
5427   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5428       (VT == MVT::v2f64 || VT == MVT::v2i64))
5429     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5430
5431   if (X86::isPSHUFDMask(SVOp)) {
5432     // The actual implementation will match the mask in the if above and then
5433     // during isel it can match several different instructions, not only pshufd
5434     // as its name says, sad but true, emulate the behavior for now...
5435     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5436         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5437
5438     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5439
5440     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5441       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5442
5443     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5444       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5445                                   TargetMask, DAG);
5446
5447     if (VT == MVT::v4f32)
5448       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5449                                   TargetMask, DAG);
5450   }
5451
5452   // Check if this can be converted into a logical shift.
5453   bool isLeft = false;
5454   unsigned ShAmt = 0;
5455   SDValue ShVal;
5456   bool isShift = getSubtarget()->hasSSE2() &&
5457     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5458   if (isShift && ShVal.hasOneUse()) {
5459     // If the shifted value has multiple uses, it may be cheaper to use
5460     // v_set0 + movlhps or movhlps, etc.
5461     EVT EltVT = VT.getVectorElementType();
5462     ShAmt *= EltVT.getSizeInBits();
5463     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5464   }
5465
5466   if (X86::isMOVLMask(SVOp)) {
5467     if (V1IsUndef)
5468       return V2;
5469     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5470       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5471     if (!X86::isMOVLPMask(SVOp)) {
5472       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5473         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5474
5475       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5476         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5477     }
5478   }
5479
5480   // FIXME: fold these into legal mask.
5481   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5482     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5483
5484   if (X86::isMOVHLPSMask(SVOp))
5485     return getMOVHighToLow(Op, dl, DAG);
5486
5487   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5488     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5489
5490   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5491     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5492
5493   if (X86::isMOVLPMask(SVOp))
5494     return getMOVLP(Op, dl, DAG, HasSSE2);
5495
5496   if (ShouldXformToMOVHLPS(SVOp) ||
5497       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5498     return CommuteVectorShuffle(SVOp, DAG);
5499
5500   if (isShift) {
5501     // No better options. Use a vshl / vsrl.
5502     EVT EltVT = VT.getVectorElementType();
5503     ShAmt *= EltVT.getSizeInBits();
5504     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5505   }
5506
5507   bool Commuted = false;
5508   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5509   // 1,1,1,1 -> v8i16 though.
5510   V1IsSplat = isSplatVector(V1.getNode());
5511   V2IsSplat = isSplatVector(V2.getNode());
5512
5513   // Canonicalize the splat or undef, if present, to be on the RHS.
5514   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5515     Op = CommuteVectorShuffle(SVOp, DAG);
5516     SVOp = cast<ShuffleVectorSDNode>(Op);
5517     V1 = SVOp->getOperand(0);
5518     V2 = SVOp->getOperand(1);
5519     std::swap(V1IsSplat, V2IsSplat);
5520     std::swap(V1IsUndef, V2IsUndef);
5521     Commuted = true;
5522   }
5523
5524   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5525     // Shuffling low element of v1 into undef, just return v1.
5526     if (V2IsUndef)
5527       return V1;
5528     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5529     // the instruction selector will not match, so get a canonical MOVL with
5530     // swapped operands to undo the commute.
5531     return getMOVL(DAG, dl, VT, V2, V1);
5532   }
5533
5534   if (X86::isUNPCKLMask(SVOp))
5535     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5536
5537   if (X86::isUNPCKHMask(SVOp))
5538     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5539
5540   if (V2IsSplat) {
5541     // Normalize mask so all entries that point to V2 points to its first
5542     // element then try to match unpck{h|l} again. If match, return a
5543     // new vector_shuffle with the corrected mask.
5544     SDValue NewMask = NormalizeMask(SVOp, DAG);
5545     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5546     if (NSVOp != SVOp) {
5547       if (X86::isUNPCKLMask(NSVOp, true)) {
5548         return NewMask;
5549       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5550         return NewMask;
5551       }
5552     }
5553   }
5554
5555   if (Commuted) {
5556     // Commute is back and try unpck* again.
5557     // FIXME: this seems wrong.
5558     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5559     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5560
5561     if (X86::isUNPCKLMask(NewSVOp))
5562       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5563
5564     if (X86::isUNPCKHMask(NewSVOp))
5565       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5566   }
5567
5568   // Normalize the node to match x86 shuffle ops if needed
5569   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5570     return CommuteVectorShuffle(SVOp, DAG);
5571
5572   // The checks below are all present in isShuffleMaskLegal, but they are
5573   // inlined here right now to enable us to directly emit target specific
5574   // nodes, and remove one by one until they don't return Op anymore.
5575   SmallVector<int, 16> M;
5576   SVOp->getMask(M);
5577
5578   if (isPALIGNRMask(M, VT, HasSSSE3))
5579     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5580                                 X86::getShufflePALIGNRImmediate(SVOp),
5581                                 DAG);
5582
5583   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5584       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5585     if (VT == MVT::v2f64)
5586       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5587     if (VT == MVT::v2i64)
5588       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5589   }
5590
5591   if (isPSHUFHWMask(M, VT))
5592     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5593                                 X86::getShufflePSHUFHWImmediate(SVOp),
5594                                 DAG);
5595
5596   if (isPSHUFLWMask(M, VT))
5597     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5598                                 X86::getShufflePSHUFLWImmediate(SVOp),
5599                                 DAG);
5600
5601   if (isSHUFPMask(M, VT)) {
5602     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5603     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5604       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5605                                   TargetMask, DAG);
5606     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5607       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5608                                   TargetMask, DAG);
5609   }
5610
5611   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5612     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5613       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5614   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5615     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5616       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5617
5618   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5619   if (VT == MVT::v8i16) {
5620     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5621     if (NewOp.getNode())
5622       return NewOp;
5623   }
5624
5625   if (VT == MVT::v16i8) {
5626     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5627     if (NewOp.getNode())
5628       return NewOp;
5629   }
5630
5631   // Handle all 4 wide cases with a number of shuffles.
5632   if (NumElems == 4)
5633     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5634
5635   return SDValue();
5636 }
5637
5638 SDValue
5639 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5640                                                 SelectionDAG &DAG) const {
5641   EVT VT = Op.getValueType();
5642   DebugLoc dl = Op.getDebugLoc();
5643   if (VT.getSizeInBits() == 8) {
5644     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5645                                     Op.getOperand(0), Op.getOperand(1));
5646     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5647                                     DAG.getValueType(VT));
5648     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5649   } else if (VT.getSizeInBits() == 16) {
5650     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5651     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5652     if (Idx == 0)
5653       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5654                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5655                                      DAG.getNode(ISD::BITCAST, dl,
5656                                                  MVT::v4i32,
5657                                                  Op.getOperand(0)),
5658                                      Op.getOperand(1)));
5659     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5660                                     Op.getOperand(0), Op.getOperand(1));
5661     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5662                                     DAG.getValueType(VT));
5663     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5664   } else if (VT == MVT::f32) {
5665     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5666     // the result back to FR32 register. It's only worth matching if the
5667     // result has a single use which is a store or a bitcast to i32.  And in
5668     // the case of a store, it's not worth it if the index is a constant 0,
5669     // because a MOVSSmr can be used instead, which is smaller and faster.
5670     if (!Op.hasOneUse())
5671       return SDValue();
5672     SDNode *User = *Op.getNode()->use_begin();
5673     if ((User->getOpcode() != ISD::STORE ||
5674          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5675           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5676         (User->getOpcode() != ISD::BITCAST ||
5677          User->getValueType(0) != MVT::i32))
5678       return SDValue();
5679     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5680                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5681                                               Op.getOperand(0)),
5682                                               Op.getOperand(1));
5683     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5684   } else if (VT == MVT::i32) {
5685     // ExtractPS works with constant index.
5686     if (isa<ConstantSDNode>(Op.getOperand(1)))
5687       return Op;
5688   }
5689   return SDValue();
5690 }
5691
5692
5693 SDValue
5694 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5695                                            SelectionDAG &DAG) const {
5696   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5697     return SDValue();
5698
5699   if (Subtarget->hasSSE41()) {
5700     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5701     if (Res.getNode())
5702       return Res;
5703   }
5704
5705   EVT VT = Op.getValueType();
5706   DebugLoc dl = Op.getDebugLoc();
5707   // TODO: handle v16i8.
5708   if (VT.getSizeInBits() == 16) {
5709     SDValue Vec = Op.getOperand(0);
5710     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5711     if (Idx == 0)
5712       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5713                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5714                                      DAG.getNode(ISD::BITCAST, dl,
5715                                                  MVT::v4i32, Vec),
5716                                      Op.getOperand(1)));
5717     // Transform it so it match pextrw which produces a 32-bit result.
5718     EVT EltVT = MVT::i32;
5719     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5720                                     Op.getOperand(0), Op.getOperand(1));
5721     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5722                                     DAG.getValueType(VT));
5723     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5724   } else if (VT.getSizeInBits() == 32) {
5725     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5726     if (Idx == 0)
5727       return Op;
5728
5729     // SHUFPS the element to the lowest double word, then movss.
5730     int Mask[4] = { Idx, -1, -1, -1 };
5731     EVT VVT = Op.getOperand(0).getValueType();
5732     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5733                                        DAG.getUNDEF(VVT), Mask);
5734     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5735                        DAG.getIntPtrConstant(0));
5736   } else if (VT.getSizeInBits() == 64) {
5737     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5738     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5739     //        to match extract_elt for f64.
5740     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5741     if (Idx == 0)
5742       return Op;
5743
5744     // UNPCKHPD the element to the lowest double word, then movsd.
5745     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5746     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5747     int Mask[2] = { 1, -1 };
5748     EVT VVT = Op.getOperand(0).getValueType();
5749     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5750                                        DAG.getUNDEF(VVT), Mask);
5751     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5752                        DAG.getIntPtrConstant(0));
5753   }
5754
5755   return SDValue();
5756 }
5757
5758 SDValue
5759 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5760                                                SelectionDAG &DAG) const {
5761   EVT VT = Op.getValueType();
5762   EVT EltVT = VT.getVectorElementType();
5763   DebugLoc dl = Op.getDebugLoc();
5764
5765   SDValue N0 = Op.getOperand(0);
5766   SDValue N1 = Op.getOperand(1);
5767   SDValue N2 = Op.getOperand(2);
5768
5769   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5770       isa<ConstantSDNode>(N2)) {
5771     unsigned Opc;
5772     if (VT == MVT::v8i16)
5773       Opc = X86ISD::PINSRW;
5774     else if (VT == MVT::v16i8)
5775       Opc = X86ISD::PINSRB;
5776     else
5777       Opc = X86ISD::PINSRB;
5778
5779     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5780     // argument.
5781     if (N1.getValueType() != MVT::i32)
5782       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5783     if (N2.getValueType() != MVT::i32)
5784       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5785     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5786   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5787     // Bits [7:6] of the constant are the source select.  This will always be
5788     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5789     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5790     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5791     // Bits [5:4] of the constant are the destination select.  This is the
5792     //  value of the incoming immediate.
5793     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5794     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5795     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5796     // Create this as a scalar to vector..
5797     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5798     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5799   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5800     // PINSR* works with constant index.
5801     return Op;
5802   }
5803   return SDValue();
5804 }
5805
5806 SDValue
5807 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5808   EVT VT = Op.getValueType();
5809   EVT EltVT = VT.getVectorElementType();
5810
5811   if (Subtarget->hasSSE41())
5812     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5813
5814   if (EltVT == MVT::i8)
5815     return SDValue();
5816
5817   DebugLoc dl = Op.getDebugLoc();
5818   SDValue N0 = Op.getOperand(0);
5819   SDValue N1 = Op.getOperand(1);
5820   SDValue N2 = Op.getOperand(2);
5821
5822   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5823     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5824     // as its second argument.
5825     if (N1.getValueType() != MVT::i32)
5826       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5827     if (N2.getValueType() != MVT::i32)
5828       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5829     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5830   }
5831   return SDValue();
5832 }
5833
5834 SDValue
5835 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5836   DebugLoc dl = Op.getDebugLoc();
5837
5838   if (Op.getValueType() == MVT::v1i64 &&
5839       Op.getOperand(0).getValueType() == MVT::i64)
5840     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5841
5842   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5843   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5844          "Expected an SSE type!");
5845   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5846                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5847 }
5848
5849 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
5850 // a simple subregister reference or explicit instructions to grab
5851 // upper bits of a vector.
5852 SDValue
5853 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
5854   if (Subtarget->hasAVX()) {
5855     // TODO
5856   }
5857   return SDValue();
5858 }
5859
5860 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
5861 // simple superregister reference or explicit instructions to insert
5862 // the upper bits of a vector.
5863 SDValue
5864 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
5865   if (Subtarget->hasAVX()) {
5866     DebugLoc dl = Op.getNode()->getDebugLoc();
5867     SDValue Vec = Op.getNode()->getOperand(0);
5868     SDValue SubVec = Op.getNode()->getOperand(1);
5869     SDValue Idx = Op.getNode()->getOperand(2);
5870
5871     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
5872         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
5873       // TODO
5874     }
5875   }
5876   return SDValue();
5877 }
5878
5879 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5880 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5881 // one of the above mentioned nodes. It has to be wrapped because otherwise
5882 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5883 // be used to form addressing mode. These wrapped nodes will be selected
5884 // into MOV32ri.
5885 SDValue
5886 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5887   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5888
5889   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5890   // global base reg.
5891   unsigned char OpFlag = 0;
5892   unsigned WrapperKind = X86ISD::Wrapper;
5893   CodeModel::Model M = getTargetMachine().getCodeModel();
5894
5895   if (Subtarget->isPICStyleRIPRel() &&
5896       (M == CodeModel::Small || M == CodeModel::Kernel))
5897     WrapperKind = X86ISD::WrapperRIP;
5898   else if (Subtarget->isPICStyleGOT())
5899     OpFlag = X86II::MO_GOTOFF;
5900   else if (Subtarget->isPICStyleStubPIC())
5901     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5902
5903   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5904                                              CP->getAlignment(),
5905                                              CP->getOffset(), OpFlag);
5906   DebugLoc DL = CP->getDebugLoc();
5907   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5908   // With PIC, the address is actually $g + Offset.
5909   if (OpFlag) {
5910     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5911                          DAG.getNode(X86ISD::GlobalBaseReg,
5912                                      DebugLoc(), getPointerTy()),
5913                          Result);
5914   }
5915
5916   return Result;
5917 }
5918
5919 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5920   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5921
5922   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5923   // global base reg.
5924   unsigned char OpFlag = 0;
5925   unsigned WrapperKind = X86ISD::Wrapper;
5926   CodeModel::Model M = getTargetMachine().getCodeModel();
5927
5928   if (Subtarget->isPICStyleRIPRel() &&
5929       (M == CodeModel::Small || M == CodeModel::Kernel))
5930     WrapperKind = X86ISD::WrapperRIP;
5931   else if (Subtarget->isPICStyleGOT())
5932     OpFlag = X86II::MO_GOTOFF;
5933   else if (Subtarget->isPICStyleStubPIC())
5934     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5935
5936   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5937                                           OpFlag);
5938   DebugLoc DL = JT->getDebugLoc();
5939   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5940
5941   // With PIC, the address is actually $g + Offset.
5942   if (OpFlag)
5943     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5944                          DAG.getNode(X86ISD::GlobalBaseReg,
5945                                      DebugLoc(), getPointerTy()),
5946                          Result);
5947
5948   return Result;
5949 }
5950
5951 SDValue
5952 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5953   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5954
5955   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5956   // global base reg.
5957   unsigned char OpFlag = 0;
5958   unsigned WrapperKind = X86ISD::Wrapper;
5959   CodeModel::Model M = getTargetMachine().getCodeModel();
5960
5961   if (Subtarget->isPICStyleRIPRel() &&
5962       (M == CodeModel::Small || M == CodeModel::Kernel))
5963     WrapperKind = X86ISD::WrapperRIP;
5964   else if (Subtarget->isPICStyleGOT())
5965     OpFlag = X86II::MO_GOTOFF;
5966   else if (Subtarget->isPICStyleStubPIC())
5967     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5968
5969   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5970
5971   DebugLoc DL = Op.getDebugLoc();
5972   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5973
5974
5975   // With PIC, the address is actually $g + Offset.
5976   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5977       !Subtarget->is64Bit()) {
5978     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5979                          DAG.getNode(X86ISD::GlobalBaseReg,
5980                                      DebugLoc(), getPointerTy()),
5981                          Result);
5982   }
5983
5984   return Result;
5985 }
5986
5987 SDValue
5988 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5989   // Create the TargetBlockAddressAddress node.
5990   unsigned char OpFlags =
5991     Subtarget->ClassifyBlockAddressReference();
5992   CodeModel::Model M = getTargetMachine().getCodeModel();
5993   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5994   DebugLoc dl = Op.getDebugLoc();
5995   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5996                                        /*isTarget=*/true, OpFlags);
5997
5998   if (Subtarget->isPICStyleRIPRel() &&
5999       (M == CodeModel::Small || M == CodeModel::Kernel))
6000     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6001   else
6002     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6003
6004   // With PIC, the address is actually $g + Offset.
6005   if (isGlobalRelativeToPICBase(OpFlags)) {
6006     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6007                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6008                          Result);
6009   }
6010
6011   return Result;
6012 }
6013
6014 SDValue
6015 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6016                                       int64_t Offset,
6017                                       SelectionDAG &DAG) const {
6018   // Create the TargetGlobalAddress node, folding in the constant
6019   // offset if it is legal.
6020   unsigned char OpFlags =
6021     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6022   CodeModel::Model M = getTargetMachine().getCodeModel();
6023   SDValue Result;
6024   if (OpFlags == X86II::MO_NO_FLAG &&
6025       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6026     // A direct static reference to a global.
6027     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6028     Offset = 0;
6029   } else {
6030     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6031   }
6032
6033   if (Subtarget->isPICStyleRIPRel() &&
6034       (M == CodeModel::Small || M == CodeModel::Kernel))
6035     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6036   else
6037     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6038
6039   // With PIC, the address is actually $g + Offset.
6040   if (isGlobalRelativeToPICBase(OpFlags)) {
6041     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6042                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6043                          Result);
6044   }
6045
6046   // For globals that require a load from a stub to get the address, emit the
6047   // load.
6048   if (isGlobalStubReference(OpFlags))
6049     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6050                          MachinePointerInfo::getGOT(), false, false, 0);
6051
6052   // If there was a non-zero offset that we didn't fold, create an explicit
6053   // addition for it.
6054   if (Offset != 0)
6055     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6056                          DAG.getConstant(Offset, getPointerTy()));
6057
6058   return Result;
6059 }
6060
6061 SDValue
6062 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6063   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6064   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6065   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6066 }
6067
6068 static SDValue
6069 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6070            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6071            unsigned char OperandFlags) {
6072   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6073   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6074   DebugLoc dl = GA->getDebugLoc();
6075   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6076                                            GA->getValueType(0),
6077                                            GA->getOffset(),
6078                                            OperandFlags);
6079   if (InFlag) {
6080     SDValue Ops[] = { Chain,  TGA, *InFlag };
6081     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6082   } else {
6083     SDValue Ops[]  = { Chain, TGA };
6084     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6085   }
6086
6087   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6088   MFI->setAdjustsStack(true);
6089
6090   SDValue Flag = Chain.getValue(1);
6091   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6092 }
6093
6094 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6095 static SDValue
6096 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6097                                 const EVT PtrVT) {
6098   SDValue InFlag;
6099   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6100   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6101                                      DAG.getNode(X86ISD::GlobalBaseReg,
6102                                                  DebugLoc(), PtrVT), InFlag);
6103   InFlag = Chain.getValue(1);
6104
6105   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6106 }
6107
6108 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6109 static SDValue
6110 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6111                                 const EVT PtrVT) {
6112   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6113                     X86::RAX, X86II::MO_TLSGD);
6114 }
6115
6116 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6117 // "local exec" model.
6118 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6119                                    const EVT PtrVT, TLSModel::Model model,
6120                                    bool is64Bit) {
6121   DebugLoc dl = GA->getDebugLoc();
6122
6123   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6124   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6125                                                          is64Bit ? 257 : 256));
6126
6127   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6128                                       DAG.getIntPtrConstant(0),
6129                                       MachinePointerInfo(Ptr), false, false, 0);
6130
6131   unsigned char OperandFlags = 0;
6132   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6133   // initialexec.
6134   unsigned WrapperKind = X86ISD::Wrapper;
6135   if (model == TLSModel::LocalExec) {
6136     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6137   } else if (is64Bit) {
6138     assert(model == TLSModel::InitialExec);
6139     OperandFlags = X86II::MO_GOTTPOFF;
6140     WrapperKind = X86ISD::WrapperRIP;
6141   } else {
6142     assert(model == TLSModel::InitialExec);
6143     OperandFlags = X86II::MO_INDNTPOFF;
6144   }
6145
6146   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6147   // exec)
6148   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6149                                            GA->getValueType(0),
6150                                            GA->getOffset(), OperandFlags);
6151   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6152
6153   if (model == TLSModel::InitialExec)
6154     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6155                          MachinePointerInfo::getGOT(), false, false, 0);
6156
6157   // The address of the thread local variable is the add of the thread
6158   // pointer with the offset of the variable.
6159   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6160 }
6161
6162 SDValue
6163 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6164
6165   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6166   const GlobalValue *GV = GA->getGlobal();
6167
6168   if (Subtarget->isTargetELF()) {
6169     // TODO: implement the "local dynamic" model
6170     // TODO: implement the "initial exec"model for pic executables
6171
6172     // If GV is an alias then use the aliasee for determining
6173     // thread-localness.
6174     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6175       GV = GA->resolveAliasedGlobal(false);
6176
6177     TLSModel::Model model
6178       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6179
6180     switch (model) {
6181       case TLSModel::GeneralDynamic:
6182       case TLSModel::LocalDynamic: // not implemented
6183         if (Subtarget->is64Bit())
6184           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6185         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6186
6187       case TLSModel::InitialExec:
6188       case TLSModel::LocalExec:
6189         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6190                                    Subtarget->is64Bit());
6191     }
6192   } else if (Subtarget->isTargetDarwin()) {
6193     // Darwin only has one model of TLS.  Lower to that.
6194     unsigned char OpFlag = 0;
6195     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6196                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6197
6198     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6199     // global base reg.
6200     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6201                   !Subtarget->is64Bit();
6202     if (PIC32)
6203       OpFlag = X86II::MO_TLVP_PIC_BASE;
6204     else
6205       OpFlag = X86II::MO_TLVP;
6206     DebugLoc DL = Op.getDebugLoc();
6207     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6208                                                 GA->getValueType(0),
6209                                                 GA->getOffset(), OpFlag);
6210     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6211
6212     // With PIC32, the address is actually $g + Offset.
6213     if (PIC32)
6214       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6215                            DAG.getNode(X86ISD::GlobalBaseReg,
6216                                        DebugLoc(), getPointerTy()),
6217                            Offset);
6218
6219     // Lowering the machine isd will make sure everything is in the right
6220     // location.
6221     SDValue Chain = DAG.getEntryNode();
6222     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6223     SDValue Args[] = { Chain, Offset };
6224     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6225
6226     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6227     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6228     MFI->setAdjustsStack(true);
6229
6230     // And our return value (tls address) is in the standard call return value
6231     // location.
6232     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6233     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6234   }
6235
6236   assert(false &&
6237          "TLS not implemented for this target.");
6238
6239   llvm_unreachable("Unreachable");
6240   return SDValue();
6241 }
6242
6243
6244 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6245 /// take a 2 x i32 value to shift plus a shift amount.
6246 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6247   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6248   EVT VT = Op.getValueType();
6249   unsigned VTBits = VT.getSizeInBits();
6250   DebugLoc dl = Op.getDebugLoc();
6251   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6252   SDValue ShOpLo = Op.getOperand(0);
6253   SDValue ShOpHi = Op.getOperand(1);
6254   SDValue ShAmt  = Op.getOperand(2);
6255   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6256                                      DAG.getConstant(VTBits - 1, MVT::i8))
6257                        : DAG.getConstant(0, VT);
6258
6259   SDValue Tmp2, Tmp3;
6260   if (Op.getOpcode() == ISD::SHL_PARTS) {
6261     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6262     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6263   } else {
6264     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6265     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6266   }
6267
6268   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6269                                 DAG.getConstant(VTBits, MVT::i8));
6270   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6271                              AndNode, DAG.getConstant(0, MVT::i8));
6272
6273   SDValue Hi, Lo;
6274   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6275   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6276   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6277
6278   if (Op.getOpcode() == ISD::SHL_PARTS) {
6279     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6280     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6281   } else {
6282     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6283     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6284   }
6285
6286   SDValue Ops[2] = { Lo, Hi };
6287   return DAG.getMergeValues(Ops, 2, dl);
6288 }
6289
6290 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6291                                            SelectionDAG &DAG) const {
6292   EVT SrcVT = Op.getOperand(0).getValueType();
6293
6294   if (SrcVT.isVector())
6295     return SDValue();
6296
6297   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6298          "Unknown SINT_TO_FP to lower!");
6299
6300   // These are really Legal; return the operand so the caller accepts it as
6301   // Legal.
6302   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6303     return Op;
6304   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6305       Subtarget->is64Bit()) {
6306     return Op;
6307   }
6308
6309   DebugLoc dl = Op.getDebugLoc();
6310   unsigned Size = SrcVT.getSizeInBits()/8;
6311   MachineFunction &MF = DAG.getMachineFunction();
6312   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6313   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6314   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6315                                StackSlot,
6316                                MachinePointerInfo::getFixedStack(SSFI),
6317                                false, false, 0);
6318   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6319 }
6320
6321 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6322                                      SDValue StackSlot,
6323                                      SelectionDAG &DAG) const {
6324   // Build the FILD
6325   DebugLoc DL = Op.getDebugLoc();
6326   SDVTList Tys;
6327   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6328   if (useSSE)
6329     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6330   else
6331     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6332
6333   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6334
6335   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6336   MachineMemOperand *MMO =
6337     DAG.getMachineFunction()
6338     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6339                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6340
6341   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6342   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6343                                            X86ISD::FILD, DL,
6344                                            Tys, Ops, array_lengthof(Ops),
6345                                            SrcVT, MMO);
6346
6347   if (useSSE) {
6348     Chain = Result.getValue(1);
6349     SDValue InFlag = Result.getValue(2);
6350
6351     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6352     // shouldn't be necessary except that RFP cannot be live across
6353     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6354     MachineFunction &MF = DAG.getMachineFunction();
6355     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6356     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6357     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6358     Tys = DAG.getVTList(MVT::Other);
6359     SDValue Ops[] = {
6360       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6361     };
6362     MachineMemOperand *MMO =
6363       DAG.getMachineFunction()
6364       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6365                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6366
6367     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6368                                     Ops, array_lengthof(Ops),
6369                                     Op.getValueType(), MMO);
6370     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6371                          MachinePointerInfo::getFixedStack(SSFI),
6372                          false, false, 0);
6373   }
6374
6375   return Result;
6376 }
6377
6378 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6379 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6380                                                SelectionDAG &DAG) const {
6381   // This algorithm is not obvious. Here it is in C code, more or less:
6382   /*
6383     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6384       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6385       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6386
6387       // Copy ints to xmm registers.
6388       __m128i xh = _mm_cvtsi32_si128( hi );
6389       __m128i xl = _mm_cvtsi32_si128( lo );
6390
6391       // Combine into low half of a single xmm register.
6392       __m128i x = _mm_unpacklo_epi32( xh, xl );
6393       __m128d d;
6394       double sd;
6395
6396       // Merge in appropriate exponents to give the integer bits the right
6397       // magnitude.
6398       x = _mm_unpacklo_epi32( x, exp );
6399
6400       // Subtract away the biases to deal with the IEEE-754 double precision
6401       // implicit 1.
6402       d = _mm_sub_pd( (__m128d) x, bias );
6403
6404       // All conversions up to here are exact. The correctly rounded result is
6405       // calculated using the current rounding mode using the following
6406       // horizontal add.
6407       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6408       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6409                                 // store doesn't really need to be here (except
6410                                 // maybe to zero the other double)
6411       return sd;
6412     }
6413   */
6414
6415   DebugLoc dl = Op.getDebugLoc();
6416   LLVMContext *Context = DAG.getContext();
6417
6418   // Build some magic constants.
6419   std::vector<Constant*> CV0;
6420   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6421   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6422   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6423   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6424   Constant *C0 = ConstantVector::get(CV0);
6425   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6426
6427   std::vector<Constant*> CV1;
6428   CV1.push_back(
6429     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6430   CV1.push_back(
6431     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6432   Constant *C1 = ConstantVector::get(CV1);
6433   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6434
6435   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6436                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6437                                         Op.getOperand(0),
6438                                         DAG.getIntPtrConstant(1)));
6439   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6440                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6441                                         Op.getOperand(0),
6442                                         DAG.getIntPtrConstant(0)));
6443   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6444   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6445                               MachinePointerInfo::getConstantPool(),
6446                               false, false, 16);
6447   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6448   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6449   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6450                               MachinePointerInfo::getConstantPool(),
6451                               false, false, 16);
6452   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6453
6454   // Add the halves; easiest way is to swap them into another reg first.
6455   int ShufMask[2] = { 1, -1 };
6456   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6457                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6458   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6459   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6460                      DAG.getIntPtrConstant(0));
6461 }
6462
6463 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6464 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6465                                                SelectionDAG &DAG) const {
6466   DebugLoc dl = Op.getDebugLoc();
6467   // FP constant to bias correct the final result.
6468   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6469                                    MVT::f64);
6470
6471   // Load the 32-bit value into an XMM register.
6472   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6473                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6474                                          Op.getOperand(0),
6475                                          DAG.getIntPtrConstant(0)));
6476
6477   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6478                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6479                      DAG.getIntPtrConstant(0));
6480
6481   // Or the load with the bias.
6482   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6483                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6484                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6485                                                    MVT::v2f64, Load)),
6486                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6487                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6488                                                    MVT::v2f64, Bias)));
6489   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6490                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6491                    DAG.getIntPtrConstant(0));
6492
6493   // Subtract the bias.
6494   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6495
6496   // Handle final rounding.
6497   EVT DestVT = Op.getValueType();
6498
6499   if (DestVT.bitsLT(MVT::f64)) {
6500     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6501                        DAG.getIntPtrConstant(0));
6502   } else if (DestVT.bitsGT(MVT::f64)) {
6503     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6504   }
6505
6506   // Handle final rounding.
6507   return Sub;
6508 }
6509
6510 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6511                                            SelectionDAG &DAG) const {
6512   SDValue N0 = Op.getOperand(0);
6513   DebugLoc dl = Op.getDebugLoc();
6514
6515   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6516   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6517   // the optimization here.
6518   if (DAG.SignBitIsZero(N0))
6519     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6520
6521   EVT SrcVT = N0.getValueType();
6522   EVT DstVT = Op.getValueType();
6523   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6524     return LowerUINT_TO_FP_i64(Op, DAG);
6525   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6526     return LowerUINT_TO_FP_i32(Op, DAG);
6527
6528   // Make a 64-bit buffer, and use it to build an FILD.
6529   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6530   if (SrcVT == MVT::i32) {
6531     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6532     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6533                                      getPointerTy(), StackSlot, WordOff);
6534     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6535                                   StackSlot, MachinePointerInfo(),
6536                                   false, false, 0);
6537     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6538                                   OffsetSlot, MachinePointerInfo(),
6539                                   false, false, 0);
6540     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6541     return Fild;
6542   }
6543
6544   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6545   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6546                                 StackSlot, MachinePointerInfo(),
6547                                false, false, 0);
6548   // For i64 source, we need to add the appropriate power of 2 if the input
6549   // was negative.  This is the same as the optimization in
6550   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6551   // we must be careful to do the computation in x87 extended precision, not
6552   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6553   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6554   MachineMemOperand *MMO =
6555     DAG.getMachineFunction()
6556     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6557                           MachineMemOperand::MOLoad, 8, 8);
6558
6559   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6560   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6561   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6562                                          MVT::i64, MMO);
6563
6564   APInt FF(32, 0x5F800000ULL);
6565
6566   // Check whether the sign bit is set.
6567   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6568                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6569                                  ISD::SETLT);
6570
6571   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6572   SDValue FudgePtr = DAG.getConstantPool(
6573                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6574                                          getPointerTy());
6575
6576   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6577   SDValue Zero = DAG.getIntPtrConstant(0);
6578   SDValue Four = DAG.getIntPtrConstant(4);
6579   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6580                                Zero, Four);
6581   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6582
6583   // Load the value out, extending it from f32 to f80.
6584   // FIXME: Avoid the extend by constructing the right constant pool?
6585   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6586                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6587                                  MVT::f32, false, false, 4);
6588   // Extend everything to 80 bits to force it to be done on x87.
6589   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6590   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6591 }
6592
6593 std::pair<SDValue,SDValue> X86TargetLowering::
6594 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6595   DebugLoc DL = Op.getDebugLoc();
6596
6597   EVT DstTy = Op.getValueType();
6598
6599   if (!IsSigned) {
6600     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6601     DstTy = MVT::i64;
6602   }
6603
6604   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6605          DstTy.getSimpleVT() >= MVT::i16 &&
6606          "Unknown FP_TO_SINT to lower!");
6607
6608   // These are really Legal.
6609   if (DstTy == MVT::i32 &&
6610       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6611     return std::make_pair(SDValue(), SDValue());
6612   if (Subtarget->is64Bit() &&
6613       DstTy == MVT::i64 &&
6614       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6615     return std::make_pair(SDValue(), SDValue());
6616
6617   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6618   // stack slot.
6619   MachineFunction &MF = DAG.getMachineFunction();
6620   unsigned MemSize = DstTy.getSizeInBits()/8;
6621   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6622   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6623
6624
6625
6626   unsigned Opc;
6627   switch (DstTy.getSimpleVT().SimpleTy) {
6628   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6629   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6630   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6631   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6632   }
6633
6634   SDValue Chain = DAG.getEntryNode();
6635   SDValue Value = Op.getOperand(0);
6636   EVT TheVT = Op.getOperand(0).getValueType();
6637   if (isScalarFPTypeInSSEReg(TheVT)) {
6638     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6639     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6640                          MachinePointerInfo::getFixedStack(SSFI),
6641                          false, false, 0);
6642     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6643     SDValue Ops[] = {
6644       Chain, StackSlot, DAG.getValueType(TheVT)
6645     };
6646
6647     MachineMemOperand *MMO =
6648       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6649                               MachineMemOperand::MOLoad, MemSize, MemSize);
6650     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6651                                     DstTy, MMO);
6652     Chain = Value.getValue(1);
6653     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6654     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6655   }
6656
6657   MachineMemOperand *MMO =
6658     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6659                             MachineMemOperand::MOStore, MemSize, MemSize);
6660
6661   // Build the FP_TO_INT*_IN_MEM
6662   SDValue Ops[] = { Chain, Value, StackSlot };
6663   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6664                                          Ops, 3, DstTy, MMO);
6665
6666   return std::make_pair(FIST, StackSlot);
6667 }
6668
6669 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6670                                            SelectionDAG &DAG) const {
6671   if (Op.getValueType().isVector())
6672     return SDValue();
6673
6674   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6675   SDValue FIST = Vals.first, StackSlot = Vals.second;
6676   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6677   if (FIST.getNode() == 0) return Op;
6678
6679   // Load the result.
6680   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6681                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6682 }
6683
6684 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6685                                            SelectionDAG &DAG) const {
6686   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6687   SDValue FIST = Vals.first, StackSlot = Vals.second;
6688   assert(FIST.getNode() && "Unexpected failure");
6689
6690   // Load the result.
6691   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6692                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6693 }
6694
6695 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6696                                      SelectionDAG &DAG) const {
6697   LLVMContext *Context = DAG.getContext();
6698   DebugLoc dl = Op.getDebugLoc();
6699   EVT VT = Op.getValueType();
6700   EVT EltVT = VT;
6701   if (VT.isVector())
6702     EltVT = VT.getVectorElementType();
6703   std::vector<Constant*> CV;
6704   if (EltVT == MVT::f64) {
6705     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6706     CV.push_back(C);
6707     CV.push_back(C);
6708   } else {
6709     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6710     CV.push_back(C);
6711     CV.push_back(C);
6712     CV.push_back(C);
6713     CV.push_back(C);
6714   }
6715   Constant *C = ConstantVector::get(CV);
6716   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6717   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6718                              MachinePointerInfo::getConstantPool(),
6719                              false, false, 16);
6720   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6721 }
6722
6723 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6724   LLVMContext *Context = DAG.getContext();
6725   DebugLoc dl = Op.getDebugLoc();
6726   EVT VT = Op.getValueType();
6727   EVT EltVT = VT;
6728   if (VT.isVector())
6729     EltVT = VT.getVectorElementType();
6730   std::vector<Constant*> CV;
6731   if (EltVT == MVT::f64) {
6732     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6733     CV.push_back(C);
6734     CV.push_back(C);
6735   } else {
6736     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6737     CV.push_back(C);
6738     CV.push_back(C);
6739     CV.push_back(C);
6740     CV.push_back(C);
6741   }
6742   Constant *C = ConstantVector::get(CV);
6743   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6744   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6745                              MachinePointerInfo::getConstantPool(),
6746                              false, false, 16);
6747   if (VT.isVector()) {
6748     return DAG.getNode(ISD::BITCAST, dl, VT,
6749                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6750                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6751                                 Op.getOperand(0)),
6752                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6753   } else {
6754     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6755   }
6756 }
6757
6758 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6759   LLVMContext *Context = DAG.getContext();
6760   SDValue Op0 = Op.getOperand(0);
6761   SDValue Op1 = Op.getOperand(1);
6762   DebugLoc dl = Op.getDebugLoc();
6763   EVT VT = Op.getValueType();
6764   EVT SrcVT = Op1.getValueType();
6765
6766   // If second operand is smaller, extend it first.
6767   if (SrcVT.bitsLT(VT)) {
6768     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6769     SrcVT = VT;
6770   }
6771   // And if it is bigger, shrink it first.
6772   if (SrcVT.bitsGT(VT)) {
6773     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6774     SrcVT = VT;
6775   }
6776
6777   // At this point the operands and the result should have the same
6778   // type, and that won't be f80 since that is not custom lowered.
6779
6780   // First get the sign bit of second operand.
6781   std::vector<Constant*> CV;
6782   if (SrcVT == MVT::f64) {
6783     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6784     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6785   } else {
6786     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6787     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6788     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6789     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6790   }
6791   Constant *C = ConstantVector::get(CV);
6792   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6793   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6794                               MachinePointerInfo::getConstantPool(),
6795                               false, false, 16);
6796   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6797
6798   // Shift sign bit right or left if the two operands have different types.
6799   if (SrcVT.bitsGT(VT)) {
6800     // Op0 is MVT::f32, Op1 is MVT::f64.
6801     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6802     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6803                           DAG.getConstant(32, MVT::i32));
6804     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6805     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6806                           DAG.getIntPtrConstant(0));
6807   }
6808
6809   // Clear first operand sign bit.
6810   CV.clear();
6811   if (VT == MVT::f64) {
6812     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6813     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6814   } else {
6815     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6816     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6817     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6818     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6819   }
6820   C = ConstantVector::get(CV);
6821   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6822   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6823                               MachinePointerInfo::getConstantPool(),
6824                               false, false, 16);
6825   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6826
6827   // Or the value with the sign bit.
6828   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6829 }
6830
6831 /// Emit nodes that will be selected as "test Op0,Op0", or something
6832 /// equivalent.
6833 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6834                                     SelectionDAG &DAG) const {
6835   DebugLoc dl = Op.getDebugLoc();
6836
6837   // CF and OF aren't always set the way we want. Determine which
6838   // of these we need.
6839   bool NeedCF = false;
6840   bool NeedOF = false;
6841   switch (X86CC) {
6842   default: break;
6843   case X86::COND_A: case X86::COND_AE:
6844   case X86::COND_B: case X86::COND_BE:
6845     NeedCF = true;
6846     break;
6847   case X86::COND_G: case X86::COND_GE:
6848   case X86::COND_L: case X86::COND_LE:
6849   case X86::COND_O: case X86::COND_NO:
6850     NeedOF = true;
6851     break;
6852   }
6853
6854   // See if we can use the EFLAGS value from the operand instead of
6855   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6856   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6857   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6858     // Emit a CMP with 0, which is the TEST pattern.
6859     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6860                        DAG.getConstant(0, Op.getValueType()));
6861
6862   unsigned Opcode = 0;
6863   unsigned NumOperands = 0;
6864   switch (Op.getNode()->getOpcode()) {
6865   case ISD::ADD:
6866     // Due to an isel shortcoming, be conservative if this add is likely to be
6867     // selected as part of a load-modify-store instruction. When the root node
6868     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6869     // uses of other nodes in the match, such as the ADD in this case. This
6870     // leads to the ADD being left around and reselected, with the result being
6871     // two adds in the output.  Alas, even if none our users are stores, that
6872     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6873     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6874     // climbing the DAG back to the root, and it doesn't seem to be worth the
6875     // effort.
6876     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6877            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6878       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6879         goto default_case;
6880
6881     if (ConstantSDNode *C =
6882         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6883       // An add of one will be selected as an INC.
6884       if (C->getAPIntValue() == 1) {
6885         Opcode = X86ISD::INC;
6886         NumOperands = 1;
6887         break;
6888       }
6889
6890       // An add of negative one (subtract of one) will be selected as a DEC.
6891       if (C->getAPIntValue().isAllOnesValue()) {
6892         Opcode = X86ISD::DEC;
6893         NumOperands = 1;
6894         break;
6895       }
6896     }
6897
6898     // Otherwise use a regular EFLAGS-setting add.
6899     Opcode = X86ISD::ADD;
6900     NumOperands = 2;
6901     break;
6902   case ISD::AND: {
6903     // If the primary and result isn't used, don't bother using X86ISD::AND,
6904     // because a TEST instruction will be better.
6905     bool NonFlagUse = false;
6906     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6907            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6908       SDNode *User = *UI;
6909       unsigned UOpNo = UI.getOperandNo();
6910       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6911         // Look pass truncate.
6912         UOpNo = User->use_begin().getOperandNo();
6913         User = *User->use_begin();
6914       }
6915
6916       if (User->getOpcode() != ISD::BRCOND &&
6917           User->getOpcode() != ISD::SETCC &&
6918           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6919         NonFlagUse = true;
6920         break;
6921       }
6922     }
6923
6924     if (!NonFlagUse)
6925       break;
6926   }
6927     // FALL THROUGH
6928   case ISD::SUB:
6929   case ISD::OR:
6930   case ISD::XOR:
6931     // Due to the ISEL shortcoming noted above, be conservative if this op is
6932     // likely to be selected as part of a load-modify-store instruction.
6933     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6934            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6935       if (UI->getOpcode() == ISD::STORE)
6936         goto default_case;
6937
6938     // Otherwise use a regular EFLAGS-setting instruction.
6939     switch (Op.getNode()->getOpcode()) {
6940     default: llvm_unreachable("unexpected operator!");
6941     case ISD::SUB: Opcode = X86ISD::SUB; break;
6942     case ISD::OR:  Opcode = X86ISD::OR;  break;
6943     case ISD::XOR: Opcode = X86ISD::XOR; break;
6944     case ISD::AND: Opcode = X86ISD::AND; break;
6945     }
6946
6947     NumOperands = 2;
6948     break;
6949   case X86ISD::ADD:
6950   case X86ISD::SUB:
6951   case X86ISD::INC:
6952   case X86ISD::DEC:
6953   case X86ISD::OR:
6954   case X86ISD::XOR:
6955   case X86ISD::AND:
6956     return SDValue(Op.getNode(), 1);
6957   default:
6958   default_case:
6959     break;
6960   }
6961
6962   if (Opcode == 0)
6963     // Emit a CMP with 0, which is the TEST pattern.
6964     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6965                        DAG.getConstant(0, Op.getValueType()));
6966
6967   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6968   SmallVector<SDValue, 4> Ops;
6969   for (unsigned i = 0; i != NumOperands; ++i)
6970     Ops.push_back(Op.getOperand(i));
6971
6972   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6973   DAG.ReplaceAllUsesWith(Op, New);
6974   return SDValue(New.getNode(), 1);
6975 }
6976
6977 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6978 /// equivalent.
6979 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6980                                    SelectionDAG &DAG) const {
6981   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6982     if (C->getAPIntValue() == 0)
6983       return EmitTest(Op0, X86CC, DAG);
6984
6985   DebugLoc dl = Op0.getDebugLoc();
6986   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6987 }
6988
6989 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6990 /// if it's possible.
6991 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6992                                      DebugLoc dl, SelectionDAG &DAG) const {
6993   SDValue Op0 = And.getOperand(0);
6994   SDValue Op1 = And.getOperand(1);
6995   if (Op0.getOpcode() == ISD::TRUNCATE)
6996     Op0 = Op0.getOperand(0);
6997   if (Op1.getOpcode() == ISD::TRUNCATE)
6998     Op1 = Op1.getOperand(0);
6999
7000   SDValue LHS, RHS;
7001   if (Op1.getOpcode() == ISD::SHL)
7002     std::swap(Op0, Op1);
7003   if (Op0.getOpcode() == ISD::SHL) {
7004     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7005       if (And00C->getZExtValue() == 1) {
7006         // If we looked past a truncate, check that it's only truncating away
7007         // known zeros.
7008         unsigned BitWidth = Op0.getValueSizeInBits();
7009         unsigned AndBitWidth = And.getValueSizeInBits();
7010         if (BitWidth > AndBitWidth) {
7011           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7012           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7013           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7014             return SDValue();
7015         }
7016         LHS = Op1;
7017         RHS = Op0.getOperand(1);
7018       }
7019   } else if (Op1.getOpcode() == ISD::Constant) {
7020     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7021     SDValue AndLHS = Op0;
7022     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7023       LHS = AndLHS.getOperand(0);
7024       RHS = AndLHS.getOperand(1);
7025     }
7026   }
7027
7028   if (LHS.getNode()) {
7029     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7030     // instruction.  Since the shift amount is in-range-or-undefined, we know
7031     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7032     // the encoding for the i16 version is larger than the i32 version.
7033     // Also promote i16 to i32 for performance / code size reason.
7034     if (LHS.getValueType() == MVT::i8 ||
7035         LHS.getValueType() == MVT::i16)
7036       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7037
7038     // If the operand types disagree, extend the shift amount to match.  Since
7039     // BT ignores high bits (like shifts) we can use anyextend.
7040     if (LHS.getValueType() != RHS.getValueType())
7041       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7042
7043     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7044     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7045     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7046                        DAG.getConstant(Cond, MVT::i8), BT);
7047   }
7048
7049   return SDValue();
7050 }
7051
7052 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7053   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7054   SDValue Op0 = Op.getOperand(0);
7055   SDValue Op1 = Op.getOperand(1);
7056   DebugLoc dl = Op.getDebugLoc();
7057   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7058
7059   // Optimize to BT if possible.
7060   // Lower (X & (1 << N)) == 0 to BT(X, N).
7061   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7062   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7063   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7064       Op1.getOpcode() == ISD::Constant &&
7065       cast<ConstantSDNode>(Op1)->isNullValue() &&
7066       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7067     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7068     if (NewSetCC.getNode())
7069       return NewSetCC;
7070   }
7071
7072   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7073   // these.
7074   if (Op1.getOpcode() == ISD::Constant &&
7075       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7076        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7077       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7078
7079     // If the input is a setcc, then reuse the input setcc or use a new one with
7080     // the inverted condition.
7081     if (Op0.getOpcode() == X86ISD::SETCC) {
7082       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7083       bool Invert = (CC == ISD::SETNE) ^
7084         cast<ConstantSDNode>(Op1)->isNullValue();
7085       if (!Invert) return Op0;
7086
7087       CCode = X86::GetOppositeBranchCondition(CCode);
7088       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7089                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7090     }
7091   }
7092
7093   bool isFP = Op1.getValueType().isFloatingPoint();
7094   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7095   if (X86CC == X86::COND_INVALID)
7096     return SDValue();
7097
7098   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7099   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7100                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7101 }
7102
7103 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7104   SDValue Cond;
7105   SDValue Op0 = Op.getOperand(0);
7106   SDValue Op1 = Op.getOperand(1);
7107   SDValue CC = Op.getOperand(2);
7108   EVT VT = Op.getValueType();
7109   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7110   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7111   DebugLoc dl = Op.getDebugLoc();
7112
7113   if (isFP) {
7114     unsigned SSECC = 8;
7115     EVT VT0 = Op0.getValueType();
7116     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7117     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7118     bool Swap = false;
7119
7120     switch (SetCCOpcode) {
7121     default: break;
7122     case ISD::SETOEQ:
7123     case ISD::SETEQ:  SSECC = 0; break;
7124     case ISD::SETOGT:
7125     case ISD::SETGT: Swap = true; // Fallthrough
7126     case ISD::SETLT:
7127     case ISD::SETOLT: SSECC = 1; break;
7128     case ISD::SETOGE:
7129     case ISD::SETGE: Swap = true; // Fallthrough
7130     case ISD::SETLE:
7131     case ISD::SETOLE: SSECC = 2; break;
7132     case ISD::SETUO:  SSECC = 3; break;
7133     case ISD::SETUNE:
7134     case ISD::SETNE:  SSECC = 4; break;
7135     case ISD::SETULE: Swap = true;
7136     case ISD::SETUGE: SSECC = 5; break;
7137     case ISD::SETULT: Swap = true;
7138     case ISD::SETUGT: SSECC = 6; break;
7139     case ISD::SETO:   SSECC = 7; break;
7140     }
7141     if (Swap)
7142       std::swap(Op0, Op1);
7143
7144     // In the two special cases we can't handle, emit two comparisons.
7145     if (SSECC == 8) {
7146       if (SetCCOpcode == ISD::SETUEQ) {
7147         SDValue UNORD, EQ;
7148         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7149         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7150         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7151       }
7152       else if (SetCCOpcode == ISD::SETONE) {
7153         SDValue ORD, NEQ;
7154         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7155         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7156         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7157       }
7158       llvm_unreachable("Illegal FP comparison");
7159     }
7160     // Handle all other FP comparisons here.
7161     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7162   }
7163
7164   // We are handling one of the integer comparisons here.  Since SSE only has
7165   // GT and EQ comparisons for integer, swapping operands and multiple
7166   // operations may be required for some comparisons.
7167   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7168   bool Swap = false, Invert = false, FlipSigns = false;
7169
7170   switch (VT.getSimpleVT().SimpleTy) {
7171   default: break;
7172   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7173   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7174   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7175   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7176   }
7177
7178   switch (SetCCOpcode) {
7179   default: break;
7180   case ISD::SETNE:  Invert = true;
7181   case ISD::SETEQ:  Opc = EQOpc; break;
7182   case ISD::SETLT:  Swap = true;
7183   case ISD::SETGT:  Opc = GTOpc; break;
7184   case ISD::SETGE:  Swap = true;
7185   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7186   case ISD::SETULT: Swap = true;
7187   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7188   case ISD::SETUGE: Swap = true;
7189   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7190   }
7191   if (Swap)
7192     std::swap(Op0, Op1);
7193
7194   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7195   // bits of the inputs before performing those operations.
7196   if (FlipSigns) {
7197     EVT EltVT = VT.getVectorElementType();
7198     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7199                                       EltVT);
7200     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7201     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7202                                     SignBits.size());
7203     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7204     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7205   }
7206
7207   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7208
7209   // If the logical-not of the result is required, perform that now.
7210   if (Invert)
7211     Result = DAG.getNOT(dl, Result, VT);
7212
7213   return Result;
7214 }
7215
7216 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7217 static bool isX86LogicalCmp(SDValue Op) {
7218   unsigned Opc = Op.getNode()->getOpcode();
7219   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7220     return true;
7221   if (Op.getResNo() == 1 &&
7222       (Opc == X86ISD::ADD ||
7223        Opc == X86ISD::SUB ||
7224        Opc == X86ISD::ADC ||
7225        Opc == X86ISD::SBB ||
7226        Opc == X86ISD::SMUL ||
7227        Opc == X86ISD::UMUL ||
7228        Opc == X86ISD::INC ||
7229        Opc == X86ISD::DEC ||
7230        Opc == X86ISD::OR ||
7231        Opc == X86ISD::XOR ||
7232        Opc == X86ISD::AND))
7233     return true;
7234
7235   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7236     return true;
7237
7238   return false;
7239 }
7240
7241 static bool isZero(SDValue V) {
7242   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7243   return C && C->isNullValue();
7244 }
7245
7246 static bool isAllOnes(SDValue V) {
7247   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7248   return C && C->isAllOnesValue();
7249 }
7250
7251 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7252   bool addTest = true;
7253   SDValue Cond  = Op.getOperand(0);
7254   SDValue Op1 = Op.getOperand(1);
7255   SDValue Op2 = Op.getOperand(2);
7256   DebugLoc DL = Op.getDebugLoc();
7257   SDValue CC;
7258
7259   if (Cond.getOpcode() == ISD::SETCC) {
7260     SDValue NewCond = LowerSETCC(Cond, DAG);
7261     if (NewCond.getNode())
7262       Cond = NewCond;
7263   }
7264
7265   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7266   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7267   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7268   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7269   if (Cond.getOpcode() == X86ISD::SETCC &&
7270       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7271       isZero(Cond.getOperand(1).getOperand(1))) {
7272     SDValue Cmp = Cond.getOperand(1);
7273
7274     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7275
7276     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7277         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7278       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7279
7280       SDValue CmpOp0 = Cmp.getOperand(0);
7281       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7282                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7283
7284       SDValue Res =   // Res = 0 or -1.
7285         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7286                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7287
7288       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7289         Res = DAG.getNOT(DL, Res, Res.getValueType());
7290
7291       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7292       if (N2C == 0 || !N2C->isNullValue())
7293         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7294       return Res;
7295     }
7296   }
7297
7298   // Look past (and (setcc_carry (cmp ...)), 1).
7299   if (Cond.getOpcode() == ISD::AND &&
7300       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7301     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7302     if (C && C->getAPIntValue() == 1)
7303       Cond = Cond.getOperand(0);
7304   }
7305
7306   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7307   // setting operand in place of the X86ISD::SETCC.
7308   if (Cond.getOpcode() == X86ISD::SETCC ||
7309       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7310     CC = Cond.getOperand(0);
7311
7312     SDValue Cmp = Cond.getOperand(1);
7313     unsigned Opc = Cmp.getOpcode();
7314     EVT VT = Op.getValueType();
7315
7316     bool IllegalFPCMov = false;
7317     if (VT.isFloatingPoint() && !VT.isVector() &&
7318         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7319       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7320
7321     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7322         Opc == X86ISD::BT) { // FIXME
7323       Cond = Cmp;
7324       addTest = false;
7325     }
7326   }
7327
7328   if (addTest) {
7329     // Look pass the truncate.
7330     if (Cond.getOpcode() == ISD::TRUNCATE)
7331       Cond = Cond.getOperand(0);
7332
7333     // We know the result of AND is compared against zero. Try to match
7334     // it to BT.
7335     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7336       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7337       if (NewSetCC.getNode()) {
7338         CC = NewSetCC.getOperand(0);
7339         Cond = NewSetCC.getOperand(1);
7340         addTest = false;
7341       }
7342     }
7343   }
7344
7345   if (addTest) {
7346     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7347     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7348   }
7349
7350   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7351   // a <  b ?  0 : -1 -> RES = setcc_carry
7352   // a >= b ? -1 :  0 -> RES = setcc_carry
7353   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7354   if (Cond.getOpcode() == X86ISD::CMP) {
7355     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7356
7357     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7358         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7359       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7360                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7361       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7362         return DAG.getNOT(DL, Res, Res.getValueType());
7363       return Res;
7364     }
7365   }
7366
7367   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7368   // condition is true.
7369   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7370   SDValue Ops[] = { Op2, Op1, CC, Cond };
7371   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7372 }
7373
7374 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7375 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7376 // from the AND / OR.
7377 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7378   Opc = Op.getOpcode();
7379   if (Opc != ISD::OR && Opc != ISD::AND)
7380     return false;
7381   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7382           Op.getOperand(0).hasOneUse() &&
7383           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7384           Op.getOperand(1).hasOneUse());
7385 }
7386
7387 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7388 // 1 and that the SETCC node has a single use.
7389 static bool isXor1OfSetCC(SDValue Op) {
7390   if (Op.getOpcode() != ISD::XOR)
7391     return false;
7392   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7393   if (N1C && N1C->getAPIntValue() == 1) {
7394     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7395       Op.getOperand(0).hasOneUse();
7396   }
7397   return false;
7398 }
7399
7400 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7401   bool addTest = true;
7402   SDValue Chain = Op.getOperand(0);
7403   SDValue Cond  = Op.getOperand(1);
7404   SDValue Dest  = Op.getOperand(2);
7405   DebugLoc dl = Op.getDebugLoc();
7406   SDValue CC;
7407
7408   if (Cond.getOpcode() == ISD::SETCC) {
7409     SDValue NewCond = LowerSETCC(Cond, DAG);
7410     if (NewCond.getNode())
7411       Cond = NewCond;
7412   }
7413 #if 0
7414   // FIXME: LowerXALUO doesn't handle these!!
7415   else if (Cond.getOpcode() == X86ISD::ADD  ||
7416            Cond.getOpcode() == X86ISD::SUB  ||
7417            Cond.getOpcode() == X86ISD::SMUL ||
7418            Cond.getOpcode() == X86ISD::UMUL)
7419     Cond = LowerXALUO(Cond, DAG);
7420 #endif
7421
7422   // Look pass (and (setcc_carry (cmp ...)), 1).
7423   if (Cond.getOpcode() == ISD::AND &&
7424       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7425     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7426     if (C && C->getAPIntValue() == 1)
7427       Cond = Cond.getOperand(0);
7428   }
7429
7430   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7431   // setting operand in place of the X86ISD::SETCC.
7432   if (Cond.getOpcode() == X86ISD::SETCC ||
7433       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7434     CC = Cond.getOperand(0);
7435
7436     SDValue Cmp = Cond.getOperand(1);
7437     unsigned Opc = Cmp.getOpcode();
7438     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7439     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7440       Cond = Cmp;
7441       addTest = false;
7442     } else {
7443       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7444       default: break;
7445       case X86::COND_O:
7446       case X86::COND_B:
7447         // These can only come from an arithmetic instruction with overflow,
7448         // e.g. SADDO, UADDO.
7449         Cond = Cond.getNode()->getOperand(1);
7450         addTest = false;
7451         break;
7452       }
7453     }
7454   } else {
7455     unsigned CondOpc;
7456     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7457       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7458       if (CondOpc == ISD::OR) {
7459         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7460         // two branches instead of an explicit OR instruction with a
7461         // separate test.
7462         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7463             isX86LogicalCmp(Cmp)) {
7464           CC = Cond.getOperand(0).getOperand(0);
7465           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7466                               Chain, Dest, CC, Cmp);
7467           CC = Cond.getOperand(1).getOperand(0);
7468           Cond = Cmp;
7469           addTest = false;
7470         }
7471       } else { // ISD::AND
7472         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7473         // two branches instead of an explicit AND instruction with a
7474         // separate test. However, we only do this if this block doesn't
7475         // have a fall-through edge, because this requires an explicit
7476         // jmp when the condition is false.
7477         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7478             isX86LogicalCmp(Cmp) &&
7479             Op.getNode()->hasOneUse()) {
7480           X86::CondCode CCode =
7481             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7482           CCode = X86::GetOppositeBranchCondition(CCode);
7483           CC = DAG.getConstant(CCode, MVT::i8);
7484           SDNode *User = *Op.getNode()->use_begin();
7485           // Look for an unconditional branch following this conditional branch.
7486           // We need this because we need to reverse the successors in order
7487           // to implement FCMP_OEQ.
7488           if (User->getOpcode() == ISD::BR) {
7489             SDValue FalseBB = User->getOperand(1);
7490             SDNode *NewBR =
7491               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7492             assert(NewBR == User);
7493             (void)NewBR;
7494             Dest = FalseBB;
7495
7496             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7497                                 Chain, Dest, CC, Cmp);
7498             X86::CondCode CCode =
7499               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7500             CCode = X86::GetOppositeBranchCondition(CCode);
7501             CC = DAG.getConstant(CCode, MVT::i8);
7502             Cond = Cmp;
7503             addTest = false;
7504           }
7505         }
7506       }
7507     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7508       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7509       // It should be transformed during dag combiner except when the condition
7510       // is set by a arithmetics with overflow node.
7511       X86::CondCode CCode =
7512         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7513       CCode = X86::GetOppositeBranchCondition(CCode);
7514       CC = DAG.getConstant(CCode, MVT::i8);
7515       Cond = Cond.getOperand(0).getOperand(1);
7516       addTest = false;
7517     }
7518   }
7519
7520   if (addTest) {
7521     // Look pass the truncate.
7522     if (Cond.getOpcode() == ISD::TRUNCATE)
7523       Cond = Cond.getOperand(0);
7524
7525     // We know the result of AND is compared against zero. Try to match
7526     // it to BT.
7527     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7528       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7529       if (NewSetCC.getNode()) {
7530         CC = NewSetCC.getOperand(0);
7531         Cond = NewSetCC.getOperand(1);
7532         addTest = false;
7533       }
7534     }
7535   }
7536
7537   if (addTest) {
7538     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7539     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7540   }
7541   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7542                      Chain, Dest, CC, Cond);
7543 }
7544
7545
7546 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7547 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7548 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7549 // that the guard pages used by the OS virtual memory manager are allocated in
7550 // correct sequence.
7551 SDValue
7552 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7553                                            SelectionDAG &DAG) const {
7554   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7555          "This should be used only on Windows targets");
7556   DebugLoc dl = Op.getDebugLoc();
7557
7558   // Get the inputs.
7559   SDValue Chain = Op.getOperand(0);
7560   SDValue Size  = Op.getOperand(1);
7561   // FIXME: Ensure alignment here
7562
7563   SDValue Flag;
7564
7565   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7566
7567   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7568   Flag = Chain.getValue(1);
7569
7570   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7571
7572   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7573   Flag = Chain.getValue(1);
7574
7575   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7576
7577   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7578   return DAG.getMergeValues(Ops1, 2, dl);
7579 }
7580
7581 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7582   MachineFunction &MF = DAG.getMachineFunction();
7583   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7584
7585   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7586   DebugLoc DL = Op.getDebugLoc();
7587
7588   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7589     // vastart just stores the address of the VarArgsFrameIndex slot into the
7590     // memory location argument.
7591     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7592                                    getPointerTy());
7593     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7594                         MachinePointerInfo(SV), false, false, 0);
7595   }
7596
7597   // __va_list_tag:
7598   //   gp_offset         (0 - 6 * 8)
7599   //   fp_offset         (48 - 48 + 8 * 16)
7600   //   overflow_arg_area (point to parameters coming in memory).
7601   //   reg_save_area
7602   SmallVector<SDValue, 8> MemOps;
7603   SDValue FIN = Op.getOperand(1);
7604   // Store gp_offset
7605   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7606                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7607                                                MVT::i32),
7608                                FIN, MachinePointerInfo(SV), false, false, 0);
7609   MemOps.push_back(Store);
7610
7611   // Store fp_offset
7612   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7613                     FIN, DAG.getIntPtrConstant(4));
7614   Store = DAG.getStore(Op.getOperand(0), DL,
7615                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7616                                        MVT::i32),
7617                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7618   MemOps.push_back(Store);
7619
7620   // Store ptr to overflow_arg_area
7621   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7622                     FIN, DAG.getIntPtrConstant(4));
7623   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7624                                     getPointerTy());
7625   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7626                        MachinePointerInfo(SV, 8),
7627                        false, false, 0);
7628   MemOps.push_back(Store);
7629
7630   // Store ptr to reg_save_area.
7631   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7632                     FIN, DAG.getIntPtrConstant(8));
7633   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7634                                     getPointerTy());
7635   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7636                        MachinePointerInfo(SV, 16), false, false, 0);
7637   MemOps.push_back(Store);
7638   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7639                      &MemOps[0], MemOps.size());
7640 }
7641
7642 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7643   assert(Subtarget->is64Bit() &&
7644          "LowerVAARG only handles 64-bit va_arg!");
7645   assert((Subtarget->isTargetLinux() ||
7646           Subtarget->isTargetDarwin()) &&
7647           "Unhandled target in LowerVAARG");
7648   assert(Op.getNode()->getNumOperands() == 4);
7649   SDValue Chain = Op.getOperand(0);
7650   SDValue SrcPtr = Op.getOperand(1);
7651   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7652   unsigned Align = Op.getConstantOperandVal(3);
7653   DebugLoc dl = Op.getDebugLoc();
7654
7655   EVT ArgVT = Op.getNode()->getValueType(0);
7656   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7657   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7658   uint8_t ArgMode;
7659
7660   // Decide which area this value should be read from.
7661   // TODO: Implement the AMD64 ABI in its entirety. This simple
7662   // selection mechanism works only for the basic types.
7663   if (ArgVT == MVT::f80) {
7664     llvm_unreachable("va_arg for f80 not yet implemented");
7665   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7666     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7667   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7668     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7669   } else {
7670     llvm_unreachable("Unhandled argument type in LowerVAARG");
7671   }
7672
7673   if (ArgMode == 2) {
7674     // Sanity Check: Make sure using fp_offset makes sense.
7675     assert(!UseSoftFloat &&
7676            !(DAG.getMachineFunction()
7677                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7678            Subtarget->hasXMM());
7679   }
7680
7681   // Insert VAARG_64 node into the DAG
7682   // VAARG_64 returns two values: Variable Argument Address, Chain
7683   SmallVector<SDValue, 11> InstOps;
7684   InstOps.push_back(Chain);
7685   InstOps.push_back(SrcPtr);
7686   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7687   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7688   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7689   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7690   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7691                                           VTs, &InstOps[0], InstOps.size(),
7692                                           MVT::i64,
7693                                           MachinePointerInfo(SV),
7694                                           /*Align=*/0,
7695                                           /*Volatile=*/false,
7696                                           /*ReadMem=*/true,
7697                                           /*WriteMem=*/true);
7698   Chain = VAARG.getValue(1);
7699
7700   // Load the next argument and return it
7701   return DAG.getLoad(ArgVT, dl,
7702                      Chain,
7703                      VAARG,
7704                      MachinePointerInfo(),
7705                      false, false, 0);
7706 }
7707
7708 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7709   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7710   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7711   SDValue Chain = Op.getOperand(0);
7712   SDValue DstPtr = Op.getOperand(1);
7713   SDValue SrcPtr = Op.getOperand(2);
7714   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7715   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7716   DebugLoc DL = Op.getDebugLoc();
7717
7718   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7719                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7720                        false,
7721                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7722 }
7723
7724 SDValue
7725 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7726   DebugLoc dl = Op.getDebugLoc();
7727   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7728   switch (IntNo) {
7729   default: return SDValue();    // Don't custom lower most intrinsics.
7730   // Comparison intrinsics.
7731   case Intrinsic::x86_sse_comieq_ss:
7732   case Intrinsic::x86_sse_comilt_ss:
7733   case Intrinsic::x86_sse_comile_ss:
7734   case Intrinsic::x86_sse_comigt_ss:
7735   case Intrinsic::x86_sse_comige_ss:
7736   case Intrinsic::x86_sse_comineq_ss:
7737   case Intrinsic::x86_sse_ucomieq_ss:
7738   case Intrinsic::x86_sse_ucomilt_ss:
7739   case Intrinsic::x86_sse_ucomile_ss:
7740   case Intrinsic::x86_sse_ucomigt_ss:
7741   case Intrinsic::x86_sse_ucomige_ss:
7742   case Intrinsic::x86_sse_ucomineq_ss:
7743   case Intrinsic::x86_sse2_comieq_sd:
7744   case Intrinsic::x86_sse2_comilt_sd:
7745   case Intrinsic::x86_sse2_comile_sd:
7746   case Intrinsic::x86_sse2_comigt_sd:
7747   case Intrinsic::x86_sse2_comige_sd:
7748   case Intrinsic::x86_sse2_comineq_sd:
7749   case Intrinsic::x86_sse2_ucomieq_sd:
7750   case Intrinsic::x86_sse2_ucomilt_sd:
7751   case Intrinsic::x86_sse2_ucomile_sd:
7752   case Intrinsic::x86_sse2_ucomigt_sd:
7753   case Intrinsic::x86_sse2_ucomige_sd:
7754   case Intrinsic::x86_sse2_ucomineq_sd: {
7755     unsigned Opc = 0;
7756     ISD::CondCode CC = ISD::SETCC_INVALID;
7757     switch (IntNo) {
7758     default: break;
7759     case Intrinsic::x86_sse_comieq_ss:
7760     case Intrinsic::x86_sse2_comieq_sd:
7761       Opc = X86ISD::COMI;
7762       CC = ISD::SETEQ;
7763       break;
7764     case Intrinsic::x86_sse_comilt_ss:
7765     case Intrinsic::x86_sse2_comilt_sd:
7766       Opc = X86ISD::COMI;
7767       CC = ISD::SETLT;
7768       break;
7769     case Intrinsic::x86_sse_comile_ss:
7770     case Intrinsic::x86_sse2_comile_sd:
7771       Opc = X86ISD::COMI;
7772       CC = ISD::SETLE;
7773       break;
7774     case Intrinsic::x86_sse_comigt_ss:
7775     case Intrinsic::x86_sse2_comigt_sd:
7776       Opc = X86ISD::COMI;
7777       CC = ISD::SETGT;
7778       break;
7779     case Intrinsic::x86_sse_comige_ss:
7780     case Intrinsic::x86_sse2_comige_sd:
7781       Opc = X86ISD::COMI;
7782       CC = ISD::SETGE;
7783       break;
7784     case Intrinsic::x86_sse_comineq_ss:
7785     case Intrinsic::x86_sse2_comineq_sd:
7786       Opc = X86ISD::COMI;
7787       CC = ISD::SETNE;
7788       break;
7789     case Intrinsic::x86_sse_ucomieq_ss:
7790     case Intrinsic::x86_sse2_ucomieq_sd:
7791       Opc = X86ISD::UCOMI;
7792       CC = ISD::SETEQ;
7793       break;
7794     case Intrinsic::x86_sse_ucomilt_ss:
7795     case Intrinsic::x86_sse2_ucomilt_sd:
7796       Opc = X86ISD::UCOMI;
7797       CC = ISD::SETLT;
7798       break;
7799     case Intrinsic::x86_sse_ucomile_ss:
7800     case Intrinsic::x86_sse2_ucomile_sd:
7801       Opc = X86ISD::UCOMI;
7802       CC = ISD::SETLE;
7803       break;
7804     case Intrinsic::x86_sse_ucomigt_ss:
7805     case Intrinsic::x86_sse2_ucomigt_sd:
7806       Opc = X86ISD::UCOMI;
7807       CC = ISD::SETGT;
7808       break;
7809     case Intrinsic::x86_sse_ucomige_ss:
7810     case Intrinsic::x86_sse2_ucomige_sd:
7811       Opc = X86ISD::UCOMI;
7812       CC = ISD::SETGE;
7813       break;
7814     case Intrinsic::x86_sse_ucomineq_ss:
7815     case Intrinsic::x86_sse2_ucomineq_sd:
7816       Opc = X86ISD::UCOMI;
7817       CC = ISD::SETNE;
7818       break;
7819     }
7820
7821     SDValue LHS = Op.getOperand(1);
7822     SDValue RHS = Op.getOperand(2);
7823     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7824     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7825     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7826     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7827                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7828     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7829   }
7830   // ptest and testp intrinsics. The intrinsic these come from are designed to
7831   // return an integer value, not just an instruction so lower it to the ptest
7832   // or testp pattern and a setcc for the result.
7833   case Intrinsic::x86_sse41_ptestz:
7834   case Intrinsic::x86_sse41_ptestc:
7835   case Intrinsic::x86_sse41_ptestnzc:
7836   case Intrinsic::x86_avx_ptestz_256:
7837   case Intrinsic::x86_avx_ptestc_256:
7838   case Intrinsic::x86_avx_ptestnzc_256:
7839   case Intrinsic::x86_avx_vtestz_ps:
7840   case Intrinsic::x86_avx_vtestc_ps:
7841   case Intrinsic::x86_avx_vtestnzc_ps:
7842   case Intrinsic::x86_avx_vtestz_pd:
7843   case Intrinsic::x86_avx_vtestc_pd:
7844   case Intrinsic::x86_avx_vtestnzc_pd:
7845   case Intrinsic::x86_avx_vtestz_ps_256:
7846   case Intrinsic::x86_avx_vtestc_ps_256:
7847   case Intrinsic::x86_avx_vtestnzc_ps_256:
7848   case Intrinsic::x86_avx_vtestz_pd_256:
7849   case Intrinsic::x86_avx_vtestc_pd_256:
7850   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7851     bool IsTestPacked = false;
7852     unsigned X86CC = 0;
7853     switch (IntNo) {
7854     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7855     case Intrinsic::x86_avx_vtestz_ps:
7856     case Intrinsic::x86_avx_vtestz_pd:
7857     case Intrinsic::x86_avx_vtestz_ps_256:
7858     case Intrinsic::x86_avx_vtestz_pd_256:
7859       IsTestPacked = true; // Fallthrough
7860     case Intrinsic::x86_sse41_ptestz:
7861     case Intrinsic::x86_avx_ptestz_256:
7862       // ZF = 1
7863       X86CC = X86::COND_E;
7864       break;
7865     case Intrinsic::x86_avx_vtestc_ps:
7866     case Intrinsic::x86_avx_vtestc_pd:
7867     case Intrinsic::x86_avx_vtestc_ps_256:
7868     case Intrinsic::x86_avx_vtestc_pd_256:
7869       IsTestPacked = true; // Fallthrough
7870     case Intrinsic::x86_sse41_ptestc:
7871     case Intrinsic::x86_avx_ptestc_256:
7872       // CF = 1
7873       X86CC = X86::COND_B;
7874       break;
7875     case Intrinsic::x86_avx_vtestnzc_ps:
7876     case Intrinsic::x86_avx_vtestnzc_pd:
7877     case Intrinsic::x86_avx_vtestnzc_ps_256:
7878     case Intrinsic::x86_avx_vtestnzc_pd_256:
7879       IsTestPacked = true; // Fallthrough
7880     case Intrinsic::x86_sse41_ptestnzc:
7881     case Intrinsic::x86_avx_ptestnzc_256:
7882       // ZF and CF = 0
7883       X86CC = X86::COND_A;
7884       break;
7885     }
7886
7887     SDValue LHS = Op.getOperand(1);
7888     SDValue RHS = Op.getOperand(2);
7889     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7890     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7891     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7892     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7893     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7894   }
7895
7896   // Fix vector shift instructions where the last operand is a non-immediate
7897   // i32 value.
7898   case Intrinsic::x86_sse2_pslli_w:
7899   case Intrinsic::x86_sse2_pslli_d:
7900   case Intrinsic::x86_sse2_pslli_q:
7901   case Intrinsic::x86_sse2_psrli_w:
7902   case Intrinsic::x86_sse2_psrli_d:
7903   case Intrinsic::x86_sse2_psrli_q:
7904   case Intrinsic::x86_sse2_psrai_w:
7905   case Intrinsic::x86_sse2_psrai_d:
7906   case Intrinsic::x86_mmx_pslli_w:
7907   case Intrinsic::x86_mmx_pslli_d:
7908   case Intrinsic::x86_mmx_pslli_q:
7909   case Intrinsic::x86_mmx_psrli_w:
7910   case Intrinsic::x86_mmx_psrli_d:
7911   case Intrinsic::x86_mmx_psrli_q:
7912   case Intrinsic::x86_mmx_psrai_w:
7913   case Intrinsic::x86_mmx_psrai_d: {
7914     SDValue ShAmt = Op.getOperand(2);
7915     if (isa<ConstantSDNode>(ShAmt))
7916       return SDValue();
7917
7918     unsigned NewIntNo = 0;
7919     EVT ShAmtVT = MVT::v4i32;
7920     switch (IntNo) {
7921     case Intrinsic::x86_sse2_pslli_w:
7922       NewIntNo = Intrinsic::x86_sse2_psll_w;
7923       break;
7924     case Intrinsic::x86_sse2_pslli_d:
7925       NewIntNo = Intrinsic::x86_sse2_psll_d;
7926       break;
7927     case Intrinsic::x86_sse2_pslli_q:
7928       NewIntNo = Intrinsic::x86_sse2_psll_q;
7929       break;
7930     case Intrinsic::x86_sse2_psrli_w:
7931       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7932       break;
7933     case Intrinsic::x86_sse2_psrli_d:
7934       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7935       break;
7936     case Intrinsic::x86_sse2_psrli_q:
7937       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7938       break;
7939     case Intrinsic::x86_sse2_psrai_w:
7940       NewIntNo = Intrinsic::x86_sse2_psra_w;
7941       break;
7942     case Intrinsic::x86_sse2_psrai_d:
7943       NewIntNo = Intrinsic::x86_sse2_psra_d;
7944       break;
7945     default: {
7946       ShAmtVT = MVT::v2i32;
7947       switch (IntNo) {
7948       case Intrinsic::x86_mmx_pslli_w:
7949         NewIntNo = Intrinsic::x86_mmx_psll_w;
7950         break;
7951       case Intrinsic::x86_mmx_pslli_d:
7952         NewIntNo = Intrinsic::x86_mmx_psll_d;
7953         break;
7954       case Intrinsic::x86_mmx_pslli_q:
7955         NewIntNo = Intrinsic::x86_mmx_psll_q;
7956         break;
7957       case Intrinsic::x86_mmx_psrli_w:
7958         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7959         break;
7960       case Intrinsic::x86_mmx_psrli_d:
7961         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7962         break;
7963       case Intrinsic::x86_mmx_psrli_q:
7964         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7965         break;
7966       case Intrinsic::x86_mmx_psrai_w:
7967         NewIntNo = Intrinsic::x86_mmx_psra_w;
7968         break;
7969       case Intrinsic::x86_mmx_psrai_d:
7970         NewIntNo = Intrinsic::x86_mmx_psra_d;
7971         break;
7972       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7973       }
7974       break;
7975     }
7976     }
7977
7978     // The vector shift intrinsics with scalars uses 32b shift amounts but
7979     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7980     // to be zero.
7981     SDValue ShOps[4];
7982     ShOps[0] = ShAmt;
7983     ShOps[1] = DAG.getConstant(0, MVT::i32);
7984     if (ShAmtVT == MVT::v4i32) {
7985       ShOps[2] = DAG.getUNDEF(MVT::i32);
7986       ShOps[3] = DAG.getUNDEF(MVT::i32);
7987       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7988     } else {
7989       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7990 // FIXME this must be lowered to get rid of the invalid type.
7991     }
7992
7993     EVT VT = Op.getValueType();
7994     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7995     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7996                        DAG.getConstant(NewIntNo, MVT::i32),
7997                        Op.getOperand(1), ShAmt);
7998   }
7999   }
8000 }
8001
8002 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8003                                            SelectionDAG &DAG) const {
8004   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8005   MFI->setReturnAddressIsTaken(true);
8006
8007   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8008   DebugLoc dl = Op.getDebugLoc();
8009
8010   if (Depth > 0) {
8011     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8012     SDValue Offset =
8013       DAG.getConstant(TD->getPointerSize(),
8014                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8015     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8016                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8017                                    FrameAddr, Offset),
8018                        MachinePointerInfo(), false, false, 0);
8019   }
8020
8021   // Just load the return address.
8022   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8023   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8024                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8025 }
8026
8027 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8028   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8029   MFI->setFrameAddressIsTaken(true);
8030
8031   EVT VT = Op.getValueType();
8032   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8033   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8034   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8035   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8036   while (Depth--)
8037     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8038                             MachinePointerInfo(),
8039                             false, false, 0);
8040   return FrameAddr;
8041 }
8042
8043 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8044                                                      SelectionDAG &DAG) const {
8045   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8046 }
8047
8048 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8049   MachineFunction &MF = DAG.getMachineFunction();
8050   SDValue Chain     = Op.getOperand(0);
8051   SDValue Offset    = Op.getOperand(1);
8052   SDValue Handler   = Op.getOperand(2);
8053   DebugLoc dl       = Op.getDebugLoc();
8054
8055   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8056                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8057                                      getPointerTy());
8058   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8059
8060   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8061                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8062   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8063   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8064                        false, false, 0);
8065   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8066   MF.getRegInfo().addLiveOut(StoreAddrReg);
8067
8068   return DAG.getNode(X86ISD::EH_RETURN, dl,
8069                      MVT::Other,
8070                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8071 }
8072
8073 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8074                                              SelectionDAG &DAG) const {
8075   SDValue Root = Op.getOperand(0);
8076   SDValue Trmp = Op.getOperand(1); // trampoline
8077   SDValue FPtr = Op.getOperand(2); // nested function
8078   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8079   DebugLoc dl  = Op.getDebugLoc();
8080
8081   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8082
8083   if (Subtarget->is64Bit()) {
8084     SDValue OutChains[6];
8085
8086     // Large code-model.
8087     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8088     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8089
8090     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8091     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8092
8093     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8094
8095     // Load the pointer to the nested function into R11.
8096     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8097     SDValue Addr = Trmp;
8098     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8099                                 Addr, MachinePointerInfo(TrmpAddr),
8100                                 false, false, 0);
8101
8102     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8103                        DAG.getConstant(2, MVT::i64));
8104     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8105                                 MachinePointerInfo(TrmpAddr, 2),
8106                                 false, false, 2);
8107
8108     // Load the 'nest' parameter value into R10.
8109     // R10 is specified in X86CallingConv.td
8110     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8111     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8112                        DAG.getConstant(10, MVT::i64));
8113     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8114                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8115                                 false, false, 0);
8116
8117     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8118                        DAG.getConstant(12, MVT::i64));
8119     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8120                                 MachinePointerInfo(TrmpAddr, 12),
8121                                 false, false, 2);
8122
8123     // Jump to the nested function.
8124     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8125     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8126                        DAG.getConstant(20, MVT::i64));
8127     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8128                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8129                                 false, false, 0);
8130
8131     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8132     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8133                        DAG.getConstant(22, MVT::i64));
8134     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8135                                 MachinePointerInfo(TrmpAddr, 22),
8136                                 false, false, 0);
8137
8138     SDValue Ops[] =
8139       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8140     return DAG.getMergeValues(Ops, 2, dl);
8141   } else {
8142     const Function *Func =
8143       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8144     CallingConv::ID CC = Func->getCallingConv();
8145     unsigned NestReg;
8146
8147     switch (CC) {
8148     default:
8149       llvm_unreachable("Unsupported calling convention");
8150     case CallingConv::C:
8151     case CallingConv::X86_StdCall: {
8152       // Pass 'nest' parameter in ECX.
8153       // Must be kept in sync with X86CallingConv.td
8154       NestReg = X86::ECX;
8155
8156       // Check that ECX wasn't needed by an 'inreg' parameter.
8157       const FunctionType *FTy = Func->getFunctionType();
8158       const AttrListPtr &Attrs = Func->getAttributes();
8159
8160       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8161         unsigned InRegCount = 0;
8162         unsigned Idx = 1;
8163
8164         for (FunctionType::param_iterator I = FTy->param_begin(),
8165              E = FTy->param_end(); I != E; ++I, ++Idx)
8166           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8167             // FIXME: should only count parameters that are lowered to integers.
8168             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8169
8170         if (InRegCount > 2) {
8171           report_fatal_error("Nest register in use - reduce number of inreg"
8172                              " parameters!");
8173         }
8174       }
8175       break;
8176     }
8177     case CallingConv::X86_FastCall:
8178     case CallingConv::X86_ThisCall:
8179     case CallingConv::Fast:
8180       // Pass 'nest' parameter in EAX.
8181       // Must be kept in sync with X86CallingConv.td
8182       NestReg = X86::EAX;
8183       break;
8184     }
8185
8186     SDValue OutChains[4];
8187     SDValue Addr, Disp;
8188
8189     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8190                        DAG.getConstant(10, MVT::i32));
8191     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8192
8193     // This is storing the opcode for MOV32ri.
8194     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8195     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8196     OutChains[0] = DAG.getStore(Root, dl,
8197                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8198                                 Trmp, MachinePointerInfo(TrmpAddr),
8199                                 false, false, 0);
8200
8201     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8202                        DAG.getConstant(1, MVT::i32));
8203     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8204                                 MachinePointerInfo(TrmpAddr, 1),
8205                                 false, false, 1);
8206
8207     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8208     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8209                        DAG.getConstant(5, MVT::i32));
8210     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8211                                 MachinePointerInfo(TrmpAddr, 5),
8212                                 false, false, 1);
8213
8214     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8215                        DAG.getConstant(6, MVT::i32));
8216     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8217                                 MachinePointerInfo(TrmpAddr, 6),
8218                                 false, false, 1);
8219
8220     SDValue Ops[] =
8221       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8222     return DAG.getMergeValues(Ops, 2, dl);
8223   }
8224 }
8225
8226 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8227                                             SelectionDAG &DAG) const {
8228   /*
8229    The rounding mode is in bits 11:10 of FPSR, and has the following
8230    settings:
8231      00 Round to nearest
8232      01 Round to -inf
8233      10 Round to +inf
8234      11 Round to 0
8235
8236   FLT_ROUNDS, on the other hand, expects the following:
8237     -1 Undefined
8238      0 Round to 0
8239      1 Round to nearest
8240      2 Round to +inf
8241      3 Round to -inf
8242
8243   To perform the conversion, we do:
8244     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8245   */
8246
8247   MachineFunction &MF = DAG.getMachineFunction();
8248   const TargetMachine &TM = MF.getTarget();
8249   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8250   unsigned StackAlignment = TFI.getStackAlignment();
8251   EVT VT = Op.getValueType();
8252   DebugLoc DL = Op.getDebugLoc();
8253
8254   // Save FP Control Word to stack slot
8255   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8256   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8257
8258
8259   MachineMemOperand *MMO =
8260    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8261                            MachineMemOperand::MOStore, 2, 2);
8262
8263   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8264   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8265                                           DAG.getVTList(MVT::Other),
8266                                           Ops, 2, MVT::i16, MMO);
8267
8268   // Load FP Control Word from stack slot
8269   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8270                             MachinePointerInfo(), false, false, 0);
8271
8272   // Transform as necessary
8273   SDValue CWD1 =
8274     DAG.getNode(ISD::SRL, DL, MVT::i16,
8275                 DAG.getNode(ISD::AND, DL, MVT::i16,
8276                             CWD, DAG.getConstant(0x800, MVT::i16)),
8277                 DAG.getConstant(11, MVT::i8));
8278   SDValue CWD2 =
8279     DAG.getNode(ISD::SRL, DL, MVT::i16,
8280                 DAG.getNode(ISD::AND, DL, MVT::i16,
8281                             CWD, DAG.getConstant(0x400, MVT::i16)),
8282                 DAG.getConstant(9, MVT::i8));
8283
8284   SDValue RetVal =
8285     DAG.getNode(ISD::AND, DL, MVT::i16,
8286                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8287                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8288                             DAG.getConstant(1, MVT::i16)),
8289                 DAG.getConstant(3, MVT::i16));
8290
8291
8292   return DAG.getNode((VT.getSizeInBits() < 16 ?
8293                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8294 }
8295
8296 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8297   EVT VT = Op.getValueType();
8298   EVT OpVT = VT;
8299   unsigned NumBits = VT.getSizeInBits();
8300   DebugLoc dl = Op.getDebugLoc();
8301
8302   Op = Op.getOperand(0);
8303   if (VT == MVT::i8) {
8304     // Zero extend to i32 since there is not an i8 bsr.
8305     OpVT = MVT::i32;
8306     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8307   }
8308
8309   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8310   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8311   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8312
8313   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8314   SDValue Ops[] = {
8315     Op,
8316     DAG.getConstant(NumBits+NumBits-1, OpVT),
8317     DAG.getConstant(X86::COND_E, MVT::i8),
8318     Op.getValue(1)
8319   };
8320   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8321
8322   // Finally xor with NumBits-1.
8323   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8324
8325   if (VT == MVT::i8)
8326     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8327   return Op;
8328 }
8329
8330 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8331   EVT VT = Op.getValueType();
8332   EVT OpVT = VT;
8333   unsigned NumBits = VT.getSizeInBits();
8334   DebugLoc dl = Op.getDebugLoc();
8335
8336   Op = Op.getOperand(0);
8337   if (VT == MVT::i8) {
8338     OpVT = MVT::i32;
8339     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8340   }
8341
8342   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8343   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8344   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8345
8346   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8347   SDValue Ops[] = {
8348     Op,
8349     DAG.getConstant(NumBits, OpVT),
8350     DAG.getConstant(X86::COND_E, MVT::i8),
8351     Op.getValue(1)
8352   };
8353   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8354
8355   if (VT == MVT::i8)
8356     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8357   return Op;
8358 }
8359
8360 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8361   EVT VT = Op.getValueType();
8362   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8363   DebugLoc dl = Op.getDebugLoc();
8364
8365   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8366   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8367   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8368   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8369   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8370   //
8371   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8372   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8373   //  return AloBlo + AloBhi + AhiBlo;
8374
8375   SDValue A = Op.getOperand(0);
8376   SDValue B = Op.getOperand(1);
8377
8378   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8379                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8380                        A, DAG.getConstant(32, MVT::i32));
8381   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8382                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8383                        B, DAG.getConstant(32, MVT::i32));
8384   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8385                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8386                        A, B);
8387   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8388                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8389                        A, Bhi);
8390   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8391                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8392                        Ahi, B);
8393   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8394                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8395                        AloBhi, DAG.getConstant(32, MVT::i32));
8396   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8397                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8398                        AhiBlo, DAG.getConstant(32, MVT::i32));
8399   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8400   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8401   return Res;
8402 }
8403
8404 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8405   EVT VT = Op.getValueType();
8406   DebugLoc dl = Op.getDebugLoc();
8407   SDValue R = Op.getOperand(0);
8408
8409   LLVMContext *Context = DAG.getContext();
8410
8411   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8412
8413   if (VT == MVT::v4i32) {
8414     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8415                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8416                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8417
8418     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8419
8420     std::vector<Constant*> CV(4, CI);
8421     Constant *C = ConstantVector::get(CV);
8422     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8423     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8424                                  MachinePointerInfo::getConstantPool(),
8425                                  false, false, 16);
8426
8427     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8428     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8429     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8430     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8431   }
8432   if (VT == MVT::v16i8) {
8433     // a = a << 5;
8434     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8435                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8436                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8437
8438     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8439     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8440
8441     std::vector<Constant*> CVM1(16, CM1);
8442     std::vector<Constant*> CVM2(16, CM2);
8443     Constant *C = ConstantVector::get(CVM1);
8444     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8445     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8446                             MachinePointerInfo::getConstantPool(),
8447                             false, false, 16);
8448
8449     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8450     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8451     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8452                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8453                     DAG.getConstant(4, MVT::i32));
8454     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8455     // a += a
8456     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8457
8458     C = ConstantVector::get(CVM2);
8459     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8460     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8461                     MachinePointerInfo::getConstantPool(),
8462                     false, false, 16);
8463
8464     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8465     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8466     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8467                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8468                     DAG.getConstant(2, MVT::i32));
8469     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8470     // a += a
8471     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8472
8473     // return pblendv(r, r+r, a);
8474     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8475                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8476     return R;
8477   }
8478   return SDValue();
8479 }
8480
8481 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8482   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8483   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8484   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8485   // has only one use.
8486   SDNode *N = Op.getNode();
8487   SDValue LHS = N->getOperand(0);
8488   SDValue RHS = N->getOperand(1);
8489   unsigned BaseOp = 0;
8490   unsigned Cond = 0;
8491   DebugLoc DL = Op.getDebugLoc();
8492   switch (Op.getOpcode()) {
8493   default: llvm_unreachable("Unknown ovf instruction!");
8494   case ISD::SADDO:
8495     // A subtract of one will be selected as a INC. Note that INC doesn't
8496     // set CF, so we can't do this for UADDO.
8497     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8498       if (C->getAPIntValue() == 1) {
8499         BaseOp = X86ISD::INC;
8500         Cond = X86::COND_O;
8501         break;
8502       }
8503     BaseOp = X86ISD::ADD;
8504     Cond = X86::COND_O;
8505     break;
8506   case ISD::UADDO:
8507     BaseOp = X86ISD::ADD;
8508     Cond = X86::COND_B;
8509     break;
8510   case ISD::SSUBO:
8511     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8512     // set CF, so we can't do this for USUBO.
8513     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8514       if (C->getAPIntValue() == 1) {
8515         BaseOp = X86ISD::DEC;
8516         Cond = X86::COND_O;
8517         break;
8518       }
8519     BaseOp = X86ISD::SUB;
8520     Cond = X86::COND_O;
8521     break;
8522   case ISD::USUBO:
8523     BaseOp = X86ISD::SUB;
8524     Cond = X86::COND_B;
8525     break;
8526   case ISD::SMULO:
8527     BaseOp = X86ISD::SMUL;
8528     Cond = X86::COND_O;
8529     break;
8530   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8531     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8532                                  MVT::i32);
8533     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8534
8535     SDValue SetCC =
8536       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8537                   DAG.getConstant(X86::COND_O, MVT::i32),
8538                   SDValue(Sum.getNode(), 2));
8539
8540     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8541     return Sum;
8542   }
8543   }
8544
8545   // Also sets EFLAGS.
8546   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8547   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8548
8549   SDValue SetCC =
8550     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8551                 DAG.getConstant(Cond, MVT::i32),
8552                 SDValue(Sum.getNode(), 1));
8553
8554   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8555   return Sum;
8556 }
8557
8558 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8559   DebugLoc dl = Op.getDebugLoc();
8560
8561   if (!Subtarget->hasSSE2()) {
8562     SDValue Chain = Op.getOperand(0);
8563     SDValue Zero = DAG.getConstant(0,
8564                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8565     SDValue Ops[] = {
8566       DAG.getRegister(X86::ESP, MVT::i32), // Base
8567       DAG.getTargetConstant(1, MVT::i8),   // Scale
8568       DAG.getRegister(0, MVT::i32),        // Index
8569       DAG.getTargetConstant(0, MVT::i32),  // Disp
8570       DAG.getRegister(0, MVT::i32),        // Segment.
8571       Zero,
8572       Chain
8573     };
8574     SDNode *Res =
8575       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8576                           array_lengthof(Ops));
8577     return SDValue(Res, 0);
8578   }
8579
8580   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8581   if (!isDev)
8582     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8583
8584   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8585   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8586   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8587   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8588
8589   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8590   if (!Op1 && !Op2 && !Op3 && Op4)
8591     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8592
8593   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8594   if (Op1 && !Op2 && !Op3 && !Op4)
8595     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8596
8597   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8598   //           (MFENCE)>;
8599   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8600 }
8601
8602 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8603   EVT T = Op.getValueType();
8604   DebugLoc DL = Op.getDebugLoc();
8605   unsigned Reg = 0;
8606   unsigned size = 0;
8607   switch(T.getSimpleVT().SimpleTy) {
8608   default:
8609     assert(false && "Invalid value type!");
8610   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8611   case MVT::i16: Reg = X86::AX;  size = 2; break;
8612   case MVT::i32: Reg = X86::EAX; size = 4; break;
8613   case MVT::i64:
8614     assert(Subtarget->is64Bit() && "Node not type legal!");
8615     Reg = X86::RAX; size = 8;
8616     break;
8617   }
8618   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8619                                     Op.getOperand(2), SDValue());
8620   SDValue Ops[] = { cpIn.getValue(0),
8621                     Op.getOperand(1),
8622                     Op.getOperand(3),
8623                     DAG.getTargetConstant(size, MVT::i8),
8624                     cpIn.getValue(1) };
8625   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8626   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8627   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8628                                            Ops, 5, T, MMO);
8629   SDValue cpOut =
8630     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8631   return cpOut;
8632 }
8633
8634 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8635                                                  SelectionDAG &DAG) const {
8636   assert(Subtarget->is64Bit() && "Result not type legalized?");
8637   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8638   SDValue TheChain = Op.getOperand(0);
8639   DebugLoc dl = Op.getDebugLoc();
8640   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8641   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8642   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8643                                    rax.getValue(2));
8644   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8645                             DAG.getConstant(32, MVT::i8));
8646   SDValue Ops[] = {
8647     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8648     rdx.getValue(1)
8649   };
8650   return DAG.getMergeValues(Ops, 2, dl);
8651 }
8652
8653 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8654                                             SelectionDAG &DAG) const {
8655   EVT SrcVT = Op.getOperand(0).getValueType();
8656   EVT DstVT = Op.getValueType();
8657   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8658          Subtarget->hasMMX() && "Unexpected custom BITCAST");
8659   assert((DstVT == MVT::i64 ||
8660           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8661          "Unexpected custom BITCAST");
8662   // i64 <=> MMX conversions are Legal.
8663   if (SrcVT==MVT::i64 && DstVT.isVector())
8664     return Op;
8665   if (DstVT==MVT::i64 && SrcVT.isVector())
8666     return Op;
8667   // MMX <=> MMX conversions are Legal.
8668   if (SrcVT.isVector() && DstVT.isVector())
8669     return Op;
8670   // All other conversions need to be expanded.
8671   return SDValue();
8672 }
8673
8674 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8675   SDNode *Node = Op.getNode();
8676   DebugLoc dl = Node->getDebugLoc();
8677   EVT T = Node->getValueType(0);
8678   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8679                               DAG.getConstant(0, T), Node->getOperand(2));
8680   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8681                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8682                        Node->getOperand(0),
8683                        Node->getOperand(1), negOp,
8684                        cast<AtomicSDNode>(Node)->getSrcValue(),
8685                        cast<AtomicSDNode>(Node)->getAlignment());
8686 }
8687
8688 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8689   EVT VT = Op.getNode()->getValueType(0);
8690
8691   // Let legalize expand this if it isn't a legal type yet.
8692   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8693     return SDValue();
8694
8695   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8696
8697   unsigned Opc;
8698   bool ExtraOp = false;
8699   switch (Op.getOpcode()) {
8700   default: assert(0 && "Invalid code");
8701   case ISD::ADDC: Opc = X86ISD::ADD; break;
8702   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8703   case ISD::SUBC: Opc = X86ISD::SUB; break;
8704   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8705   }
8706
8707   if (!ExtraOp)
8708     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8709                        Op.getOperand(1));
8710   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8711                      Op.getOperand(1), Op.getOperand(2));
8712 }
8713
8714 /// LowerOperation - Provide custom lowering hooks for some operations.
8715 ///
8716 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8717   switch (Op.getOpcode()) {
8718   default: llvm_unreachable("Should not custom lower this!");
8719   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8720   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8721   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8722   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8723   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8724   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8725   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8726   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8727   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
8728   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
8729   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8730   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8731   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8732   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8733   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8734   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8735   case ISD::SHL_PARTS:
8736   case ISD::SRA_PARTS:
8737   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8738   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8739   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8740   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8741   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8742   case ISD::FABS:               return LowerFABS(Op, DAG);
8743   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8744   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8745   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8746   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8747   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8748   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8749   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8750   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8751   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8752   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8753   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8754   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8755   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8756   case ISD::FRAME_TO_ARGS_OFFSET:
8757                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8758   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8759   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8760   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8761   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8762   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8763   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8764   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8765   case ISD::SHL:                return LowerSHL(Op, DAG);
8766   case ISD::SADDO:
8767   case ISD::UADDO:
8768   case ISD::SSUBO:
8769   case ISD::USUBO:
8770   case ISD::SMULO:
8771   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8772   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8773   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8774   case ISD::ADDC:
8775   case ISD::ADDE:
8776   case ISD::SUBC:
8777   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8778   }
8779 }
8780
8781 void X86TargetLowering::
8782 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8783                         SelectionDAG &DAG, unsigned NewOp) const {
8784   EVT T = Node->getValueType(0);
8785   DebugLoc dl = Node->getDebugLoc();
8786   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8787
8788   SDValue Chain = Node->getOperand(0);
8789   SDValue In1 = Node->getOperand(1);
8790   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8791                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8792   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8793                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8794   SDValue Ops[] = { Chain, In1, In2L, In2H };
8795   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8796   SDValue Result =
8797     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8798                             cast<MemSDNode>(Node)->getMemOperand());
8799   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8800   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8801   Results.push_back(Result.getValue(2));
8802 }
8803
8804 /// ReplaceNodeResults - Replace a node with an illegal result type
8805 /// with a new node built out of custom code.
8806 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8807                                            SmallVectorImpl<SDValue>&Results,
8808                                            SelectionDAG &DAG) const {
8809   DebugLoc dl = N->getDebugLoc();
8810   switch (N->getOpcode()) {
8811   default:
8812     assert(false && "Do not know how to custom type legalize this operation!");
8813     return;
8814   case ISD::ADDC:
8815   case ISD::ADDE:
8816   case ISD::SUBC:
8817   case ISD::SUBE:
8818     // We don't want to expand or promote these.
8819     return;
8820   case ISD::FP_TO_SINT: {
8821     std::pair<SDValue,SDValue> Vals =
8822         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8823     SDValue FIST = Vals.first, StackSlot = Vals.second;
8824     if (FIST.getNode() != 0) {
8825       EVT VT = N->getValueType(0);
8826       // Return a load from the stack slot.
8827       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8828                                     MachinePointerInfo(), false, false, 0));
8829     }
8830     return;
8831   }
8832   case ISD::READCYCLECOUNTER: {
8833     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8834     SDValue TheChain = N->getOperand(0);
8835     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8836     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8837                                      rd.getValue(1));
8838     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8839                                      eax.getValue(2));
8840     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8841     SDValue Ops[] = { eax, edx };
8842     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8843     Results.push_back(edx.getValue(1));
8844     return;
8845   }
8846   case ISD::ATOMIC_CMP_SWAP: {
8847     EVT T = N->getValueType(0);
8848     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8849     SDValue cpInL, cpInH;
8850     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8851                         DAG.getConstant(0, MVT::i32));
8852     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8853                         DAG.getConstant(1, MVT::i32));
8854     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8855     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8856                              cpInL.getValue(1));
8857     SDValue swapInL, swapInH;
8858     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8859                           DAG.getConstant(0, MVT::i32));
8860     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8861                           DAG.getConstant(1, MVT::i32));
8862     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8863                                cpInH.getValue(1));
8864     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8865                                swapInL.getValue(1));
8866     SDValue Ops[] = { swapInH.getValue(0),
8867                       N->getOperand(1),
8868                       swapInH.getValue(1) };
8869     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8870     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8871     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8872                                              Ops, 3, T, MMO);
8873     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8874                                         MVT::i32, Result.getValue(1));
8875     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8876                                         MVT::i32, cpOutL.getValue(2));
8877     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8878     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8879     Results.push_back(cpOutH.getValue(1));
8880     return;
8881   }
8882   case ISD::ATOMIC_LOAD_ADD:
8883     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8884     return;
8885   case ISD::ATOMIC_LOAD_AND:
8886     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8887     return;
8888   case ISD::ATOMIC_LOAD_NAND:
8889     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8890     return;
8891   case ISD::ATOMIC_LOAD_OR:
8892     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8893     return;
8894   case ISD::ATOMIC_LOAD_SUB:
8895     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8896     return;
8897   case ISD::ATOMIC_LOAD_XOR:
8898     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8899     return;
8900   case ISD::ATOMIC_SWAP:
8901     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8902     return;
8903   }
8904 }
8905
8906 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8907   switch (Opcode) {
8908   default: return NULL;
8909   case X86ISD::BSF:                return "X86ISD::BSF";
8910   case X86ISD::BSR:                return "X86ISD::BSR";
8911   case X86ISD::SHLD:               return "X86ISD::SHLD";
8912   case X86ISD::SHRD:               return "X86ISD::SHRD";
8913   case X86ISD::FAND:               return "X86ISD::FAND";
8914   case X86ISD::FOR:                return "X86ISD::FOR";
8915   case X86ISD::FXOR:               return "X86ISD::FXOR";
8916   case X86ISD::FSRL:               return "X86ISD::FSRL";
8917   case X86ISD::FILD:               return "X86ISD::FILD";
8918   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8919   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8920   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8921   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8922   case X86ISD::FLD:                return "X86ISD::FLD";
8923   case X86ISD::FST:                return "X86ISD::FST";
8924   case X86ISD::CALL:               return "X86ISD::CALL";
8925   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8926   case X86ISD::BT:                 return "X86ISD::BT";
8927   case X86ISD::CMP:                return "X86ISD::CMP";
8928   case X86ISD::COMI:               return "X86ISD::COMI";
8929   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8930   case X86ISD::SETCC:              return "X86ISD::SETCC";
8931   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8932   case X86ISD::CMOV:               return "X86ISD::CMOV";
8933   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8934   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8935   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8936   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8937   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8938   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8939   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8940   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8941   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8942   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8943   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8944   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8945   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8946   case X86ISD::PANDN:              return "X86ISD::PANDN";
8947   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
8948   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
8949   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
8950   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
8951   case X86ISD::FMAX:               return "X86ISD::FMAX";
8952   case X86ISD::FMIN:               return "X86ISD::FMIN";
8953   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8954   case X86ISD::FRCP:               return "X86ISD::FRCP";
8955   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8956   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8957   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8958   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8959   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8960   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8961   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8962   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8963   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8964   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8965   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8966   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8967   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8968   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8969   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8970   case X86ISD::VSHL:               return "X86ISD::VSHL";
8971   case X86ISD::VSRL:               return "X86ISD::VSRL";
8972   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8973   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8974   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8975   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8976   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8977   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8978   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8979   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8980   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8981   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8982   case X86ISD::ADD:                return "X86ISD::ADD";
8983   case X86ISD::SUB:                return "X86ISD::SUB";
8984   case X86ISD::ADC:                return "X86ISD::ADC";
8985   case X86ISD::SBB:                return "X86ISD::SBB";
8986   case X86ISD::SMUL:               return "X86ISD::SMUL";
8987   case X86ISD::UMUL:               return "X86ISD::UMUL";
8988   case X86ISD::INC:                return "X86ISD::INC";
8989   case X86ISD::DEC:                return "X86ISD::DEC";
8990   case X86ISD::OR:                 return "X86ISD::OR";
8991   case X86ISD::XOR:                return "X86ISD::XOR";
8992   case X86ISD::AND:                return "X86ISD::AND";
8993   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8994   case X86ISD::PTEST:              return "X86ISD::PTEST";
8995   case X86ISD::TESTP:              return "X86ISD::TESTP";
8996   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8997   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8998   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8999   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9000   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9001   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9002   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9003   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9004   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9005   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9006   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9007   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9008   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9009   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9010   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9011   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9012   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9013   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9014   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9015   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9016   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9017   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9018   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9019   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9020   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9021   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9022   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9023   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9024   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9025   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9026   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9027   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9028   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9029   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9030   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9031   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9032   }
9033 }
9034
9035 // isLegalAddressingMode - Return true if the addressing mode represented
9036 // by AM is legal for this target, for a load/store of the specified type.
9037 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9038                                               const Type *Ty) const {
9039   // X86 supports extremely general addressing modes.
9040   CodeModel::Model M = getTargetMachine().getCodeModel();
9041   Reloc::Model R = getTargetMachine().getRelocationModel();
9042
9043   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9044   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9045     return false;
9046
9047   if (AM.BaseGV) {
9048     unsigned GVFlags =
9049       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9050
9051     // If a reference to this global requires an extra load, we can't fold it.
9052     if (isGlobalStubReference(GVFlags))
9053       return false;
9054
9055     // If BaseGV requires a register for the PIC base, we cannot also have a
9056     // BaseReg specified.
9057     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9058       return false;
9059
9060     // If lower 4G is not available, then we must use rip-relative addressing.
9061     if ((M != CodeModel::Small || R != Reloc::Static) &&
9062         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9063       return false;
9064   }
9065
9066   switch (AM.Scale) {
9067   case 0:
9068   case 1:
9069   case 2:
9070   case 4:
9071   case 8:
9072     // These scales always work.
9073     break;
9074   case 3:
9075   case 5:
9076   case 9:
9077     // These scales are formed with basereg+scalereg.  Only accept if there is
9078     // no basereg yet.
9079     if (AM.HasBaseReg)
9080       return false;
9081     break;
9082   default:  // Other stuff never works.
9083     return false;
9084   }
9085
9086   return true;
9087 }
9088
9089
9090 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9091   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9092     return false;
9093   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9094   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9095   if (NumBits1 <= NumBits2)
9096     return false;
9097   return true;
9098 }
9099
9100 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9101   if (!VT1.isInteger() || !VT2.isInteger())
9102     return false;
9103   unsigned NumBits1 = VT1.getSizeInBits();
9104   unsigned NumBits2 = VT2.getSizeInBits();
9105   if (NumBits1 <= NumBits2)
9106     return false;
9107   return true;
9108 }
9109
9110 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9111   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9112   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9113 }
9114
9115 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9116   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9117   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9118 }
9119
9120 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9121   // i16 instructions are longer (0x66 prefix) and potentially slower.
9122   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9123 }
9124
9125 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9126 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9127 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9128 /// are assumed to be legal.
9129 bool
9130 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9131                                       EVT VT) const {
9132   // Very little shuffling can be done for 64-bit vectors right now.
9133   if (VT.getSizeInBits() == 64)
9134     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9135
9136   // FIXME: pshufb, blends, shifts.
9137   return (VT.getVectorNumElements() == 2 ||
9138           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9139           isMOVLMask(M, VT) ||
9140           isSHUFPMask(M, VT) ||
9141           isPSHUFDMask(M, VT) ||
9142           isPSHUFHWMask(M, VT) ||
9143           isPSHUFLWMask(M, VT) ||
9144           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9145           isUNPCKLMask(M, VT) ||
9146           isUNPCKHMask(M, VT) ||
9147           isUNPCKL_v_undef_Mask(M, VT) ||
9148           isUNPCKH_v_undef_Mask(M, VT));
9149 }
9150
9151 bool
9152 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9153                                           EVT VT) const {
9154   unsigned NumElts = VT.getVectorNumElements();
9155   // FIXME: This collection of masks seems suspect.
9156   if (NumElts == 2)
9157     return true;
9158   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9159     return (isMOVLMask(Mask, VT)  ||
9160             isCommutedMOVLMask(Mask, VT, true) ||
9161             isSHUFPMask(Mask, VT) ||
9162             isCommutedSHUFPMask(Mask, VT));
9163   }
9164   return false;
9165 }
9166
9167 //===----------------------------------------------------------------------===//
9168 //                           X86 Scheduler Hooks
9169 //===----------------------------------------------------------------------===//
9170
9171 // private utility function
9172 MachineBasicBlock *
9173 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9174                                                        MachineBasicBlock *MBB,
9175                                                        unsigned regOpc,
9176                                                        unsigned immOpc,
9177                                                        unsigned LoadOpc,
9178                                                        unsigned CXchgOpc,
9179                                                        unsigned notOpc,
9180                                                        unsigned EAXreg,
9181                                                        TargetRegisterClass *RC,
9182                                                        bool invSrc) const {
9183   // For the atomic bitwise operator, we generate
9184   //   thisMBB:
9185   //   newMBB:
9186   //     ld  t1 = [bitinstr.addr]
9187   //     op  t2 = t1, [bitinstr.val]
9188   //     mov EAX = t1
9189   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9190   //     bz  newMBB
9191   //     fallthrough -->nextMBB
9192   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9193   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9194   MachineFunction::iterator MBBIter = MBB;
9195   ++MBBIter;
9196
9197   /// First build the CFG
9198   MachineFunction *F = MBB->getParent();
9199   MachineBasicBlock *thisMBB = MBB;
9200   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9201   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9202   F->insert(MBBIter, newMBB);
9203   F->insert(MBBIter, nextMBB);
9204
9205   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9206   nextMBB->splice(nextMBB->begin(), thisMBB,
9207                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9208                   thisMBB->end());
9209   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9210
9211   // Update thisMBB to fall through to newMBB
9212   thisMBB->addSuccessor(newMBB);
9213
9214   // newMBB jumps to itself and fall through to nextMBB
9215   newMBB->addSuccessor(nextMBB);
9216   newMBB->addSuccessor(newMBB);
9217
9218   // Insert instructions into newMBB based on incoming instruction
9219   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9220          "unexpected number of operands");
9221   DebugLoc dl = bInstr->getDebugLoc();
9222   MachineOperand& destOper = bInstr->getOperand(0);
9223   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9224   int numArgs = bInstr->getNumOperands() - 1;
9225   for (int i=0; i < numArgs; ++i)
9226     argOpers[i] = &bInstr->getOperand(i+1);
9227
9228   // x86 address has 4 operands: base, index, scale, and displacement
9229   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9230   int valArgIndx = lastAddrIndx + 1;
9231
9232   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9233   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9234   for (int i=0; i <= lastAddrIndx; ++i)
9235     (*MIB).addOperand(*argOpers[i]);
9236
9237   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9238   if (invSrc) {
9239     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9240   }
9241   else
9242     tt = t1;
9243
9244   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9245   assert((argOpers[valArgIndx]->isReg() ||
9246           argOpers[valArgIndx]->isImm()) &&
9247          "invalid operand");
9248   if (argOpers[valArgIndx]->isReg())
9249     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9250   else
9251     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9252   MIB.addReg(tt);
9253   (*MIB).addOperand(*argOpers[valArgIndx]);
9254
9255   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9256   MIB.addReg(t1);
9257
9258   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9259   for (int i=0; i <= lastAddrIndx; ++i)
9260     (*MIB).addOperand(*argOpers[i]);
9261   MIB.addReg(t2);
9262   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9263   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9264                     bInstr->memoperands_end());
9265
9266   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9267   MIB.addReg(EAXreg);
9268
9269   // insert branch
9270   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9271
9272   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9273   return nextMBB;
9274 }
9275
9276 // private utility function:  64 bit atomics on 32 bit host.
9277 MachineBasicBlock *
9278 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9279                                                        MachineBasicBlock *MBB,
9280                                                        unsigned regOpcL,
9281                                                        unsigned regOpcH,
9282                                                        unsigned immOpcL,
9283                                                        unsigned immOpcH,
9284                                                        bool invSrc) const {
9285   // For the atomic bitwise operator, we generate
9286   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9287   //     ld t1,t2 = [bitinstr.addr]
9288   //   newMBB:
9289   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9290   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9291   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9292   //     mov ECX, EBX <- t5, t6
9293   //     mov EAX, EDX <- t1, t2
9294   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9295   //     mov t3, t4 <- EAX, EDX
9296   //     bz  newMBB
9297   //     result in out1, out2
9298   //     fallthrough -->nextMBB
9299
9300   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9301   const unsigned LoadOpc = X86::MOV32rm;
9302   const unsigned NotOpc = X86::NOT32r;
9303   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9304   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9305   MachineFunction::iterator MBBIter = MBB;
9306   ++MBBIter;
9307
9308   /// First build the CFG
9309   MachineFunction *F = MBB->getParent();
9310   MachineBasicBlock *thisMBB = MBB;
9311   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9312   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9313   F->insert(MBBIter, newMBB);
9314   F->insert(MBBIter, nextMBB);
9315
9316   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9317   nextMBB->splice(nextMBB->begin(), thisMBB,
9318                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9319                   thisMBB->end());
9320   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9321
9322   // Update thisMBB to fall through to newMBB
9323   thisMBB->addSuccessor(newMBB);
9324
9325   // newMBB jumps to itself and fall through to nextMBB
9326   newMBB->addSuccessor(nextMBB);
9327   newMBB->addSuccessor(newMBB);
9328
9329   DebugLoc dl = bInstr->getDebugLoc();
9330   // Insert instructions into newMBB based on incoming instruction
9331   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9332   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9333          "unexpected number of operands");
9334   MachineOperand& dest1Oper = bInstr->getOperand(0);
9335   MachineOperand& dest2Oper = bInstr->getOperand(1);
9336   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9337   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9338     argOpers[i] = &bInstr->getOperand(i+2);
9339
9340     // We use some of the operands multiple times, so conservatively just
9341     // clear any kill flags that might be present.
9342     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9343       argOpers[i]->setIsKill(false);
9344   }
9345
9346   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9347   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9348
9349   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9350   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9351   for (int i=0; i <= lastAddrIndx; ++i)
9352     (*MIB).addOperand(*argOpers[i]);
9353   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9354   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9355   // add 4 to displacement.
9356   for (int i=0; i <= lastAddrIndx-2; ++i)
9357     (*MIB).addOperand(*argOpers[i]);
9358   MachineOperand newOp3 = *(argOpers[3]);
9359   if (newOp3.isImm())
9360     newOp3.setImm(newOp3.getImm()+4);
9361   else
9362     newOp3.setOffset(newOp3.getOffset()+4);
9363   (*MIB).addOperand(newOp3);
9364   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9365
9366   // t3/4 are defined later, at the bottom of the loop
9367   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9368   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9369   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9370     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9371   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9372     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9373
9374   // The subsequent operations should be using the destination registers of
9375   //the PHI instructions.
9376   if (invSrc) {
9377     t1 = F->getRegInfo().createVirtualRegister(RC);
9378     t2 = F->getRegInfo().createVirtualRegister(RC);
9379     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9380     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9381   } else {
9382     t1 = dest1Oper.getReg();
9383     t2 = dest2Oper.getReg();
9384   }
9385
9386   int valArgIndx = lastAddrIndx + 1;
9387   assert((argOpers[valArgIndx]->isReg() ||
9388           argOpers[valArgIndx]->isImm()) &&
9389          "invalid operand");
9390   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9391   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9392   if (argOpers[valArgIndx]->isReg())
9393     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9394   else
9395     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9396   if (regOpcL != X86::MOV32rr)
9397     MIB.addReg(t1);
9398   (*MIB).addOperand(*argOpers[valArgIndx]);
9399   assert(argOpers[valArgIndx + 1]->isReg() ==
9400          argOpers[valArgIndx]->isReg());
9401   assert(argOpers[valArgIndx + 1]->isImm() ==
9402          argOpers[valArgIndx]->isImm());
9403   if (argOpers[valArgIndx + 1]->isReg())
9404     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9405   else
9406     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9407   if (regOpcH != X86::MOV32rr)
9408     MIB.addReg(t2);
9409   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9410
9411   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9412   MIB.addReg(t1);
9413   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9414   MIB.addReg(t2);
9415
9416   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9417   MIB.addReg(t5);
9418   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9419   MIB.addReg(t6);
9420
9421   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9422   for (int i=0; i <= lastAddrIndx; ++i)
9423     (*MIB).addOperand(*argOpers[i]);
9424
9425   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9426   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9427                     bInstr->memoperands_end());
9428
9429   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9430   MIB.addReg(X86::EAX);
9431   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9432   MIB.addReg(X86::EDX);
9433
9434   // insert branch
9435   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9436
9437   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9438   return nextMBB;
9439 }
9440
9441 // private utility function
9442 MachineBasicBlock *
9443 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9444                                                       MachineBasicBlock *MBB,
9445                                                       unsigned cmovOpc) const {
9446   // For the atomic min/max operator, we generate
9447   //   thisMBB:
9448   //   newMBB:
9449   //     ld t1 = [min/max.addr]
9450   //     mov t2 = [min/max.val]
9451   //     cmp  t1, t2
9452   //     cmov[cond] t2 = t1
9453   //     mov EAX = t1
9454   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9455   //     bz   newMBB
9456   //     fallthrough -->nextMBB
9457   //
9458   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9459   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9460   MachineFunction::iterator MBBIter = MBB;
9461   ++MBBIter;
9462
9463   /// First build the CFG
9464   MachineFunction *F = MBB->getParent();
9465   MachineBasicBlock *thisMBB = MBB;
9466   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9467   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9468   F->insert(MBBIter, newMBB);
9469   F->insert(MBBIter, nextMBB);
9470
9471   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9472   nextMBB->splice(nextMBB->begin(), thisMBB,
9473                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9474                   thisMBB->end());
9475   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9476
9477   // Update thisMBB to fall through to newMBB
9478   thisMBB->addSuccessor(newMBB);
9479
9480   // newMBB jumps to newMBB and fall through to nextMBB
9481   newMBB->addSuccessor(nextMBB);
9482   newMBB->addSuccessor(newMBB);
9483
9484   DebugLoc dl = mInstr->getDebugLoc();
9485   // Insert instructions into newMBB based on incoming instruction
9486   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9487          "unexpected number of operands");
9488   MachineOperand& destOper = mInstr->getOperand(0);
9489   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9490   int numArgs = mInstr->getNumOperands() - 1;
9491   for (int i=0; i < numArgs; ++i)
9492     argOpers[i] = &mInstr->getOperand(i+1);
9493
9494   // x86 address has 4 operands: base, index, scale, and displacement
9495   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9496   int valArgIndx = lastAddrIndx + 1;
9497
9498   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9499   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9500   for (int i=0; i <= lastAddrIndx; ++i)
9501     (*MIB).addOperand(*argOpers[i]);
9502
9503   // We only support register and immediate values
9504   assert((argOpers[valArgIndx]->isReg() ||
9505           argOpers[valArgIndx]->isImm()) &&
9506          "invalid operand");
9507
9508   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9509   if (argOpers[valArgIndx]->isReg())
9510     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9511   else
9512     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9513   (*MIB).addOperand(*argOpers[valArgIndx]);
9514
9515   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9516   MIB.addReg(t1);
9517
9518   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9519   MIB.addReg(t1);
9520   MIB.addReg(t2);
9521
9522   // Generate movc
9523   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9524   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9525   MIB.addReg(t2);
9526   MIB.addReg(t1);
9527
9528   // Cmp and exchange if none has modified the memory location
9529   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9530   for (int i=0; i <= lastAddrIndx; ++i)
9531     (*MIB).addOperand(*argOpers[i]);
9532   MIB.addReg(t3);
9533   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9534   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9535                     mInstr->memoperands_end());
9536
9537   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9538   MIB.addReg(X86::EAX);
9539
9540   // insert branch
9541   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9542
9543   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9544   return nextMBB;
9545 }
9546
9547 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9548 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9549 // in the .td file.
9550 MachineBasicBlock *
9551 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9552                             unsigned numArgs, bool memArg) const {
9553   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9554          "Target must have SSE4.2 or AVX features enabled");
9555
9556   DebugLoc dl = MI->getDebugLoc();
9557   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9558   unsigned Opc;
9559   if (!Subtarget->hasAVX()) {
9560     if (memArg)
9561       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9562     else
9563       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9564   } else {
9565     if (memArg)
9566       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9567     else
9568       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9569   }
9570
9571   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9572   for (unsigned i = 0; i < numArgs; ++i) {
9573     MachineOperand &Op = MI->getOperand(i+1);
9574     if (!(Op.isReg() && Op.isImplicit()))
9575       MIB.addOperand(Op);
9576   }
9577   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9578     .addReg(X86::XMM0);
9579
9580   MI->eraseFromParent();
9581   return BB;
9582 }
9583
9584 MachineBasicBlock *
9585 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9586   DebugLoc dl = MI->getDebugLoc();
9587   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9588
9589   // Address into RAX/EAX, other two args into ECX, EDX.
9590   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9591   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9592   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9593   for (int i = 0; i < X86::AddrNumOperands; ++i)
9594     MIB.addOperand(MI->getOperand(i));
9595
9596   unsigned ValOps = X86::AddrNumOperands;
9597   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9598     .addReg(MI->getOperand(ValOps).getReg());
9599   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9600     .addReg(MI->getOperand(ValOps+1).getReg());
9601
9602   // The instruction doesn't actually take any operands though.
9603   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9604
9605   MI->eraseFromParent(); // The pseudo is gone now.
9606   return BB;
9607 }
9608
9609 MachineBasicBlock *
9610 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9611   DebugLoc dl = MI->getDebugLoc();
9612   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9613
9614   // First arg in ECX, the second in EAX.
9615   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9616     .addReg(MI->getOperand(0).getReg());
9617   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9618     .addReg(MI->getOperand(1).getReg());
9619
9620   // The instruction doesn't actually take any operands though.
9621   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9622
9623   MI->eraseFromParent(); // The pseudo is gone now.
9624   return BB;
9625 }
9626
9627 MachineBasicBlock *
9628 X86TargetLowering::EmitVAARG64WithCustomInserter(
9629                    MachineInstr *MI,
9630                    MachineBasicBlock *MBB) const {
9631   // Emit va_arg instruction on X86-64.
9632
9633   // Operands to this pseudo-instruction:
9634   // 0  ) Output        : destination address (reg)
9635   // 1-5) Input         : va_list address (addr, i64mem)
9636   // 6  ) ArgSize       : Size (in bytes) of vararg type
9637   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9638   // 8  ) Align         : Alignment of type
9639   // 9  ) EFLAGS (implicit-def)
9640
9641   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9642   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9643
9644   unsigned DestReg = MI->getOperand(0).getReg();
9645   MachineOperand &Base = MI->getOperand(1);
9646   MachineOperand &Scale = MI->getOperand(2);
9647   MachineOperand &Index = MI->getOperand(3);
9648   MachineOperand &Disp = MI->getOperand(4);
9649   MachineOperand &Segment = MI->getOperand(5);
9650   unsigned ArgSize = MI->getOperand(6).getImm();
9651   unsigned ArgMode = MI->getOperand(7).getImm();
9652   unsigned Align = MI->getOperand(8).getImm();
9653
9654   // Memory Reference
9655   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9656   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9657   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9658
9659   // Machine Information
9660   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9661   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9662   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9663   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9664   DebugLoc DL = MI->getDebugLoc();
9665
9666   // struct va_list {
9667   //   i32   gp_offset
9668   //   i32   fp_offset
9669   //   i64   overflow_area (address)
9670   //   i64   reg_save_area (address)
9671   // }
9672   // sizeof(va_list) = 24
9673   // alignment(va_list) = 8
9674
9675   unsigned TotalNumIntRegs = 6;
9676   unsigned TotalNumXMMRegs = 8;
9677   bool UseGPOffset = (ArgMode == 1);
9678   bool UseFPOffset = (ArgMode == 2);
9679   unsigned MaxOffset = TotalNumIntRegs * 8 +
9680                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9681
9682   /* Align ArgSize to a multiple of 8 */
9683   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9684   bool NeedsAlign = (Align > 8);
9685
9686   MachineBasicBlock *thisMBB = MBB;
9687   MachineBasicBlock *overflowMBB;
9688   MachineBasicBlock *offsetMBB;
9689   MachineBasicBlock *endMBB;
9690
9691   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9692   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9693   unsigned OffsetReg = 0;
9694
9695   if (!UseGPOffset && !UseFPOffset) {
9696     // If we only pull from the overflow region, we don't create a branch.
9697     // We don't need to alter control flow.
9698     OffsetDestReg = 0; // unused
9699     OverflowDestReg = DestReg;
9700
9701     offsetMBB = NULL;
9702     overflowMBB = thisMBB;
9703     endMBB = thisMBB;
9704   } else {
9705     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9706     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9707     // If not, pull from overflow_area. (branch to overflowMBB)
9708     //
9709     //       thisMBB
9710     //         |     .
9711     //         |        .
9712     //     offsetMBB   overflowMBB
9713     //         |        .
9714     //         |     .
9715     //        endMBB
9716
9717     // Registers for the PHI in endMBB
9718     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9719     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9720
9721     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9722     MachineFunction *MF = MBB->getParent();
9723     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9724     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9725     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9726
9727     MachineFunction::iterator MBBIter = MBB;
9728     ++MBBIter;
9729
9730     // Insert the new basic blocks
9731     MF->insert(MBBIter, offsetMBB);
9732     MF->insert(MBBIter, overflowMBB);
9733     MF->insert(MBBIter, endMBB);
9734
9735     // Transfer the remainder of MBB and its successor edges to endMBB.
9736     endMBB->splice(endMBB->begin(), thisMBB,
9737                     llvm::next(MachineBasicBlock::iterator(MI)),
9738                     thisMBB->end());
9739     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9740
9741     // Make offsetMBB and overflowMBB successors of thisMBB
9742     thisMBB->addSuccessor(offsetMBB);
9743     thisMBB->addSuccessor(overflowMBB);
9744
9745     // endMBB is a successor of both offsetMBB and overflowMBB
9746     offsetMBB->addSuccessor(endMBB);
9747     overflowMBB->addSuccessor(endMBB);
9748
9749     // Load the offset value into a register
9750     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9751     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9752       .addOperand(Base)
9753       .addOperand(Scale)
9754       .addOperand(Index)
9755       .addDisp(Disp, UseFPOffset ? 4 : 0)
9756       .addOperand(Segment)
9757       .setMemRefs(MMOBegin, MMOEnd);
9758
9759     // Check if there is enough room left to pull this argument.
9760     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9761       .addReg(OffsetReg)
9762       .addImm(MaxOffset + 8 - ArgSizeA8);
9763
9764     // Branch to "overflowMBB" if offset >= max
9765     // Fall through to "offsetMBB" otherwise
9766     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9767       .addMBB(overflowMBB);
9768   }
9769
9770   // In offsetMBB, emit code to use the reg_save_area.
9771   if (offsetMBB) {
9772     assert(OffsetReg != 0);
9773
9774     // Read the reg_save_area address.
9775     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9776     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9777       .addOperand(Base)
9778       .addOperand(Scale)
9779       .addOperand(Index)
9780       .addDisp(Disp, 16)
9781       .addOperand(Segment)
9782       .setMemRefs(MMOBegin, MMOEnd);
9783
9784     // Zero-extend the offset
9785     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9786       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9787         .addImm(0)
9788         .addReg(OffsetReg)
9789         .addImm(X86::sub_32bit);
9790
9791     // Add the offset to the reg_save_area to get the final address.
9792     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9793       .addReg(OffsetReg64)
9794       .addReg(RegSaveReg);
9795
9796     // Compute the offset for the next argument
9797     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9798     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9799       .addReg(OffsetReg)
9800       .addImm(UseFPOffset ? 16 : 8);
9801
9802     // Store it back into the va_list.
9803     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9804       .addOperand(Base)
9805       .addOperand(Scale)
9806       .addOperand(Index)
9807       .addDisp(Disp, UseFPOffset ? 4 : 0)
9808       .addOperand(Segment)
9809       .addReg(NextOffsetReg)
9810       .setMemRefs(MMOBegin, MMOEnd);
9811
9812     // Jump to endMBB
9813     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9814       .addMBB(endMBB);
9815   }
9816
9817   //
9818   // Emit code to use overflow area
9819   //
9820
9821   // Load the overflow_area address into a register.
9822   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9823   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9824     .addOperand(Base)
9825     .addOperand(Scale)
9826     .addOperand(Index)
9827     .addDisp(Disp, 8)
9828     .addOperand(Segment)
9829     .setMemRefs(MMOBegin, MMOEnd);
9830
9831   // If we need to align it, do so. Otherwise, just copy the address
9832   // to OverflowDestReg.
9833   if (NeedsAlign) {
9834     // Align the overflow address
9835     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9836     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9837
9838     // aligned_addr = (addr + (align-1)) & ~(align-1)
9839     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9840       .addReg(OverflowAddrReg)
9841       .addImm(Align-1);
9842
9843     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9844       .addReg(TmpReg)
9845       .addImm(~(uint64_t)(Align-1));
9846   } else {
9847     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9848       .addReg(OverflowAddrReg);
9849   }
9850
9851   // Compute the next overflow address after this argument.
9852   // (the overflow address should be kept 8-byte aligned)
9853   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9854   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9855     .addReg(OverflowDestReg)
9856     .addImm(ArgSizeA8);
9857
9858   // Store the new overflow address.
9859   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9860     .addOperand(Base)
9861     .addOperand(Scale)
9862     .addOperand(Index)
9863     .addDisp(Disp, 8)
9864     .addOperand(Segment)
9865     .addReg(NextAddrReg)
9866     .setMemRefs(MMOBegin, MMOEnd);
9867
9868   // If we branched, emit the PHI to the front of endMBB.
9869   if (offsetMBB) {
9870     BuildMI(*endMBB, endMBB->begin(), DL,
9871             TII->get(X86::PHI), DestReg)
9872       .addReg(OffsetDestReg).addMBB(offsetMBB)
9873       .addReg(OverflowDestReg).addMBB(overflowMBB);
9874   }
9875
9876   // Erase the pseudo instruction
9877   MI->eraseFromParent();
9878
9879   return endMBB;
9880 }
9881
9882 MachineBasicBlock *
9883 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9884                                                  MachineInstr *MI,
9885                                                  MachineBasicBlock *MBB) const {
9886   // Emit code to save XMM registers to the stack. The ABI says that the
9887   // number of registers to save is given in %al, so it's theoretically
9888   // possible to do an indirect jump trick to avoid saving all of them,
9889   // however this code takes a simpler approach and just executes all
9890   // of the stores if %al is non-zero. It's less code, and it's probably
9891   // easier on the hardware branch predictor, and stores aren't all that
9892   // expensive anyway.
9893
9894   // Create the new basic blocks. One block contains all the XMM stores,
9895   // and one block is the final destination regardless of whether any
9896   // stores were performed.
9897   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9898   MachineFunction *F = MBB->getParent();
9899   MachineFunction::iterator MBBIter = MBB;
9900   ++MBBIter;
9901   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9902   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903   F->insert(MBBIter, XMMSaveMBB);
9904   F->insert(MBBIter, EndMBB);
9905
9906   // Transfer the remainder of MBB and its successor edges to EndMBB.
9907   EndMBB->splice(EndMBB->begin(), MBB,
9908                  llvm::next(MachineBasicBlock::iterator(MI)),
9909                  MBB->end());
9910   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9911
9912   // The original block will now fall through to the XMM save block.
9913   MBB->addSuccessor(XMMSaveMBB);
9914   // The XMMSaveMBB will fall through to the end block.
9915   XMMSaveMBB->addSuccessor(EndMBB);
9916
9917   // Now add the instructions.
9918   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9919   DebugLoc DL = MI->getDebugLoc();
9920
9921   unsigned CountReg = MI->getOperand(0).getReg();
9922   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9923   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9924
9925   if (!Subtarget->isTargetWin64()) {
9926     // If %al is 0, branch around the XMM save block.
9927     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9928     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9929     MBB->addSuccessor(EndMBB);
9930   }
9931
9932   // In the XMM save block, save all the XMM argument registers.
9933   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9934     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9935     MachineMemOperand *MMO =
9936       F->getMachineMemOperand(
9937           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9938         MachineMemOperand::MOStore,
9939         /*Size=*/16, /*Align=*/16);
9940     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9941       .addFrameIndex(RegSaveFrameIndex)
9942       .addImm(/*Scale=*/1)
9943       .addReg(/*IndexReg=*/0)
9944       .addImm(/*Disp=*/Offset)
9945       .addReg(/*Segment=*/0)
9946       .addReg(MI->getOperand(i).getReg())
9947       .addMemOperand(MMO);
9948   }
9949
9950   MI->eraseFromParent();   // The pseudo instruction is gone now.
9951
9952   return EndMBB;
9953 }
9954
9955 MachineBasicBlock *
9956 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9957                                      MachineBasicBlock *BB) const {
9958   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9959   DebugLoc DL = MI->getDebugLoc();
9960
9961   // To "insert" a SELECT_CC instruction, we actually have to insert the
9962   // diamond control-flow pattern.  The incoming instruction knows the
9963   // destination vreg to set, the condition code register to branch on, the
9964   // true/false values to select between, and a branch opcode to use.
9965   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9966   MachineFunction::iterator It = BB;
9967   ++It;
9968
9969   //  thisMBB:
9970   //  ...
9971   //   TrueVal = ...
9972   //   cmpTY ccX, r1, r2
9973   //   bCC copy1MBB
9974   //   fallthrough --> copy0MBB
9975   MachineBasicBlock *thisMBB = BB;
9976   MachineFunction *F = BB->getParent();
9977   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9978   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9979   F->insert(It, copy0MBB);
9980   F->insert(It, sinkMBB);
9981
9982   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9983   // live into the sink and copy blocks.
9984   const MachineFunction *MF = BB->getParent();
9985   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9986   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9987
9988   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9989     const MachineOperand &MO = MI->getOperand(I);
9990     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9991     unsigned Reg = MO.getReg();
9992     if (Reg != X86::EFLAGS) continue;
9993     copy0MBB->addLiveIn(Reg);
9994     sinkMBB->addLiveIn(Reg);
9995   }
9996
9997   // Transfer the remainder of BB and its successor edges to sinkMBB.
9998   sinkMBB->splice(sinkMBB->begin(), BB,
9999                   llvm::next(MachineBasicBlock::iterator(MI)),
10000                   BB->end());
10001   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10002
10003   // Add the true and fallthrough blocks as its successors.
10004   BB->addSuccessor(copy0MBB);
10005   BB->addSuccessor(sinkMBB);
10006
10007   // Create the conditional branch instruction.
10008   unsigned Opc =
10009     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10010   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10011
10012   //  copy0MBB:
10013   //   %FalseValue = ...
10014   //   # fallthrough to sinkMBB
10015   copy0MBB->addSuccessor(sinkMBB);
10016
10017   //  sinkMBB:
10018   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10019   //  ...
10020   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10021           TII->get(X86::PHI), MI->getOperand(0).getReg())
10022     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10023     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10024
10025   MI->eraseFromParent();   // The pseudo instruction is gone now.
10026   return sinkMBB;
10027 }
10028
10029 MachineBasicBlock *
10030 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10031                                           MachineBasicBlock *BB) const {
10032   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10033   DebugLoc DL = MI->getDebugLoc();
10034
10035   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10036   // non-trivial part is impdef of ESP.
10037   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10038   // mingw-w64.
10039
10040   const char *StackProbeSymbol =
10041       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10042
10043   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10044     .addExternalSymbol(StackProbeSymbol)
10045     .addReg(X86::EAX, RegState::Implicit)
10046     .addReg(X86::ESP, RegState::Implicit)
10047     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10048     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10049     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10050
10051   MI->eraseFromParent();   // The pseudo instruction is gone now.
10052   return BB;
10053 }
10054
10055 MachineBasicBlock *
10056 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10057                                       MachineBasicBlock *BB) const {
10058   // This is pretty easy.  We're taking the value that we received from
10059   // our load from the relocation, sticking it in either RDI (x86-64)
10060   // or EAX and doing an indirect call.  The return value will then
10061   // be in the normal return register.
10062   const X86InstrInfo *TII
10063     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10064   DebugLoc DL = MI->getDebugLoc();
10065   MachineFunction *F = BB->getParent();
10066
10067   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10068   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10069
10070   if (Subtarget->is64Bit()) {
10071     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10072                                       TII->get(X86::MOV64rm), X86::RDI)
10073     .addReg(X86::RIP)
10074     .addImm(0).addReg(0)
10075     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10076                       MI->getOperand(3).getTargetFlags())
10077     .addReg(0);
10078     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10079     addDirectMem(MIB, X86::RDI);
10080   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10081     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10082                                       TII->get(X86::MOV32rm), X86::EAX)
10083     .addReg(0)
10084     .addImm(0).addReg(0)
10085     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10086                       MI->getOperand(3).getTargetFlags())
10087     .addReg(0);
10088     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10089     addDirectMem(MIB, X86::EAX);
10090   } else {
10091     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10092                                       TII->get(X86::MOV32rm), X86::EAX)
10093     .addReg(TII->getGlobalBaseReg(F))
10094     .addImm(0).addReg(0)
10095     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10096                       MI->getOperand(3).getTargetFlags())
10097     .addReg(0);
10098     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10099     addDirectMem(MIB, X86::EAX);
10100   }
10101
10102   MI->eraseFromParent(); // The pseudo instruction is gone now.
10103   return BB;
10104 }
10105
10106 MachineBasicBlock *
10107 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10108                                                MachineBasicBlock *BB) const {
10109   switch (MI->getOpcode()) {
10110   default: assert(false && "Unexpected instr type to insert");
10111   case X86::TAILJMPd64:
10112   case X86::TAILJMPr64:
10113   case X86::TAILJMPm64:
10114     assert(!"TAILJMP64 would not be touched here.");
10115   case X86::TCRETURNdi64:
10116   case X86::TCRETURNri64:
10117   case X86::TCRETURNmi64:
10118     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10119     // On AMD64, additional defs should be added before register allocation.
10120     if (!Subtarget->isTargetWin64()) {
10121       MI->addRegisterDefined(X86::RSI);
10122       MI->addRegisterDefined(X86::RDI);
10123       MI->addRegisterDefined(X86::XMM6);
10124       MI->addRegisterDefined(X86::XMM7);
10125       MI->addRegisterDefined(X86::XMM8);
10126       MI->addRegisterDefined(X86::XMM9);
10127       MI->addRegisterDefined(X86::XMM10);
10128       MI->addRegisterDefined(X86::XMM11);
10129       MI->addRegisterDefined(X86::XMM12);
10130       MI->addRegisterDefined(X86::XMM13);
10131       MI->addRegisterDefined(X86::XMM14);
10132       MI->addRegisterDefined(X86::XMM15);
10133     }
10134     return BB;
10135   case X86::WIN_ALLOCA:
10136     return EmitLoweredWinAlloca(MI, BB);
10137   case X86::TLSCall_32:
10138   case X86::TLSCall_64:
10139     return EmitLoweredTLSCall(MI, BB);
10140   case X86::CMOV_GR8:
10141   case X86::CMOV_FR32:
10142   case X86::CMOV_FR64:
10143   case X86::CMOV_V4F32:
10144   case X86::CMOV_V2F64:
10145   case X86::CMOV_V2I64:
10146   case X86::CMOV_GR16:
10147   case X86::CMOV_GR32:
10148   case X86::CMOV_RFP32:
10149   case X86::CMOV_RFP64:
10150   case X86::CMOV_RFP80:
10151     return EmitLoweredSelect(MI, BB);
10152
10153   case X86::FP32_TO_INT16_IN_MEM:
10154   case X86::FP32_TO_INT32_IN_MEM:
10155   case X86::FP32_TO_INT64_IN_MEM:
10156   case X86::FP64_TO_INT16_IN_MEM:
10157   case X86::FP64_TO_INT32_IN_MEM:
10158   case X86::FP64_TO_INT64_IN_MEM:
10159   case X86::FP80_TO_INT16_IN_MEM:
10160   case X86::FP80_TO_INT32_IN_MEM:
10161   case X86::FP80_TO_INT64_IN_MEM: {
10162     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10163     DebugLoc DL = MI->getDebugLoc();
10164
10165     // Change the floating point control register to use "round towards zero"
10166     // mode when truncating to an integer value.
10167     MachineFunction *F = BB->getParent();
10168     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10169     addFrameReference(BuildMI(*BB, MI, DL,
10170                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10171
10172     // Load the old value of the high byte of the control word...
10173     unsigned OldCW =
10174       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10175     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10176                       CWFrameIdx);
10177
10178     // Set the high part to be round to zero...
10179     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10180       .addImm(0xC7F);
10181
10182     // Reload the modified control word now...
10183     addFrameReference(BuildMI(*BB, MI, DL,
10184                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10185
10186     // Restore the memory image of control word to original value
10187     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10188       .addReg(OldCW);
10189
10190     // Get the X86 opcode to use.
10191     unsigned Opc;
10192     switch (MI->getOpcode()) {
10193     default: llvm_unreachable("illegal opcode!");
10194     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10195     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10196     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10197     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10198     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10199     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10200     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10201     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10202     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10203     }
10204
10205     X86AddressMode AM;
10206     MachineOperand &Op = MI->getOperand(0);
10207     if (Op.isReg()) {
10208       AM.BaseType = X86AddressMode::RegBase;
10209       AM.Base.Reg = Op.getReg();
10210     } else {
10211       AM.BaseType = X86AddressMode::FrameIndexBase;
10212       AM.Base.FrameIndex = Op.getIndex();
10213     }
10214     Op = MI->getOperand(1);
10215     if (Op.isImm())
10216       AM.Scale = Op.getImm();
10217     Op = MI->getOperand(2);
10218     if (Op.isImm())
10219       AM.IndexReg = Op.getImm();
10220     Op = MI->getOperand(3);
10221     if (Op.isGlobal()) {
10222       AM.GV = Op.getGlobal();
10223     } else {
10224       AM.Disp = Op.getImm();
10225     }
10226     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10227                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10228
10229     // Reload the original control word now.
10230     addFrameReference(BuildMI(*BB, MI, DL,
10231                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10232
10233     MI->eraseFromParent();   // The pseudo instruction is gone now.
10234     return BB;
10235   }
10236     // String/text processing lowering.
10237   case X86::PCMPISTRM128REG:
10238   case X86::VPCMPISTRM128REG:
10239     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10240   case X86::PCMPISTRM128MEM:
10241   case X86::VPCMPISTRM128MEM:
10242     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10243   case X86::PCMPESTRM128REG:
10244   case X86::VPCMPESTRM128REG:
10245     return EmitPCMP(MI, BB, 5, false /* in mem */);
10246   case X86::PCMPESTRM128MEM:
10247   case X86::VPCMPESTRM128MEM:
10248     return EmitPCMP(MI, BB, 5, true /* in mem */);
10249
10250     // Thread synchronization.
10251   case X86::MONITOR:
10252     return EmitMonitor(MI, BB);
10253   case X86::MWAIT:
10254     return EmitMwait(MI, BB);
10255
10256     // Atomic Lowering.
10257   case X86::ATOMAND32:
10258     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10259                                                X86::AND32ri, X86::MOV32rm,
10260                                                X86::LCMPXCHG32,
10261                                                X86::NOT32r, X86::EAX,
10262                                                X86::GR32RegisterClass);
10263   case X86::ATOMOR32:
10264     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10265                                                X86::OR32ri, X86::MOV32rm,
10266                                                X86::LCMPXCHG32,
10267                                                X86::NOT32r, X86::EAX,
10268                                                X86::GR32RegisterClass);
10269   case X86::ATOMXOR32:
10270     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10271                                                X86::XOR32ri, X86::MOV32rm,
10272                                                X86::LCMPXCHG32,
10273                                                X86::NOT32r, X86::EAX,
10274                                                X86::GR32RegisterClass);
10275   case X86::ATOMNAND32:
10276     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10277                                                X86::AND32ri, X86::MOV32rm,
10278                                                X86::LCMPXCHG32,
10279                                                X86::NOT32r, X86::EAX,
10280                                                X86::GR32RegisterClass, true);
10281   case X86::ATOMMIN32:
10282     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10283   case X86::ATOMMAX32:
10284     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10285   case X86::ATOMUMIN32:
10286     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10287   case X86::ATOMUMAX32:
10288     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10289
10290   case X86::ATOMAND16:
10291     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10292                                                X86::AND16ri, X86::MOV16rm,
10293                                                X86::LCMPXCHG16,
10294                                                X86::NOT16r, X86::AX,
10295                                                X86::GR16RegisterClass);
10296   case X86::ATOMOR16:
10297     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10298                                                X86::OR16ri, X86::MOV16rm,
10299                                                X86::LCMPXCHG16,
10300                                                X86::NOT16r, X86::AX,
10301                                                X86::GR16RegisterClass);
10302   case X86::ATOMXOR16:
10303     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10304                                                X86::XOR16ri, X86::MOV16rm,
10305                                                X86::LCMPXCHG16,
10306                                                X86::NOT16r, X86::AX,
10307                                                X86::GR16RegisterClass);
10308   case X86::ATOMNAND16:
10309     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10310                                                X86::AND16ri, X86::MOV16rm,
10311                                                X86::LCMPXCHG16,
10312                                                X86::NOT16r, X86::AX,
10313                                                X86::GR16RegisterClass, true);
10314   case X86::ATOMMIN16:
10315     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10316   case X86::ATOMMAX16:
10317     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10318   case X86::ATOMUMIN16:
10319     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10320   case X86::ATOMUMAX16:
10321     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10322
10323   case X86::ATOMAND8:
10324     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10325                                                X86::AND8ri, X86::MOV8rm,
10326                                                X86::LCMPXCHG8,
10327                                                X86::NOT8r, X86::AL,
10328                                                X86::GR8RegisterClass);
10329   case X86::ATOMOR8:
10330     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10331                                                X86::OR8ri, X86::MOV8rm,
10332                                                X86::LCMPXCHG8,
10333                                                X86::NOT8r, X86::AL,
10334                                                X86::GR8RegisterClass);
10335   case X86::ATOMXOR8:
10336     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10337                                                X86::XOR8ri, X86::MOV8rm,
10338                                                X86::LCMPXCHG8,
10339                                                X86::NOT8r, X86::AL,
10340                                                X86::GR8RegisterClass);
10341   case X86::ATOMNAND8:
10342     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10343                                                X86::AND8ri, X86::MOV8rm,
10344                                                X86::LCMPXCHG8,
10345                                                X86::NOT8r, X86::AL,
10346                                                X86::GR8RegisterClass, true);
10347   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10348   // This group is for 64-bit host.
10349   case X86::ATOMAND64:
10350     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10351                                                X86::AND64ri32, X86::MOV64rm,
10352                                                X86::LCMPXCHG64,
10353                                                X86::NOT64r, X86::RAX,
10354                                                X86::GR64RegisterClass);
10355   case X86::ATOMOR64:
10356     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10357                                                X86::OR64ri32, X86::MOV64rm,
10358                                                X86::LCMPXCHG64,
10359                                                X86::NOT64r, X86::RAX,
10360                                                X86::GR64RegisterClass);
10361   case X86::ATOMXOR64:
10362     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10363                                                X86::XOR64ri32, X86::MOV64rm,
10364                                                X86::LCMPXCHG64,
10365                                                X86::NOT64r, X86::RAX,
10366                                                X86::GR64RegisterClass);
10367   case X86::ATOMNAND64:
10368     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10369                                                X86::AND64ri32, X86::MOV64rm,
10370                                                X86::LCMPXCHG64,
10371                                                X86::NOT64r, X86::RAX,
10372                                                X86::GR64RegisterClass, true);
10373   case X86::ATOMMIN64:
10374     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10375   case X86::ATOMMAX64:
10376     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10377   case X86::ATOMUMIN64:
10378     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10379   case X86::ATOMUMAX64:
10380     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10381
10382   // This group does 64-bit operations on a 32-bit host.
10383   case X86::ATOMAND6432:
10384     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10385                                                X86::AND32rr, X86::AND32rr,
10386                                                X86::AND32ri, X86::AND32ri,
10387                                                false);
10388   case X86::ATOMOR6432:
10389     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10390                                                X86::OR32rr, X86::OR32rr,
10391                                                X86::OR32ri, X86::OR32ri,
10392                                                false);
10393   case X86::ATOMXOR6432:
10394     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10395                                                X86::XOR32rr, X86::XOR32rr,
10396                                                X86::XOR32ri, X86::XOR32ri,
10397                                                false);
10398   case X86::ATOMNAND6432:
10399     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10400                                                X86::AND32rr, X86::AND32rr,
10401                                                X86::AND32ri, X86::AND32ri,
10402                                                true);
10403   case X86::ATOMADD6432:
10404     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10405                                                X86::ADD32rr, X86::ADC32rr,
10406                                                X86::ADD32ri, X86::ADC32ri,
10407                                                false);
10408   case X86::ATOMSUB6432:
10409     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10410                                                X86::SUB32rr, X86::SBB32rr,
10411                                                X86::SUB32ri, X86::SBB32ri,
10412                                                false);
10413   case X86::ATOMSWAP6432:
10414     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10415                                                X86::MOV32rr, X86::MOV32rr,
10416                                                X86::MOV32ri, X86::MOV32ri,
10417                                                false);
10418   case X86::VASTART_SAVE_XMM_REGS:
10419     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10420
10421   case X86::VAARG_64:
10422     return EmitVAARG64WithCustomInserter(MI, BB);
10423   }
10424 }
10425
10426 //===----------------------------------------------------------------------===//
10427 //                           X86 Optimization Hooks
10428 //===----------------------------------------------------------------------===//
10429
10430 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10431                                                        const APInt &Mask,
10432                                                        APInt &KnownZero,
10433                                                        APInt &KnownOne,
10434                                                        const SelectionDAG &DAG,
10435                                                        unsigned Depth) const {
10436   unsigned Opc = Op.getOpcode();
10437   assert((Opc >= ISD::BUILTIN_OP_END ||
10438           Opc == ISD::INTRINSIC_WO_CHAIN ||
10439           Opc == ISD::INTRINSIC_W_CHAIN ||
10440           Opc == ISD::INTRINSIC_VOID) &&
10441          "Should use MaskedValueIsZero if you don't know whether Op"
10442          " is a target node!");
10443
10444   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10445   switch (Opc) {
10446   default: break;
10447   case X86ISD::ADD:
10448   case X86ISD::SUB:
10449   case X86ISD::ADC:
10450   case X86ISD::SBB:
10451   case X86ISD::SMUL:
10452   case X86ISD::UMUL:
10453   case X86ISD::INC:
10454   case X86ISD::DEC:
10455   case X86ISD::OR:
10456   case X86ISD::XOR:
10457   case X86ISD::AND:
10458     // These nodes' second result is a boolean.
10459     if (Op.getResNo() == 0)
10460       break;
10461     // Fallthrough
10462   case X86ISD::SETCC:
10463     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10464                                        Mask.getBitWidth() - 1);
10465     break;
10466   }
10467 }
10468
10469 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10470                                                          unsigned Depth) const {
10471   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10472   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10473     return Op.getValueType().getScalarType().getSizeInBits();
10474
10475   // Fallback case.
10476   return 1;
10477 }
10478
10479 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10480 /// node is a GlobalAddress + offset.
10481 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10482                                        const GlobalValue* &GA,
10483                                        int64_t &Offset) const {
10484   if (N->getOpcode() == X86ISD::Wrapper) {
10485     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10486       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10487       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10488       return true;
10489     }
10490   }
10491   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10492 }
10493
10494 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10495 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10496 /// if the load addresses are consecutive, non-overlapping, and in the right
10497 /// order.
10498 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10499                                      TargetLowering::DAGCombinerInfo &DCI) {
10500   DebugLoc dl = N->getDebugLoc();
10501   EVT VT = N->getValueType(0);
10502
10503   if (VT.getSizeInBits() != 128)
10504     return SDValue();
10505
10506   // Don't create instructions with illegal types after legalize types has run.
10507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10508   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10509     return SDValue();
10510
10511   SmallVector<SDValue, 16> Elts;
10512   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10513     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10514
10515   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10516 }
10517
10518 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10519 /// generation and convert it from being a bunch of shuffles and extracts
10520 /// to a simple store and scalar loads to extract the elements.
10521 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10522                                                 const TargetLowering &TLI) {
10523   SDValue InputVector = N->getOperand(0);
10524
10525   // Only operate on vectors of 4 elements, where the alternative shuffling
10526   // gets to be more expensive.
10527   if (InputVector.getValueType() != MVT::v4i32)
10528     return SDValue();
10529
10530   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10531   // single use which is a sign-extend or zero-extend, and all elements are
10532   // used.
10533   SmallVector<SDNode *, 4> Uses;
10534   unsigned ExtractedElements = 0;
10535   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10536        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10537     if (UI.getUse().getResNo() != InputVector.getResNo())
10538       return SDValue();
10539
10540     SDNode *Extract = *UI;
10541     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10542       return SDValue();
10543
10544     if (Extract->getValueType(0) != MVT::i32)
10545       return SDValue();
10546     if (!Extract->hasOneUse())
10547       return SDValue();
10548     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10549         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10550       return SDValue();
10551     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10552       return SDValue();
10553
10554     // Record which element was extracted.
10555     ExtractedElements |=
10556       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10557
10558     Uses.push_back(Extract);
10559   }
10560
10561   // If not all the elements were used, this may not be worthwhile.
10562   if (ExtractedElements != 15)
10563     return SDValue();
10564
10565   // Ok, we've now decided to do the transformation.
10566   DebugLoc dl = InputVector.getDebugLoc();
10567
10568   // Store the value to a temporary stack slot.
10569   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10570   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10571                             MachinePointerInfo(), false, false, 0);
10572
10573   // Replace each use (extract) with a load of the appropriate element.
10574   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10575        UE = Uses.end(); UI != UE; ++UI) {
10576     SDNode *Extract = *UI;
10577
10578     // Compute the element's address.
10579     SDValue Idx = Extract->getOperand(1);
10580     unsigned EltSize =
10581         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10582     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10583     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10584
10585     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10586                                      StackPtr, OffsetVal);
10587
10588     // Load the scalar.
10589     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10590                                      ScalarAddr, MachinePointerInfo(),
10591                                      false, false, 0);
10592
10593     // Replace the exact with the load.
10594     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10595   }
10596
10597   // The replacement was made in place; don't return anything.
10598   return SDValue();
10599 }
10600
10601 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10602 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10603                                     const X86Subtarget *Subtarget) {
10604   DebugLoc DL = N->getDebugLoc();
10605   SDValue Cond = N->getOperand(0);
10606   // Get the LHS/RHS of the select.
10607   SDValue LHS = N->getOperand(1);
10608   SDValue RHS = N->getOperand(2);
10609
10610   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10611   // instructions match the semantics of the common C idiom x<y?x:y but not
10612   // x<=y?x:y, because of how they handle negative zero (which can be
10613   // ignored in unsafe-math mode).
10614   if (Subtarget->hasSSE2() &&
10615       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10616       Cond.getOpcode() == ISD::SETCC) {
10617     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10618
10619     unsigned Opcode = 0;
10620     // Check for x CC y ? x : y.
10621     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10622         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10623       switch (CC) {
10624       default: break;
10625       case ISD::SETULT:
10626         // Converting this to a min would handle NaNs incorrectly, and swapping
10627         // the operands would cause it to handle comparisons between positive
10628         // and negative zero incorrectly.
10629         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10630           if (!UnsafeFPMath &&
10631               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10632             break;
10633           std::swap(LHS, RHS);
10634         }
10635         Opcode = X86ISD::FMIN;
10636         break;
10637       case ISD::SETOLE:
10638         // Converting this to a min would handle comparisons between positive
10639         // and negative zero incorrectly.
10640         if (!UnsafeFPMath &&
10641             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10642           break;
10643         Opcode = X86ISD::FMIN;
10644         break;
10645       case ISD::SETULE:
10646         // Converting this to a min would handle both negative zeros and NaNs
10647         // incorrectly, but we can swap the operands to fix both.
10648         std::swap(LHS, RHS);
10649       case ISD::SETOLT:
10650       case ISD::SETLT:
10651       case ISD::SETLE:
10652         Opcode = X86ISD::FMIN;
10653         break;
10654
10655       case ISD::SETOGE:
10656         // Converting this to a max would handle comparisons between positive
10657         // and negative zero incorrectly.
10658         if (!UnsafeFPMath &&
10659             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10660           break;
10661         Opcode = X86ISD::FMAX;
10662         break;
10663       case ISD::SETUGT:
10664         // Converting this to a max would handle NaNs incorrectly, and swapping
10665         // the operands would cause it to handle comparisons between positive
10666         // and negative zero incorrectly.
10667         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10668           if (!UnsafeFPMath &&
10669               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10670             break;
10671           std::swap(LHS, RHS);
10672         }
10673         Opcode = X86ISD::FMAX;
10674         break;
10675       case ISD::SETUGE:
10676         // Converting this to a max would handle both negative zeros and NaNs
10677         // incorrectly, but we can swap the operands to fix both.
10678         std::swap(LHS, RHS);
10679       case ISD::SETOGT:
10680       case ISD::SETGT:
10681       case ISD::SETGE:
10682         Opcode = X86ISD::FMAX;
10683         break;
10684       }
10685     // Check for x CC y ? y : x -- a min/max with reversed arms.
10686     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10687                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10688       switch (CC) {
10689       default: break;
10690       case ISD::SETOGE:
10691         // Converting this to a min would handle comparisons between positive
10692         // and negative zero incorrectly, and swapping the operands would
10693         // cause it to handle NaNs incorrectly.
10694         if (!UnsafeFPMath &&
10695             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10696           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10697             break;
10698           std::swap(LHS, RHS);
10699         }
10700         Opcode = X86ISD::FMIN;
10701         break;
10702       case ISD::SETUGT:
10703         // Converting this to a min would handle NaNs incorrectly.
10704         if (!UnsafeFPMath &&
10705             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10706           break;
10707         Opcode = X86ISD::FMIN;
10708         break;
10709       case ISD::SETUGE:
10710         // Converting this to a min would handle both negative zeros and NaNs
10711         // incorrectly, but we can swap the operands to fix both.
10712         std::swap(LHS, RHS);
10713       case ISD::SETOGT:
10714       case ISD::SETGT:
10715       case ISD::SETGE:
10716         Opcode = X86ISD::FMIN;
10717         break;
10718
10719       case ISD::SETULT:
10720         // Converting this to a max would handle NaNs incorrectly.
10721         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10722           break;
10723         Opcode = X86ISD::FMAX;
10724         break;
10725       case ISD::SETOLE:
10726         // Converting this to a max would handle comparisons between positive
10727         // and negative zero incorrectly, and swapping the operands would
10728         // cause it to handle NaNs incorrectly.
10729         if (!UnsafeFPMath &&
10730             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10731           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10732             break;
10733           std::swap(LHS, RHS);
10734         }
10735         Opcode = X86ISD::FMAX;
10736         break;
10737       case ISD::SETULE:
10738         // Converting this to a max would handle both negative zeros and NaNs
10739         // incorrectly, but we can swap the operands to fix both.
10740         std::swap(LHS, RHS);
10741       case ISD::SETOLT:
10742       case ISD::SETLT:
10743       case ISD::SETLE:
10744         Opcode = X86ISD::FMAX;
10745         break;
10746       }
10747     }
10748
10749     if (Opcode)
10750       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10751   }
10752
10753   // If this is a select between two integer constants, try to do some
10754   // optimizations.
10755   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10756     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10757       // Don't do this for crazy integer types.
10758       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10759         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10760         // so that TrueC (the true value) is larger than FalseC.
10761         bool NeedsCondInvert = false;
10762
10763         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10764             // Efficiently invertible.
10765             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10766              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10767               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10768           NeedsCondInvert = true;
10769           std::swap(TrueC, FalseC);
10770         }
10771
10772         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10773         if (FalseC->getAPIntValue() == 0 &&
10774             TrueC->getAPIntValue().isPowerOf2()) {
10775           if (NeedsCondInvert) // Invert the condition if needed.
10776             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10777                                DAG.getConstant(1, Cond.getValueType()));
10778
10779           // Zero extend the condition if needed.
10780           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10781
10782           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10783           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10784                              DAG.getConstant(ShAmt, MVT::i8));
10785         }
10786
10787         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10788         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10789           if (NeedsCondInvert) // Invert the condition if needed.
10790             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10791                                DAG.getConstant(1, Cond.getValueType()));
10792
10793           // Zero extend the condition if needed.
10794           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10795                              FalseC->getValueType(0), Cond);
10796           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10797                              SDValue(FalseC, 0));
10798         }
10799
10800         // Optimize cases that will turn into an LEA instruction.  This requires
10801         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10802         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10803           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10804           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10805
10806           bool isFastMultiplier = false;
10807           if (Diff < 10) {
10808             switch ((unsigned char)Diff) {
10809               default: break;
10810               case 1:  // result = add base, cond
10811               case 2:  // result = lea base(    , cond*2)
10812               case 3:  // result = lea base(cond, cond*2)
10813               case 4:  // result = lea base(    , cond*4)
10814               case 5:  // result = lea base(cond, cond*4)
10815               case 8:  // result = lea base(    , cond*8)
10816               case 9:  // result = lea base(cond, cond*8)
10817                 isFastMultiplier = true;
10818                 break;
10819             }
10820           }
10821
10822           if (isFastMultiplier) {
10823             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10824             if (NeedsCondInvert) // Invert the condition if needed.
10825               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10826                                  DAG.getConstant(1, Cond.getValueType()));
10827
10828             // Zero extend the condition if needed.
10829             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10830                                Cond);
10831             // Scale the condition by the difference.
10832             if (Diff != 1)
10833               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10834                                  DAG.getConstant(Diff, Cond.getValueType()));
10835
10836             // Add the base if non-zero.
10837             if (FalseC->getAPIntValue() != 0)
10838               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10839                                  SDValue(FalseC, 0));
10840             return Cond;
10841           }
10842         }
10843       }
10844   }
10845
10846   return SDValue();
10847 }
10848
10849 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10850 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10851                                   TargetLowering::DAGCombinerInfo &DCI) {
10852   DebugLoc DL = N->getDebugLoc();
10853
10854   // If the flag operand isn't dead, don't touch this CMOV.
10855   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10856     return SDValue();
10857
10858   // If this is a select between two integer constants, try to do some
10859   // optimizations.  Note that the operands are ordered the opposite of SELECT
10860   // operands.
10861   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10862     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10863       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10864       // larger than FalseC (the false value).
10865       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10866
10867       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10868         CC = X86::GetOppositeBranchCondition(CC);
10869         std::swap(TrueC, FalseC);
10870       }
10871
10872       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10873       // This is efficient for any integer data type (including i8/i16) and
10874       // shift amount.
10875       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10876         SDValue Cond = N->getOperand(3);
10877         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10878                            DAG.getConstant(CC, MVT::i8), Cond);
10879
10880         // Zero extend the condition if needed.
10881         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10882
10883         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10884         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10885                            DAG.getConstant(ShAmt, MVT::i8));
10886         if (N->getNumValues() == 2)  // Dead flag value?
10887           return DCI.CombineTo(N, Cond, SDValue());
10888         return Cond;
10889       }
10890
10891       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10892       // for any integer data type, including i8/i16.
10893       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10894         SDValue Cond = N->getOperand(3);
10895         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10896                            DAG.getConstant(CC, MVT::i8), Cond);
10897
10898         // Zero extend the condition if needed.
10899         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10900                            FalseC->getValueType(0), Cond);
10901         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10902                            SDValue(FalseC, 0));
10903
10904         if (N->getNumValues() == 2)  // Dead flag value?
10905           return DCI.CombineTo(N, Cond, SDValue());
10906         return Cond;
10907       }
10908
10909       // Optimize cases that will turn into an LEA instruction.  This requires
10910       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10911       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10912         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10913         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10914
10915         bool isFastMultiplier = false;
10916         if (Diff < 10) {
10917           switch ((unsigned char)Diff) {
10918           default: break;
10919           case 1:  // result = add base, cond
10920           case 2:  // result = lea base(    , cond*2)
10921           case 3:  // result = lea base(cond, cond*2)
10922           case 4:  // result = lea base(    , cond*4)
10923           case 5:  // result = lea base(cond, cond*4)
10924           case 8:  // result = lea base(    , cond*8)
10925           case 9:  // result = lea base(cond, cond*8)
10926             isFastMultiplier = true;
10927             break;
10928           }
10929         }
10930
10931         if (isFastMultiplier) {
10932           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10933           SDValue Cond = N->getOperand(3);
10934           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10935                              DAG.getConstant(CC, MVT::i8), Cond);
10936           // Zero extend the condition if needed.
10937           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10938                              Cond);
10939           // Scale the condition by the difference.
10940           if (Diff != 1)
10941             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10942                                DAG.getConstant(Diff, Cond.getValueType()));
10943
10944           // Add the base if non-zero.
10945           if (FalseC->getAPIntValue() != 0)
10946             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10947                                SDValue(FalseC, 0));
10948           if (N->getNumValues() == 2)  // Dead flag value?
10949             return DCI.CombineTo(N, Cond, SDValue());
10950           return Cond;
10951         }
10952       }
10953     }
10954   }
10955   return SDValue();
10956 }
10957
10958
10959 /// PerformMulCombine - Optimize a single multiply with constant into two
10960 /// in order to implement it with two cheaper instructions, e.g.
10961 /// LEA + SHL, LEA + LEA.
10962 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10963                                  TargetLowering::DAGCombinerInfo &DCI) {
10964   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10965     return SDValue();
10966
10967   EVT VT = N->getValueType(0);
10968   if (VT != MVT::i64)
10969     return SDValue();
10970
10971   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10972   if (!C)
10973     return SDValue();
10974   uint64_t MulAmt = C->getZExtValue();
10975   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10976     return SDValue();
10977
10978   uint64_t MulAmt1 = 0;
10979   uint64_t MulAmt2 = 0;
10980   if ((MulAmt % 9) == 0) {
10981     MulAmt1 = 9;
10982     MulAmt2 = MulAmt / 9;
10983   } else if ((MulAmt % 5) == 0) {
10984     MulAmt1 = 5;
10985     MulAmt2 = MulAmt / 5;
10986   } else if ((MulAmt % 3) == 0) {
10987     MulAmt1 = 3;
10988     MulAmt2 = MulAmt / 3;
10989   }
10990   if (MulAmt2 &&
10991       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10992     DebugLoc DL = N->getDebugLoc();
10993
10994     if (isPowerOf2_64(MulAmt2) &&
10995         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10996       // If second multiplifer is pow2, issue it first. We want the multiply by
10997       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10998       // is an add.
10999       std::swap(MulAmt1, MulAmt2);
11000
11001     SDValue NewMul;
11002     if (isPowerOf2_64(MulAmt1))
11003       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11004                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11005     else
11006       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11007                            DAG.getConstant(MulAmt1, VT));
11008
11009     if (isPowerOf2_64(MulAmt2))
11010       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11011                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11012     else
11013       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11014                            DAG.getConstant(MulAmt2, VT));
11015
11016     // Do not add new nodes to DAG combiner worklist.
11017     DCI.CombineTo(N, NewMul, false);
11018   }
11019   return SDValue();
11020 }
11021
11022 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11023   SDValue N0 = N->getOperand(0);
11024   SDValue N1 = N->getOperand(1);
11025   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11026   EVT VT = N0.getValueType();
11027
11028   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11029   // since the result of setcc_c is all zero's or all ones.
11030   if (N1C && N0.getOpcode() == ISD::AND &&
11031       N0.getOperand(1).getOpcode() == ISD::Constant) {
11032     SDValue N00 = N0.getOperand(0);
11033     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11034         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11035           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11036          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11037       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11038       APInt ShAmt = N1C->getAPIntValue();
11039       Mask = Mask.shl(ShAmt);
11040       if (Mask != 0)
11041         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11042                            N00, DAG.getConstant(Mask, VT));
11043     }
11044   }
11045
11046   return SDValue();
11047 }
11048
11049 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11050 ///                       when possible.
11051 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11052                                    const X86Subtarget *Subtarget) {
11053   EVT VT = N->getValueType(0);
11054   if (!VT.isVector() && VT.isInteger() &&
11055       N->getOpcode() == ISD::SHL)
11056     return PerformSHLCombine(N, DAG);
11057
11058   // On X86 with SSE2 support, we can transform this to a vector shift if
11059   // all elements are shifted by the same amount.  We can't do this in legalize
11060   // because the a constant vector is typically transformed to a constant pool
11061   // so we have no knowledge of the shift amount.
11062   if (!Subtarget->hasSSE2())
11063     return SDValue();
11064
11065   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11066     return SDValue();
11067
11068   SDValue ShAmtOp = N->getOperand(1);
11069   EVT EltVT = VT.getVectorElementType();
11070   DebugLoc DL = N->getDebugLoc();
11071   SDValue BaseShAmt = SDValue();
11072   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11073     unsigned NumElts = VT.getVectorNumElements();
11074     unsigned i = 0;
11075     for (; i != NumElts; ++i) {
11076       SDValue Arg = ShAmtOp.getOperand(i);
11077       if (Arg.getOpcode() == ISD::UNDEF) continue;
11078       BaseShAmt = Arg;
11079       break;
11080     }
11081     for (; i != NumElts; ++i) {
11082       SDValue Arg = ShAmtOp.getOperand(i);
11083       if (Arg.getOpcode() == ISD::UNDEF) continue;
11084       if (Arg != BaseShAmt) {
11085         return SDValue();
11086       }
11087     }
11088   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11089              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11090     SDValue InVec = ShAmtOp.getOperand(0);
11091     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11092       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11093       unsigned i = 0;
11094       for (; i != NumElts; ++i) {
11095         SDValue Arg = InVec.getOperand(i);
11096         if (Arg.getOpcode() == ISD::UNDEF) continue;
11097         BaseShAmt = Arg;
11098         break;
11099       }
11100     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11101        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11102          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11103          if (C->getZExtValue() == SplatIdx)
11104            BaseShAmt = InVec.getOperand(1);
11105        }
11106     }
11107     if (BaseShAmt.getNode() == 0)
11108       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11109                               DAG.getIntPtrConstant(0));
11110   } else
11111     return SDValue();
11112
11113   // The shift amount is an i32.
11114   if (EltVT.bitsGT(MVT::i32))
11115     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11116   else if (EltVT.bitsLT(MVT::i32))
11117     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11118
11119   // The shift amount is identical so we can do a vector shift.
11120   SDValue  ValOp = N->getOperand(0);
11121   switch (N->getOpcode()) {
11122   default:
11123     llvm_unreachable("Unknown shift opcode!");
11124     break;
11125   case ISD::SHL:
11126     if (VT == MVT::v2i64)
11127       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11128                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11129                          ValOp, BaseShAmt);
11130     if (VT == MVT::v4i32)
11131       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11132                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11133                          ValOp, BaseShAmt);
11134     if (VT == MVT::v8i16)
11135       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11136                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11137                          ValOp, BaseShAmt);
11138     break;
11139   case ISD::SRA:
11140     if (VT == MVT::v4i32)
11141       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11142                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11143                          ValOp, BaseShAmt);
11144     if (VT == MVT::v8i16)
11145       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11146                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11147                          ValOp, BaseShAmt);
11148     break;
11149   case ISD::SRL:
11150     if (VT == MVT::v2i64)
11151       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11152                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11153                          ValOp, BaseShAmt);
11154     if (VT == MVT::v4i32)
11155       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11156                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11157                          ValOp, BaseShAmt);
11158     if (VT ==  MVT::v8i16)
11159       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11160                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11161                          ValOp, BaseShAmt);
11162     break;
11163   }
11164   return SDValue();
11165 }
11166
11167
11168 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11169                                  TargetLowering::DAGCombinerInfo &DCI,
11170                                  const X86Subtarget *Subtarget) {
11171   if (DCI.isBeforeLegalizeOps())
11172     return SDValue();
11173
11174   // Want to form PANDN nodes, in the hopes of then easily combining them with
11175   // OR and AND nodes to form PBLEND/PSIGN.
11176   EVT VT = N->getValueType(0);
11177   if (VT != MVT::v2i64)
11178     return SDValue();
11179
11180   SDValue N0 = N->getOperand(0);
11181   SDValue N1 = N->getOperand(1);
11182   DebugLoc DL = N->getDebugLoc();
11183
11184   // Check LHS for vnot
11185   if (N0.getOpcode() == ISD::XOR &&
11186       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11187     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11188
11189   // Check RHS for vnot
11190   if (N1.getOpcode() == ISD::XOR &&
11191       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11192     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11193
11194   return SDValue();
11195 }
11196
11197 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11198                                 TargetLowering::DAGCombinerInfo &DCI,
11199                                 const X86Subtarget *Subtarget) {
11200   if (DCI.isBeforeLegalizeOps())
11201     return SDValue();
11202
11203   EVT VT = N->getValueType(0);
11204   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11205     return SDValue();
11206
11207   SDValue N0 = N->getOperand(0);
11208   SDValue N1 = N->getOperand(1);
11209
11210   // look for psign/blend
11211   if (Subtarget->hasSSSE3()) {
11212     if (VT == MVT::v2i64) {
11213       // Canonicalize pandn to RHS
11214       if (N0.getOpcode() == X86ISD::PANDN)
11215         std::swap(N0, N1);
11216       // or (and (m, x), (pandn m, y))
11217       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11218         SDValue Mask = N1.getOperand(0);
11219         SDValue X    = N1.getOperand(1);
11220         SDValue Y;
11221         if (N0.getOperand(0) == Mask)
11222           Y = N0.getOperand(1);
11223         if (N0.getOperand(1) == Mask)
11224           Y = N0.getOperand(0);
11225
11226         // Check to see if the mask appeared in both the AND and PANDN and
11227         if (!Y.getNode())
11228           return SDValue();
11229
11230         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11231         if (Mask.getOpcode() != ISD::BITCAST ||
11232             X.getOpcode() != ISD::BITCAST ||
11233             Y.getOpcode() != ISD::BITCAST)
11234           return SDValue();
11235
11236         // Look through mask bitcast.
11237         Mask = Mask.getOperand(0);
11238         EVT MaskVT = Mask.getValueType();
11239
11240         // Validate that the Mask operand is a vector sra node.  The sra node
11241         // will be an intrinsic.
11242         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11243           return SDValue();
11244
11245         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11246         // there is no psrai.b
11247         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11248         case Intrinsic::x86_sse2_psrai_w:
11249         case Intrinsic::x86_sse2_psrai_d:
11250           break;
11251         default: return SDValue();
11252         }
11253
11254         // Check that the SRA is all signbits.
11255         SDValue SraC = Mask.getOperand(2);
11256         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11257         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11258         if ((SraAmt + 1) != EltBits)
11259           return SDValue();
11260
11261         DebugLoc DL = N->getDebugLoc();
11262
11263         // Now we know we at least have a plendvb with the mask val.  See if
11264         // we can form a psignb/w/d.
11265         // psign = x.type == y.type == mask.type && y = sub(0, x);
11266         X = X.getOperand(0);
11267         Y = Y.getOperand(0);
11268         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11269             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11270             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11271           unsigned Opc = 0;
11272           switch (EltBits) {
11273           case 8: Opc = X86ISD::PSIGNB; break;
11274           case 16: Opc = X86ISD::PSIGNW; break;
11275           case 32: Opc = X86ISD::PSIGND; break;
11276           default: break;
11277           }
11278           if (Opc) {
11279             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11280             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11281           }
11282         }
11283         // PBLENDVB only available on SSE 4.1
11284         if (!Subtarget->hasSSE41())
11285           return SDValue();
11286
11287         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11288         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11289         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11290         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11291         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11292       }
11293     }
11294   }
11295
11296   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11297   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11298     std::swap(N0, N1);
11299   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11300     return SDValue();
11301   if (!N0.hasOneUse() || !N1.hasOneUse())
11302     return SDValue();
11303
11304   SDValue ShAmt0 = N0.getOperand(1);
11305   if (ShAmt0.getValueType() != MVT::i8)
11306     return SDValue();
11307   SDValue ShAmt1 = N1.getOperand(1);
11308   if (ShAmt1.getValueType() != MVT::i8)
11309     return SDValue();
11310   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11311     ShAmt0 = ShAmt0.getOperand(0);
11312   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11313     ShAmt1 = ShAmt1.getOperand(0);
11314
11315   DebugLoc DL = N->getDebugLoc();
11316   unsigned Opc = X86ISD::SHLD;
11317   SDValue Op0 = N0.getOperand(0);
11318   SDValue Op1 = N1.getOperand(0);
11319   if (ShAmt0.getOpcode() == ISD::SUB) {
11320     Opc = X86ISD::SHRD;
11321     std::swap(Op0, Op1);
11322     std::swap(ShAmt0, ShAmt1);
11323   }
11324
11325   unsigned Bits = VT.getSizeInBits();
11326   if (ShAmt1.getOpcode() == ISD::SUB) {
11327     SDValue Sum = ShAmt1.getOperand(0);
11328     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11329       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11330       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11331         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11332       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11333         return DAG.getNode(Opc, DL, VT,
11334                            Op0, Op1,
11335                            DAG.getNode(ISD::TRUNCATE, DL,
11336                                        MVT::i8, ShAmt0));
11337     }
11338   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11339     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11340     if (ShAmt0C &&
11341         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11342       return DAG.getNode(Opc, DL, VT,
11343                          N0.getOperand(0), N1.getOperand(0),
11344                          DAG.getNode(ISD::TRUNCATE, DL,
11345                                        MVT::i8, ShAmt0));
11346   }
11347
11348   return SDValue();
11349 }
11350
11351 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11352 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11353                                    const X86Subtarget *Subtarget) {
11354   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11355   // the FP state in cases where an emms may be missing.
11356   // A preferable solution to the general problem is to figure out the right
11357   // places to insert EMMS.  This qualifies as a quick hack.
11358
11359   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11360   StoreSDNode *St = cast<StoreSDNode>(N);
11361   EVT VT = St->getValue().getValueType();
11362   if (VT.getSizeInBits() != 64)
11363     return SDValue();
11364
11365   const Function *F = DAG.getMachineFunction().getFunction();
11366   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11367   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11368     && Subtarget->hasSSE2();
11369   if ((VT.isVector() ||
11370        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11371       isa<LoadSDNode>(St->getValue()) &&
11372       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11373       St->getChain().hasOneUse() && !St->isVolatile()) {
11374     SDNode* LdVal = St->getValue().getNode();
11375     LoadSDNode *Ld = 0;
11376     int TokenFactorIndex = -1;
11377     SmallVector<SDValue, 8> Ops;
11378     SDNode* ChainVal = St->getChain().getNode();
11379     // Must be a store of a load.  We currently handle two cases:  the load
11380     // is a direct child, and it's under an intervening TokenFactor.  It is
11381     // possible to dig deeper under nested TokenFactors.
11382     if (ChainVal == LdVal)
11383       Ld = cast<LoadSDNode>(St->getChain());
11384     else if (St->getValue().hasOneUse() &&
11385              ChainVal->getOpcode() == ISD::TokenFactor) {
11386       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11387         if (ChainVal->getOperand(i).getNode() == LdVal) {
11388           TokenFactorIndex = i;
11389           Ld = cast<LoadSDNode>(St->getValue());
11390         } else
11391           Ops.push_back(ChainVal->getOperand(i));
11392       }
11393     }
11394
11395     if (!Ld || !ISD::isNormalLoad(Ld))
11396       return SDValue();
11397
11398     // If this is not the MMX case, i.e. we are just turning i64 load/store
11399     // into f64 load/store, avoid the transformation if there are multiple
11400     // uses of the loaded value.
11401     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11402       return SDValue();
11403
11404     DebugLoc LdDL = Ld->getDebugLoc();
11405     DebugLoc StDL = N->getDebugLoc();
11406     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11407     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11408     // pair instead.
11409     if (Subtarget->is64Bit() || F64IsLegal) {
11410       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11411       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11412                                   Ld->getPointerInfo(), Ld->isVolatile(),
11413                                   Ld->isNonTemporal(), Ld->getAlignment());
11414       SDValue NewChain = NewLd.getValue(1);
11415       if (TokenFactorIndex != -1) {
11416         Ops.push_back(NewChain);
11417         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11418                                Ops.size());
11419       }
11420       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11421                           St->getPointerInfo(),
11422                           St->isVolatile(), St->isNonTemporal(),
11423                           St->getAlignment());
11424     }
11425
11426     // Otherwise, lower to two pairs of 32-bit loads / stores.
11427     SDValue LoAddr = Ld->getBasePtr();
11428     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11429                                  DAG.getConstant(4, MVT::i32));
11430
11431     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11432                                Ld->getPointerInfo(),
11433                                Ld->isVolatile(), Ld->isNonTemporal(),
11434                                Ld->getAlignment());
11435     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11436                                Ld->getPointerInfo().getWithOffset(4),
11437                                Ld->isVolatile(), Ld->isNonTemporal(),
11438                                MinAlign(Ld->getAlignment(), 4));
11439
11440     SDValue NewChain = LoLd.getValue(1);
11441     if (TokenFactorIndex != -1) {
11442       Ops.push_back(LoLd);
11443       Ops.push_back(HiLd);
11444       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11445                              Ops.size());
11446     }
11447
11448     LoAddr = St->getBasePtr();
11449     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11450                          DAG.getConstant(4, MVT::i32));
11451
11452     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11453                                 St->getPointerInfo(),
11454                                 St->isVolatile(), St->isNonTemporal(),
11455                                 St->getAlignment());
11456     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11457                                 St->getPointerInfo().getWithOffset(4),
11458                                 St->isVolatile(),
11459                                 St->isNonTemporal(),
11460                                 MinAlign(St->getAlignment(), 4));
11461     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11462   }
11463   return SDValue();
11464 }
11465
11466 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11467 /// X86ISD::FXOR nodes.
11468 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11469   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11470   // F[X]OR(0.0, x) -> x
11471   // F[X]OR(x, 0.0) -> x
11472   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11473     if (C->getValueAPF().isPosZero())
11474       return N->getOperand(1);
11475   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11476     if (C->getValueAPF().isPosZero())
11477       return N->getOperand(0);
11478   return SDValue();
11479 }
11480
11481 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11482 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11483   // FAND(0.0, x) -> 0.0
11484   // FAND(x, 0.0) -> 0.0
11485   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11486     if (C->getValueAPF().isPosZero())
11487       return N->getOperand(0);
11488   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11489     if (C->getValueAPF().isPosZero())
11490       return N->getOperand(1);
11491   return SDValue();
11492 }
11493
11494 static SDValue PerformBTCombine(SDNode *N,
11495                                 SelectionDAG &DAG,
11496                                 TargetLowering::DAGCombinerInfo &DCI) {
11497   // BT ignores high bits in the bit index operand.
11498   SDValue Op1 = N->getOperand(1);
11499   if (Op1.hasOneUse()) {
11500     unsigned BitWidth = Op1.getValueSizeInBits();
11501     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11502     APInt KnownZero, KnownOne;
11503     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11504                                           !DCI.isBeforeLegalizeOps());
11505     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11506     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11507         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11508       DCI.CommitTargetLoweringOpt(TLO);
11509   }
11510   return SDValue();
11511 }
11512
11513 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11514   SDValue Op = N->getOperand(0);
11515   if (Op.getOpcode() == ISD::BITCAST)
11516     Op = Op.getOperand(0);
11517   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11518   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11519       VT.getVectorElementType().getSizeInBits() ==
11520       OpVT.getVectorElementType().getSizeInBits()) {
11521     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11522   }
11523   return SDValue();
11524 }
11525
11526 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11527   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11528   //           (and (i32 x86isd::setcc_carry), 1)
11529   // This eliminates the zext. This transformation is necessary because
11530   // ISD::SETCC is always legalized to i8.
11531   DebugLoc dl = N->getDebugLoc();
11532   SDValue N0 = N->getOperand(0);
11533   EVT VT = N->getValueType(0);
11534   if (N0.getOpcode() == ISD::AND &&
11535       N0.hasOneUse() &&
11536       N0.getOperand(0).hasOneUse()) {
11537     SDValue N00 = N0.getOperand(0);
11538     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11539       return SDValue();
11540     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11541     if (!C || C->getZExtValue() != 1)
11542       return SDValue();
11543     return DAG.getNode(ISD::AND, dl, VT,
11544                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11545                                    N00.getOperand(0), N00.getOperand(1)),
11546                        DAG.getConstant(1, VT));
11547   }
11548
11549   return SDValue();
11550 }
11551
11552 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11553 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11554   unsigned X86CC = N->getConstantOperandVal(0);
11555   SDValue EFLAG = N->getOperand(1);
11556   DebugLoc DL = N->getDebugLoc();
11557
11558   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11559   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11560   // cases.
11561   if (X86CC == X86::COND_B)
11562     return DAG.getNode(ISD::AND, DL, MVT::i8,
11563                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11564                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11565                        DAG.getConstant(1, MVT::i8));
11566
11567   return SDValue();
11568 }
11569
11570 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11571 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11572                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11573   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11574   // the result is either zero or one (depending on the input carry bit).
11575   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11576   if (X86::isZeroNode(N->getOperand(0)) &&
11577       X86::isZeroNode(N->getOperand(1)) &&
11578       // We don't have a good way to replace an EFLAGS use, so only do this when
11579       // dead right now.
11580       SDValue(N, 1).use_empty()) {
11581     DebugLoc DL = N->getDebugLoc();
11582     EVT VT = N->getValueType(0);
11583     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11584     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11585                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11586                                            DAG.getConstant(X86::COND_B,MVT::i8),
11587                                            N->getOperand(2)),
11588                                DAG.getConstant(1, VT));
11589     return DCI.CombineTo(N, Res1, CarryOut);
11590   }
11591
11592   return SDValue();
11593 }
11594
11595 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11596 //      (add Y, (setne X, 0)) -> sbb -1, Y
11597 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11598 //      (sub (setne X, 0), Y) -> adc -1, Y
11599 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11600   DebugLoc DL = N->getDebugLoc();
11601
11602   // Look through ZExts.
11603   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11604   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11605     return SDValue();
11606
11607   SDValue SetCC = Ext.getOperand(0);
11608   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11609     return SDValue();
11610
11611   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11612   if (CC != X86::COND_E && CC != X86::COND_NE)
11613     return SDValue();
11614
11615   SDValue Cmp = SetCC.getOperand(1);
11616   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11617       !X86::isZeroNode(Cmp.getOperand(1)) ||
11618       !Cmp.getOperand(0).getValueType().isInteger())
11619     return SDValue();
11620
11621   SDValue CmpOp0 = Cmp.getOperand(0);
11622   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11623                                DAG.getConstant(1, CmpOp0.getValueType()));
11624
11625   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11626   if (CC == X86::COND_NE)
11627     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11628                        DL, OtherVal.getValueType(), OtherVal,
11629                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11630   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11631                      DL, OtherVal.getValueType(), OtherVal,
11632                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11633 }
11634
11635 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11636                                              DAGCombinerInfo &DCI) const {
11637   SelectionDAG &DAG = DCI.DAG;
11638   switch (N->getOpcode()) {
11639   default: break;
11640   case ISD::EXTRACT_VECTOR_ELT:
11641     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11642   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11643   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11644   case ISD::ADD:
11645   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
11646   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11647   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11648   case ISD::SHL:
11649   case ISD::SRA:
11650   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11651   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11652   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11653   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11654   case X86ISD::FXOR:
11655   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11656   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11657   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11658   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11659   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11660   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
11661   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11662   case X86ISD::SHUFPD:
11663   case X86ISD::PALIGN:
11664   case X86ISD::PUNPCKHBW:
11665   case X86ISD::PUNPCKHWD:
11666   case X86ISD::PUNPCKHDQ:
11667   case X86ISD::PUNPCKHQDQ:
11668   case X86ISD::UNPCKHPS:
11669   case X86ISD::UNPCKHPD:
11670   case X86ISD::PUNPCKLBW:
11671   case X86ISD::PUNPCKLWD:
11672   case X86ISD::PUNPCKLDQ:
11673   case X86ISD::PUNPCKLQDQ:
11674   case X86ISD::UNPCKLPS:
11675   case X86ISD::UNPCKLPD:
11676   case X86ISD::MOVHLPS:
11677   case X86ISD::MOVLHPS:
11678   case X86ISD::PSHUFD:
11679   case X86ISD::PSHUFHW:
11680   case X86ISD::PSHUFLW:
11681   case X86ISD::MOVSS:
11682   case X86ISD::MOVSD:
11683   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11684   }
11685
11686   return SDValue();
11687 }
11688
11689 /// isTypeDesirableForOp - Return true if the target has native support for
11690 /// the specified value type and it is 'desirable' to use the type for the
11691 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11692 /// instruction encodings are longer and some i16 instructions are slow.
11693 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11694   if (!isTypeLegal(VT))
11695     return false;
11696   if (VT != MVT::i16)
11697     return true;
11698
11699   switch (Opc) {
11700   default:
11701     return true;
11702   case ISD::LOAD:
11703   case ISD::SIGN_EXTEND:
11704   case ISD::ZERO_EXTEND:
11705   case ISD::ANY_EXTEND:
11706   case ISD::SHL:
11707   case ISD::SRL:
11708   case ISD::SUB:
11709   case ISD::ADD:
11710   case ISD::MUL:
11711   case ISD::AND:
11712   case ISD::OR:
11713   case ISD::XOR:
11714     return false;
11715   }
11716 }
11717
11718 /// IsDesirableToPromoteOp - This method query the target whether it is
11719 /// beneficial for dag combiner to promote the specified node. If true, it
11720 /// should return the desired promotion type by reference.
11721 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11722   EVT VT = Op.getValueType();
11723   if (VT != MVT::i16)
11724     return false;
11725
11726   bool Promote = false;
11727   bool Commute = false;
11728   switch (Op.getOpcode()) {
11729   default: break;
11730   case ISD::LOAD: {
11731     LoadSDNode *LD = cast<LoadSDNode>(Op);
11732     // If the non-extending load has a single use and it's not live out, then it
11733     // might be folded.
11734     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11735                                                      Op.hasOneUse()*/) {
11736       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11737              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11738         // The only case where we'd want to promote LOAD (rather then it being
11739         // promoted as an operand is when it's only use is liveout.
11740         if (UI->getOpcode() != ISD::CopyToReg)
11741           return false;
11742       }
11743     }
11744     Promote = true;
11745     break;
11746   }
11747   case ISD::SIGN_EXTEND:
11748   case ISD::ZERO_EXTEND:
11749   case ISD::ANY_EXTEND:
11750     Promote = true;
11751     break;
11752   case ISD::SHL:
11753   case ISD::SRL: {
11754     SDValue N0 = Op.getOperand(0);
11755     // Look out for (store (shl (load), x)).
11756     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11757       return false;
11758     Promote = true;
11759     break;
11760   }
11761   case ISD::ADD:
11762   case ISD::MUL:
11763   case ISD::AND:
11764   case ISD::OR:
11765   case ISD::XOR:
11766     Commute = true;
11767     // fallthrough
11768   case ISD::SUB: {
11769     SDValue N0 = Op.getOperand(0);
11770     SDValue N1 = Op.getOperand(1);
11771     if (!Commute && MayFoldLoad(N1))
11772       return false;
11773     // Avoid disabling potential load folding opportunities.
11774     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11775       return false;
11776     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11777       return false;
11778     Promote = true;
11779   }
11780   }
11781
11782   PVT = MVT::i32;
11783   return Promote;
11784 }
11785
11786 //===----------------------------------------------------------------------===//
11787 //                           X86 Inline Assembly Support
11788 //===----------------------------------------------------------------------===//
11789
11790 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11791   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11792
11793   std::string AsmStr = IA->getAsmString();
11794
11795   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11796   SmallVector<StringRef, 4> AsmPieces;
11797   SplitString(AsmStr, AsmPieces, ";\n");
11798
11799   switch (AsmPieces.size()) {
11800   default: return false;
11801   case 1:
11802     AsmStr = AsmPieces[0];
11803     AsmPieces.clear();
11804     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11805
11806     // FIXME: this should verify that we are targetting a 486 or better.  If not,
11807     // we will turn this bswap into something that will be lowered to logical ops
11808     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11809     // so don't worry about this.
11810     // bswap $0
11811     if (AsmPieces.size() == 2 &&
11812         (AsmPieces[0] == "bswap" ||
11813          AsmPieces[0] == "bswapq" ||
11814          AsmPieces[0] == "bswapl") &&
11815         (AsmPieces[1] == "$0" ||
11816          AsmPieces[1] == "${0:q}")) {
11817       // No need to check constraints, nothing other than the equivalent of
11818       // "=r,0" would be valid here.
11819       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11820       if (!Ty || Ty->getBitWidth() % 16 != 0)
11821         return false;
11822       return IntrinsicLowering::LowerToByteSwap(CI);
11823     }
11824     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11825     if (CI->getType()->isIntegerTy(16) &&
11826         AsmPieces.size() == 3 &&
11827         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11828         AsmPieces[1] == "$$8," &&
11829         AsmPieces[2] == "${0:w}" &&
11830         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11831       AsmPieces.clear();
11832       const std::string &ConstraintsStr = IA->getConstraintString();
11833       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
11834       std::sort(AsmPieces.begin(), AsmPieces.end());
11835       if (AsmPieces.size() == 4 &&
11836           AsmPieces[0] == "~{cc}" &&
11837           AsmPieces[1] == "~{dirflag}" &&
11838           AsmPieces[2] == "~{flags}" &&
11839           AsmPieces[3] == "~{fpsr}") {
11840         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11841         if (!Ty || Ty->getBitWidth() % 16 != 0)
11842           return false;
11843         return IntrinsicLowering::LowerToByteSwap(CI);
11844       }
11845     }
11846     break;
11847   case 3:
11848     if (CI->getType()->isIntegerTy(32) &&
11849         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11850       SmallVector<StringRef, 4> Words;
11851       SplitString(AsmPieces[0], Words, " \t,");
11852       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11853           Words[2] == "${0:w}") {
11854         Words.clear();
11855         SplitString(AsmPieces[1], Words, " \t,");
11856         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11857             Words[2] == "$0") {
11858           Words.clear();
11859           SplitString(AsmPieces[2], Words, " \t,");
11860           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11861               Words[2] == "${0:w}") {
11862             AsmPieces.clear();
11863             const std::string &ConstraintsStr = IA->getConstraintString();
11864             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
11865             std::sort(AsmPieces.begin(), AsmPieces.end());
11866             if (AsmPieces.size() == 4 &&
11867                 AsmPieces[0] == "~{cc}" &&
11868                 AsmPieces[1] == "~{dirflag}" &&
11869                 AsmPieces[2] == "~{flags}" &&
11870                 AsmPieces[3] == "~{fpsr}") {
11871               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11872               if (!Ty || Ty->getBitWidth() % 16 != 0)
11873                 return false;
11874               return IntrinsicLowering::LowerToByteSwap(CI);
11875             }
11876           }
11877         }
11878       }
11879     }
11880
11881     if (CI->getType()->isIntegerTy(64)) {
11882       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11883       if (Constraints.size() >= 2 &&
11884           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11885           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11886         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11887         SmallVector<StringRef, 4> Words;
11888         SplitString(AsmPieces[0], Words, " \t");
11889         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11890           Words.clear();
11891           SplitString(AsmPieces[1], Words, " \t");
11892           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11893             Words.clear();
11894             SplitString(AsmPieces[2], Words, " \t,");
11895             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11896                 Words[2] == "%edx") {
11897               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11898               if (!Ty || Ty->getBitWidth() % 16 != 0)
11899                 return false;
11900               return IntrinsicLowering::LowerToByteSwap(CI);
11901             }
11902           }
11903         }
11904       }
11905     }
11906     break;
11907   }
11908   return false;
11909 }
11910
11911
11912
11913 /// getConstraintType - Given a constraint letter, return the type of
11914 /// constraint it is for this target.
11915 X86TargetLowering::ConstraintType
11916 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11917   if (Constraint.size() == 1) {
11918     switch (Constraint[0]) {
11919     case 'R':
11920     case 'q':
11921     case 'Q':
11922     case 'f':
11923     case 't':
11924     case 'u':
11925     case 'y':
11926     case 'x':
11927     case 'Y':
11928       return C_RegisterClass;
11929     case 'a':
11930     case 'b':
11931     case 'c':
11932     case 'd':
11933     case 'S':
11934     case 'D':
11935     case 'A':
11936       return C_Register;
11937     case 'I':
11938     case 'J':
11939     case 'K':
11940     case 'L':
11941     case 'M':
11942     case 'N':
11943     case 'G':
11944     case 'C':
11945     case 'e':
11946     case 'Z':
11947       return C_Other;
11948     default:
11949       break;
11950     }
11951   }
11952   return TargetLowering::getConstraintType(Constraint);
11953 }
11954
11955 /// Examine constraint type and operand type and determine a weight value.
11956 /// This object must already have been set up with the operand type
11957 /// and the current alternative constraint selected.
11958 TargetLowering::ConstraintWeight
11959   X86TargetLowering::getSingleConstraintMatchWeight(
11960     AsmOperandInfo &info, const char *constraint) const {
11961   ConstraintWeight weight = CW_Invalid;
11962   Value *CallOperandVal = info.CallOperandVal;
11963     // If we don't have a value, we can't do a match,
11964     // but allow it at the lowest weight.
11965   if (CallOperandVal == NULL)
11966     return CW_Default;
11967   const Type *type = CallOperandVal->getType();
11968   // Look at the constraint type.
11969   switch (*constraint) {
11970   default:
11971     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11972   case 'R':
11973   case 'q':
11974   case 'Q':
11975   case 'a':
11976   case 'b':
11977   case 'c':
11978   case 'd':
11979   case 'S':
11980   case 'D':
11981   case 'A':
11982     if (CallOperandVal->getType()->isIntegerTy())
11983       weight = CW_SpecificReg;
11984     break;
11985   case 'f':
11986   case 't':
11987   case 'u':
11988       if (type->isFloatingPointTy())
11989         weight = CW_SpecificReg;
11990       break;
11991   case 'y':
11992       if (type->isX86_MMXTy() && Subtarget->hasMMX())
11993         weight = CW_SpecificReg;
11994       break;
11995   case 'x':
11996   case 'Y':
11997     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11998       weight = CW_Register;
11999     break;
12000   case 'I':
12001     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12002       if (C->getZExtValue() <= 31)
12003         weight = CW_Constant;
12004     }
12005     break;
12006   case 'J':
12007     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12008       if (C->getZExtValue() <= 63)
12009         weight = CW_Constant;
12010     }
12011     break;
12012   case 'K':
12013     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12014       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12015         weight = CW_Constant;
12016     }
12017     break;
12018   case 'L':
12019     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12020       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12021         weight = CW_Constant;
12022     }
12023     break;
12024   case 'M':
12025     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12026       if (C->getZExtValue() <= 3)
12027         weight = CW_Constant;
12028     }
12029     break;
12030   case 'N':
12031     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12032       if (C->getZExtValue() <= 0xff)
12033         weight = CW_Constant;
12034     }
12035     break;
12036   case 'G':
12037   case 'C':
12038     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12039       weight = CW_Constant;
12040     }
12041     break;
12042   case 'e':
12043     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12044       if ((C->getSExtValue() >= -0x80000000LL) &&
12045           (C->getSExtValue() <= 0x7fffffffLL))
12046         weight = CW_Constant;
12047     }
12048     break;
12049   case 'Z':
12050     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12051       if (C->getZExtValue() <= 0xffffffff)
12052         weight = CW_Constant;
12053     }
12054     break;
12055   }
12056   return weight;
12057 }
12058
12059 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12060 /// with another that has more specific requirements based on the type of the
12061 /// corresponding operand.
12062 const char *X86TargetLowering::
12063 LowerXConstraint(EVT ConstraintVT) const {
12064   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12065   // 'f' like normal targets.
12066   if (ConstraintVT.isFloatingPoint()) {
12067     if (Subtarget->hasXMMInt())
12068       return "Y";
12069     if (Subtarget->hasXMM())
12070       return "x";
12071   }
12072
12073   return TargetLowering::LowerXConstraint(ConstraintVT);
12074 }
12075
12076 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12077 /// vector.  If it is invalid, don't add anything to Ops.
12078 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12079                                                      char Constraint,
12080                                                      std::vector<SDValue>&Ops,
12081                                                      SelectionDAG &DAG) const {
12082   SDValue Result(0, 0);
12083
12084   switch (Constraint) {
12085   default: break;
12086   case 'I':
12087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12088       if (C->getZExtValue() <= 31) {
12089         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12090         break;
12091       }
12092     }
12093     return;
12094   case 'J':
12095     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12096       if (C->getZExtValue() <= 63) {
12097         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12098         break;
12099       }
12100     }
12101     return;
12102   case 'K':
12103     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12104       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12105         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12106         break;
12107       }
12108     }
12109     return;
12110   case 'N':
12111     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12112       if (C->getZExtValue() <= 255) {
12113         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12114         break;
12115       }
12116     }
12117     return;
12118   case 'e': {
12119     // 32-bit signed value
12120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12121       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12122                                            C->getSExtValue())) {
12123         // Widen to 64 bits here to get it sign extended.
12124         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12125         break;
12126       }
12127     // FIXME gcc accepts some relocatable values here too, but only in certain
12128     // memory models; it's complicated.
12129     }
12130     return;
12131   }
12132   case 'Z': {
12133     // 32-bit unsigned value
12134     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12135       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12136                                            C->getZExtValue())) {
12137         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12138         break;
12139       }
12140     }
12141     // FIXME gcc accepts some relocatable values here too, but only in certain
12142     // memory models; it's complicated.
12143     return;
12144   }
12145   case 'i': {
12146     // Literal immediates are always ok.
12147     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12148       // Widen to 64 bits here to get it sign extended.
12149       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12150       break;
12151     }
12152
12153     // In any sort of PIC mode addresses need to be computed at runtime by
12154     // adding in a register or some sort of table lookup.  These can't
12155     // be used as immediates.
12156     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12157       return;
12158
12159     // If we are in non-pic codegen mode, we allow the address of a global (with
12160     // an optional displacement) to be used with 'i'.
12161     GlobalAddressSDNode *GA = 0;
12162     int64_t Offset = 0;
12163
12164     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12165     while (1) {
12166       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12167         Offset += GA->getOffset();
12168         break;
12169       } else if (Op.getOpcode() == ISD::ADD) {
12170         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12171           Offset += C->getZExtValue();
12172           Op = Op.getOperand(0);
12173           continue;
12174         }
12175       } else if (Op.getOpcode() == ISD::SUB) {
12176         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12177           Offset += -C->getZExtValue();
12178           Op = Op.getOperand(0);
12179           continue;
12180         }
12181       }
12182
12183       // Otherwise, this isn't something we can handle, reject it.
12184       return;
12185     }
12186
12187     const GlobalValue *GV = GA->getGlobal();
12188     // If we require an extra load to get this address, as in PIC mode, we
12189     // can't accept it.
12190     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12191                                                         getTargetMachine())))
12192       return;
12193
12194     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12195                                         GA->getValueType(0), Offset);
12196     break;
12197   }
12198   }
12199
12200   if (Result.getNode()) {
12201     Ops.push_back(Result);
12202     return;
12203   }
12204   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12205 }
12206
12207 std::vector<unsigned> X86TargetLowering::
12208 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12209                                   EVT VT) const {
12210   if (Constraint.size() == 1) {
12211     // FIXME: not handling fp-stack yet!
12212     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12213     default: break;  // Unknown constraint letter
12214     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12215       if (Subtarget->is64Bit()) {
12216         if (VT == MVT::i32)
12217           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12218                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12219                                        X86::R10D,X86::R11D,X86::R12D,
12220                                        X86::R13D,X86::R14D,X86::R15D,
12221                                        X86::EBP, X86::ESP, 0);
12222         else if (VT == MVT::i16)
12223           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12224                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12225                                        X86::R10W,X86::R11W,X86::R12W,
12226                                        X86::R13W,X86::R14W,X86::R15W,
12227                                        X86::BP,  X86::SP, 0);
12228         else if (VT == MVT::i8)
12229           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12230                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12231                                        X86::R10B,X86::R11B,X86::R12B,
12232                                        X86::R13B,X86::R14B,X86::R15B,
12233                                        X86::BPL, X86::SPL, 0);
12234
12235         else if (VT == MVT::i64)
12236           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12237                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12238                                        X86::R10, X86::R11, X86::R12,
12239                                        X86::R13, X86::R14, X86::R15,
12240                                        X86::RBP, X86::RSP, 0);
12241
12242         break;
12243       }
12244       // 32-bit fallthrough
12245     case 'Q':   // Q_REGS
12246       if (VT == MVT::i32)
12247         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12248       else if (VT == MVT::i16)
12249         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12250       else if (VT == MVT::i8)
12251         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12252       else if (VT == MVT::i64)
12253         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12254       break;
12255     }
12256   }
12257
12258   return std::vector<unsigned>();
12259 }
12260
12261 std::pair<unsigned, const TargetRegisterClass*>
12262 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12263                                                 EVT VT) const {
12264   // First, see if this is a constraint that directly corresponds to an LLVM
12265   // register class.
12266   if (Constraint.size() == 1) {
12267     // GCC Constraint Letters
12268     switch (Constraint[0]) {
12269     default: break;
12270     case 'r':   // GENERAL_REGS
12271     case 'l':   // INDEX_REGS
12272       if (VT == MVT::i8)
12273         return std::make_pair(0U, X86::GR8RegisterClass);
12274       if (VT == MVT::i16)
12275         return std::make_pair(0U, X86::GR16RegisterClass);
12276       if (VT == MVT::i32 || !Subtarget->is64Bit())
12277         return std::make_pair(0U, X86::GR32RegisterClass);
12278       return std::make_pair(0U, X86::GR64RegisterClass);
12279     case 'R':   // LEGACY_REGS
12280       if (VT == MVT::i8)
12281         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12282       if (VT == MVT::i16)
12283         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12284       if (VT == MVT::i32 || !Subtarget->is64Bit())
12285         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12286       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12287     case 'f':  // FP Stack registers.
12288       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12289       // value to the correct fpstack register class.
12290       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12291         return std::make_pair(0U, X86::RFP32RegisterClass);
12292       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12293         return std::make_pair(0U, X86::RFP64RegisterClass);
12294       return std::make_pair(0U, X86::RFP80RegisterClass);
12295     case 'y':   // MMX_REGS if MMX allowed.
12296       if (!Subtarget->hasMMX()) break;
12297       return std::make_pair(0U, X86::VR64RegisterClass);
12298     case 'Y':   // SSE_REGS if SSE2 allowed
12299       if (!Subtarget->hasXMMInt()) break;
12300       // FALL THROUGH.
12301     case 'x':   // SSE_REGS if SSE1 allowed
12302       if (!Subtarget->hasXMM()) break;
12303
12304       switch (VT.getSimpleVT().SimpleTy) {
12305       default: break;
12306       // Scalar SSE types.
12307       case MVT::f32:
12308       case MVT::i32:
12309         return std::make_pair(0U, X86::FR32RegisterClass);
12310       case MVT::f64:
12311       case MVT::i64:
12312         return std::make_pair(0U, X86::FR64RegisterClass);
12313       // Vector types.
12314       case MVT::v16i8:
12315       case MVT::v8i16:
12316       case MVT::v4i32:
12317       case MVT::v2i64:
12318       case MVT::v4f32:
12319       case MVT::v2f64:
12320         return std::make_pair(0U, X86::VR128RegisterClass);
12321       }
12322       break;
12323     }
12324   }
12325
12326   // Use the default implementation in TargetLowering to convert the register
12327   // constraint into a member of a register class.
12328   std::pair<unsigned, const TargetRegisterClass*> Res;
12329   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12330
12331   // Not found as a standard register?
12332   if (Res.second == 0) {
12333     // Map st(0) -> st(7) -> ST0
12334     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12335         tolower(Constraint[1]) == 's' &&
12336         tolower(Constraint[2]) == 't' &&
12337         Constraint[3] == '(' &&
12338         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12339         Constraint[5] == ')' &&
12340         Constraint[6] == '}') {
12341
12342       Res.first = X86::ST0+Constraint[4]-'0';
12343       Res.second = X86::RFP80RegisterClass;
12344       return Res;
12345     }
12346
12347     // GCC allows "st(0)" to be called just plain "st".
12348     if (StringRef("{st}").equals_lower(Constraint)) {
12349       Res.first = X86::ST0;
12350       Res.second = X86::RFP80RegisterClass;
12351       return Res;
12352     }
12353
12354     // flags -> EFLAGS
12355     if (StringRef("{flags}").equals_lower(Constraint)) {
12356       Res.first = X86::EFLAGS;
12357       Res.second = X86::CCRRegisterClass;
12358       return Res;
12359     }
12360
12361     // 'A' means EAX + EDX.
12362     if (Constraint == "A") {
12363       Res.first = X86::EAX;
12364       Res.second = X86::GR32_ADRegisterClass;
12365       return Res;
12366     }
12367     return Res;
12368   }
12369
12370   // Otherwise, check to see if this is a register class of the wrong value
12371   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12372   // turn into {ax},{dx}.
12373   if (Res.second->hasType(VT))
12374     return Res;   // Correct type already, nothing to do.
12375
12376   // All of the single-register GCC register classes map their values onto
12377   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12378   // really want an 8-bit or 32-bit register, map to the appropriate register
12379   // class and return the appropriate register.
12380   if (Res.second == X86::GR16RegisterClass) {
12381     if (VT == MVT::i8) {
12382       unsigned DestReg = 0;
12383       switch (Res.first) {
12384       default: break;
12385       case X86::AX: DestReg = X86::AL; break;
12386       case X86::DX: DestReg = X86::DL; break;
12387       case X86::CX: DestReg = X86::CL; break;
12388       case X86::BX: DestReg = X86::BL; break;
12389       }
12390       if (DestReg) {
12391         Res.first = DestReg;
12392         Res.second = X86::GR8RegisterClass;
12393       }
12394     } else if (VT == MVT::i32) {
12395       unsigned DestReg = 0;
12396       switch (Res.first) {
12397       default: break;
12398       case X86::AX: DestReg = X86::EAX; break;
12399       case X86::DX: DestReg = X86::EDX; break;
12400       case X86::CX: DestReg = X86::ECX; break;
12401       case X86::BX: DestReg = X86::EBX; break;
12402       case X86::SI: DestReg = X86::ESI; break;
12403       case X86::DI: DestReg = X86::EDI; break;
12404       case X86::BP: DestReg = X86::EBP; break;
12405       case X86::SP: DestReg = X86::ESP; break;
12406       }
12407       if (DestReg) {
12408         Res.first = DestReg;
12409         Res.second = X86::GR32RegisterClass;
12410       }
12411     } else if (VT == MVT::i64) {
12412       unsigned DestReg = 0;
12413       switch (Res.first) {
12414       default: break;
12415       case X86::AX: DestReg = X86::RAX; break;
12416       case X86::DX: DestReg = X86::RDX; break;
12417       case X86::CX: DestReg = X86::RCX; break;
12418       case X86::BX: DestReg = X86::RBX; break;
12419       case X86::SI: DestReg = X86::RSI; break;
12420       case X86::DI: DestReg = X86::RDI; break;
12421       case X86::BP: DestReg = X86::RBP; break;
12422       case X86::SP: DestReg = X86::RSP; break;
12423       }
12424       if (DestReg) {
12425         Res.first = DestReg;
12426         Res.second = X86::GR64RegisterClass;
12427       }
12428     }
12429   } else if (Res.second == X86::FR32RegisterClass ||
12430              Res.second == X86::FR64RegisterClass ||
12431              Res.second == X86::VR128RegisterClass) {
12432     // Handle references to XMM physical registers that got mapped into the
12433     // wrong class.  This can happen with constraints like {xmm0} where the
12434     // target independent register mapper will just pick the first match it can
12435     // find, ignoring the required type.
12436     if (VT == MVT::f32)
12437       Res.second = X86::FR32RegisterClass;
12438     else if (VT == MVT::f64)
12439       Res.second = X86::FR64RegisterClass;
12440     else if (X86::VR128RegisterClass->hasType(VT))
12441       Res.second = X86::VR128RegisterClass;
12442   }
12443
12444   return Res;
12445 }