eliminate the now-unneeded context argument of MBB::getSymbol()
[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 "X86MCTargetExpr.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionMachO.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 static cl::opt<bool>
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60
61 // Disable16Bit - 16-bit operations typically have a larger encoding than
62 // corresponding 32-bit instructions, and 16-bit code is slow on some
63 // processors. This is an experimental flag to disable 16-bit operations
64 // (which forces them to be Legalized to 32-bit operations).
65 static cl::opt<bool>
66 Disable16Bit("disable-16bit", cl::Hidden,
67              cl::desc("Disable use of 16-bit instructions"));
68
69 // Forward declarations.
70 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
71                        SDValue V2);
72
73 // FIXME: This is for a test.
74 static cl::opt<bool>
75 EnableX86EHTest("enable-x86-eh-test", cl::Hidden);
76
77 namespace llvm {
78   class X86_test_MachoTargetObjectFile : public TargetLoweringObjectFileMachO {
79   public:
80     virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
81       TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
82
83       // Exception Handling.
84       LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
85                                     SectionKind::getReadOnlyWithRel());
86     }
87
88     virtual unsigned getTTypeEncoding() const {
89       return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
90     }
91   };
92
93   class X8664_test_MachoTargetObjectFile : public X8664_MachoTargetObjectFile {
94   public:
95     virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
96       TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
97
98       // Exception Handling.
99       LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
100                                     SectionKind::getReadOnlyWithRel());
101     }
102
103     virtual unsigned getTTypeEncoding() const {
104       return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
105     }
106   };
107 }
108
109 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
110   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
111   default: llvm_unreachable("unknown subtarget type");
112   case X86Subtarget::isDarwin:
113     // FIXME: This is for an EH test.
114     if (EnableX86EHTest) {
115       if (TM.getSubtarget<X86Subtarget>().is64Bit())
116         return new X8664_test_MachoTargetObjectFile();
117       else
118         return new X86_test_MachoTargetObjectFile();
119     }
120
121     if (TM.getSubtarget<X86Subtarget>().is64Bit())
122       return new X8664_MachoTargetObjectFile();
123     return new TargetLoweringObjectFileMachO();
124   case X86Subtarget::isELF:
125    if (TM.getSubtarget<X86Subtarget>().is64Bit())
126      return new X8664_ELFTargetObjectFile(TM);
127     return new X8632_ELFTargetObjectFile(TM);
128   case X86Subtarget::isMingw:
129   case X86Subtarget::isCygwin:
130   case X86Subtarget::isWindows:
131     return new TargetLoweringObjectFileCOFF();
132   }
133 }
134
135 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
136   : TargetLowering(TM, createTLOF(TM)) {
137   Subtarget = &TM.getSubtarget<X86Subtarget>();
138   X86ScalarSSEf64 = Subtarget->hasSSE2();
139   X86ScalarSSEf32 = Subtarget->hasSSE1();
140   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
141
142   RegInfo = TM.getRegisterInfo();
143   TD = getTargetData();
144
145   // Set up the TargetLowering object.
146
147   // X86 is weird, it always uses i8 for shift amounts and setcc results.
148   setShiftAmountType(MVT::i8);
149   setBooleanContents(ZeroOrOneBooleanContent);
150   setSchedulingPreference(SchedulingForRegPressure);
151   setStackPointerRegisterToSaveRestore(X86StackPtr);
152
153   if (Subtarget->isTargetDarwin()) {
154     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
155     setUseUnderscoreSetJmp(false);
156     setUseUnderscoreLongJmp(false);
157   } else if (Subtarget->isTargetMingw()) {
158     // MS runtime is weird: it exports _setjmp, but longjmp!
159     setUseUnderscoreSetJmp(true);
160     setUseUnderscoreLongJmp(false);
161   } else {
162     setUseUnderscoreSetJmp(true);
163     setUseUnderscoreLongJmp(true);
164   }
165
166   // Set up the register classes.
167   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
168   if (!Disable16Bit)
169     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
170   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
171   if (Subtarget->is64Bit())
172     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
173
174   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
175
176   // We don't accept any truncstore of integer registers.
177   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
178   if (!Disable16Bit)
179     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
180   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
181   if (!Disable16Bit)
182     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
183   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
184   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
185
186   // SETOEQ and SETUNE require checking two conditions.
187   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
188   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
189   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
190   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
191   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
192   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
193
194   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
195   // operation.
196   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
197   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
198   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
199
200   if (Subtarget->is64Bit()) {
201     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
202     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
203   } else if (!UseSoftFloat) {
204     if (X86ScalarSSEf64) {
205       // We have an impenetrably clever algorithm for ui64->double only.
206       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
207     }
208     // We have an algorithm for SSE2, and we turn this into a 64-bit
209     // FILD for other targets.
210     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
211   }
212
213   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
214   // this operation.
215   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
216   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
217
218   if (!UseSoftFloat) {
219     // SSE has no i16 to fp conversion, only i32
220     if (X86ScalarSSEf32) {
221       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
222       // f32 and f64 cases are Legal, f80 case is not
223       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
224     } else {
225       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
226       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
227     }
228   } else {
229     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
230     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
231   }
232
233   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
234   // are Legal, f80 is custom lowered.
235   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
236   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
237
238   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
239   // this operation.
240   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
241   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
242
243   if (X86ScalarSSEf32) {
244     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
245     // f32 and f64 cases are Legal, f80 case is not
246     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
247   } else {
248     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
249     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
250   }
251
252   // Handle FP_TO_UINT by promoting the destination to a larger signed
253   // conversion.
254   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
255   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
256   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
257
258   if (Subtarget->is64Bit()) {
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
260     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
261   } else if (!UseSoftFloat) {
262     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
263       // Expand FP_TO_UINT into a select.
264       // FIXME: We would like to use a Custom expander here eventually to do
265       // the optimal thing for SSE vs. the default expansion in the legalizer.
266       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
267     else
268       // With SSE3 we can use fisttpll to convert to a signed i64; without
269       // SSE, we're stuck with a fistpll.
270       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
271   }
272
273   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
274   if (!X86ScalarSSEf64) {
275     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
276     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
277   }
278
279   // Scalar integer divide and remainder are lowered to use operations that
280   // produce two results, to match the available instructions. This exposes
281   // the two-result form to trivial CSE, which is able to combine x/y and x%y
282   // into a single instruction.
283   //
284   // Scalar integer multiply-high is also lowered to use two-result
285   // operations, to match the available instructions. However, plain multiply
286   // (low) operations are left as Legal, as there are single-result
287   // instructions for this in x86. Using the two-result multiply instructions
288   // when both high and low results are needed must be arranged by dagcombine.
289   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
290   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
291   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
292   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
293   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
294   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
295   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
296   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
297   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
298   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
299   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
300   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
301   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
302   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
303   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
304   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
305   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
306   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
307   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
308   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
309   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
310   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
311   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
312   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
313
314   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
315   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
316   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
317   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
318   if (Subtarget->is64Bit())
319     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
320   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
321   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
322   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
323   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
324   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
325   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
326   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
327   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
328
329   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
330   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
331   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
332   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
333   if (Disable16Bit) {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
335     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
336   } else {
337     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
338     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
339   }
340   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
341   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
342   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
343   if (Subtarget->is64Bit()) {
344     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
345     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
346     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
347   }
348
349   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
350   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
351
352   // These should be promoted to a larger select which is supported.
353   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
354   // X86 wants to expand cmov itself.
355   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
356   if (Disable16Bit)
357     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
358   else
359     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
360   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
361   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
362   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
363   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
364   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
365   if (Disable16Bit)
366     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
367   else
368     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
369   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
370   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
371   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
372   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
375     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
376   }
377   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
378
379   // Darwin ABI issue.
380   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
381   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
382   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
383   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
384   if (Subtarget->is64Bit())
385     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
386   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
387   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
388   if (Subtarget->is64Bit()) {
389     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
390     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
391     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
392     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
393     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
394   }
395   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
396   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
397   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
398   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
399   if (Subtarget->is64Bit()) {
400     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
401     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
402     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
403   }
404
405   if (Subtarget->hasSSE1())
406     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
407
408   if (!Subtarget->hasSSE2())
409     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
410
411   // Expand certain atomics
412   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
413   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
414   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
415   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
416
417   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
418   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
419   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
420   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
421
422   if (!Subtarget->is64Bit()) {
423     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
424     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
425     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
426     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
427     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
428     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
429     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
430   }
431
432   // FIXME - use subtarget debug flags
433   if (!Subtarget->isTargetDarwin() &&
434       !Subtarget->isTargetELF() &&
435       !Subtarget->isTargetCygMing()) {
436     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
437   }
438
439   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
440   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
441   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
442   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
443   if (Subtarget->is64Bit()) {
444     setExceptionPointerRegister(X86::RAX);
445     setExceptionSelectorRegister(X86::RDX);
446   } else {
447     setExceptionPointerRegister(X86::EAX);
448     setExceptionSelectorRegister(X86::EDX);
449   }
450   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
451   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
452
453   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
454
455   setOperationAction(ISD::TRAP, MVT::Other, Legal);
456
457   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
458   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
459   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
460   if (Subtarget->is64Bit()) {
461     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
462     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
463   } else {
464     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
465     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
466   }
467
468   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
469   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
470   if (Subtarget->is64Bit())
471     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
472   if (Subtarget->isTargetCygMing())
473     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
474   else
475     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
476
477   if (!UseSoftFloat && X86ScalarSSEf64) {
478     // f32 and f64 use SSE.
479     // Set up the FP register classes.
480     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
481     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
482
483     // Use ANDPD to simulate FABS.
484     setOperationAction(ISD::FABS , MVT::f64, Custom);
485     setOperationAction(ISD::FABS , MVT::f32, Custom);
486
487     // Use XORP to simulate FNEG.
488     setOperationAction(ISD::FNEG , MVT::f64, Custom);
489     setOperationAction(ISD::FNEG , MVT::f32, Custom);
490
491     // Use ANDPD and ORPD to simulate FCOPYSIGN.
492     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
493     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
494
495     // We don't support sin/cos/fmod
496     setOperationAction(ISD::FSIN , MVT::f64, Expand);
497     setOperationAction(ISD::FCOS , MVT::f64, Expand);
498     setOperationAction(ISD::FSIN , MVT::f32, Expand);
499     setOperationAction(ISD::FCOS , MVT::f32, Expand);
500
501     // Expand FP immediates into loads from the stack, except for the special
502     // cases we handle.
503     addLegalFPImmediate(APFloat(+0.0)); // xorpd
504     addLegalFPImmediate(APFloat(+0.0f)); // xorps
505   } else if (!UseSoftFloat && X86ScalarSSEf32) {
506     // Use SSE for f32, x87 for f64.
507     // Set up the FP register classes.
508     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
509     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
510
511     // Use ANDPS to simulate FABS.
512     setOperationAction(ISD::FABS , MVT::f32, Custom);
513
514     // Use XORP to simulate FNEG.
515     setOperationAction(ISD::FNEG , MVT::f32, Custom);
516
517     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
518
519     // Use ANDPS and ORPS to simulate FCOPYSIGN.
520     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
521     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
522
523     // We don't support sin/cos/fmod
524     setOperationAction(ISD::FSIN , MVT::f32, Expand);
525     setOperationAction(ISD::FCOS , MVT::f32, Expand);
526
527     // Special cases we handle for FP constants.
528     addLegalFPImmediate(APFloat(+0.0f)); // xorps
529     addLegalFPImmediate(APFloat(+0.0)); // FLD0
530     addLegalFPImmediate(APFloat(+1.0)); // FLD1
531     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
532     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
533
534     if (!UnsafeFPMath) {
535       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
536       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
537     }
538   } else if (!UseSoftFloat) {
539     // f32 and f64 in x87.
540     // Set up the FP register classes.
541     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
542     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
543
544     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
545     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
546     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
547     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
548
549     if (!UnsafeFPMath) {
550       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
551       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
552     }
553     addLegalFPImmediate(APFloat(+0.0)); // FLD0
554     addLegalFPImmediate(APFloat(+1.0)); // FLD1
555     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
556     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
557     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
558     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
559     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
560     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
561   }
562
563   // Long double always uses X87.
564   if (!UseSoftFloat) {
565     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
566     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
567     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
568     {
569       bool ignored;
570       APFloat TmpFlt(+0.0);
571       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
572                      &ignored);
573       addLegalFPImmediate(TmpFlt);  // FLD0
574       TmpFlt.changeSign();
575       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
576       APFloat TmpFlt2(+1.0);
577       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
578                       &ignored);
579       addLegalFPImmediate(TmpFlt2);  // FLD1
580       TmpFlt2.changeSign();
581       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
582     }
583
584     if (!UnsafeFPMath) {
585       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
586       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
587     }
588   }
589
590   // Always use a library call for pow.
591   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
592   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
593   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
594
595   setOperationAction(ISD::FLOG, MVT::f80, Expand);
596   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
597   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
598   setOperationAction(ISD::FEXP, MVT::f80, Expand);
599   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
600
601   // First set operation action for all vector types to either promote
602   // (for widening) or expand (for scalarization). Then we will selectively
603   // turn on ones that can be effectively codegen'd.
604   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
606     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
610     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
614     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
615     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
616     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
617     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
618     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
619     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
620     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
621     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
622     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
623     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
624     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
625     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
626     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
627     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
628     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
629     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
630     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
631     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
632     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
633     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
634     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
635     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
636     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
637     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
638     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
639     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
640     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
641     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
642     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
643     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
644     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
645     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
646     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
647     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
648     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
649     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
650     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
651     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
652     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
653     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
654     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
655     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
656     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
657     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
658     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
659     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
660          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
661       setTruncStoreAction((MVT::SimpleValueType)VT,
662                           (MVT::SimpleValueType)InnerVT, Expand);
663     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
664     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
665     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
666   }
667
668   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
669   // with -msoft-float, disable use of MMX as well.
670   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
671     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
672     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
673     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
674     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
675     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
676
677     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
678     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
679     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
680     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
681
682     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
683     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
684     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
685     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
686
687     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
688     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
689
690     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
691     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
692     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
693     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
694     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
695     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
696     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
697
698     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
699     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
700     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
701     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
702     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
703     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
704     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
705
706     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
707     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
708     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
709     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
710     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
711     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
712     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
713
714     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
715     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
716     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
717     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
718     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
719     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
720     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
721     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
722     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
723
724     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
725     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
726     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
727     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
728     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
729
730     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
731     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
732     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
733     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
734
735     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
736     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
737     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
738     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
739
740     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
741
742     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
743     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
744     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
745     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
747     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
748     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
749   }
750
751   if (!UseSoftFloat && Subtarget->hasSSE1()) {
752     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
753
754     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
755     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
756     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
757     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
758     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
759     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
760     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
761     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
762     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
763     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
764     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
765     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
766   }
767
768   if (!UseSoftFloat && Subtarget->hasSSE2()) {
769     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
770
771     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
772     // registers cannot be used even for integer operations.
773     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
774     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
775     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
776     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
777
778     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
779     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
780     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
781     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
782     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
783     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
784     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
785     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
786     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
787     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
788     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
789     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
790     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
791     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
792     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
793     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
794
795     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
796     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
797     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
798     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
799
800     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
801     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
802     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
803     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
804     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
805
806     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
807     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
808     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
809     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
810     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
811
812     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
813     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
814       EVT VT = (MVT::SimpleValueType)i;
815       // Do not attempt to custom lower non-power-of-2 vectors
816       if (!isPowerOf2_32(VT.getVectorNumElements()))
817         continue;
818       // Do not attempt to custom lower non-128-bit vectors
819       if (!VT.is128BitVector())
820         continue;
821       setOperationAction(ISD::BUILD_VECTOR,
822                          VT.getSimpleVT().SimpleTy, Custom);
823       setOperationAction(ISD::VECTOR_SHUFFLE,
824                          VT.getSimpleVT().SimpleTy, Custom);
825       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
826                          VT.getSimpleVT().SimpleTy, Custom);
827     }
828
829     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
830     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
831     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
832     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
834     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
835
836     if (Subtarget->is64Bit()) {
837       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
838       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
839     }
840
841     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
842     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
843       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
844       EVT VT = SVT;
845
846       // Do not attempt to promote non-128-bit vectors
847       if (!VT.is128BitVector()) {
848         continue;
849       }
850       setOperationAction(ISD::AND,    SVT, Promote);
851       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
852       setOperationAction(ISD::OR,     SVT, Promote);
853       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
854       setOperationAction(ISD::XOR,    SVT, Promote);
855       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
856       setOperationAction(ISD::LOAD,   SVT, Promote);
857       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
858       setOperationAction(ISD::SELECT, SVT, Promote);
859       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
860     }
861
862     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
863
864     // Custom lower v2i64 and v2f64 selects.
865     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
866     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
867     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
868     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
869
870     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
871     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
872     if (!DisableMMX && Subtarget->hasMMX()) {
873       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
874       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
875     }
876   }
877
878   if (Subtarget->hasSSE41()) {
879     // FIXME: Do we need to handle scalar-to-vector here?
880     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
881
882     // i8 and i16 vectors are custom , because the source register and source
883     // source memory operand types are not the same width.  f32 vectors are
884     // custom since the immediate controlling the insert encodes additional
885     // information.
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
888     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
890
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
892     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
893     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
899     }
900   }
901
902   if (Subtarget->hasSSE42()) {
903     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
904   }
905
906   if (!UseSoftFloat && Subtarget->hasAVX()) {
907     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
908     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
909     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
910     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
911
912     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
913     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
914     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
915     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
916     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
917     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
918     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
919     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
920     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
921     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
922     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
923     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
924     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
925     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
926     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
927
928     // Operations to consider commented out -v16i16 v32i8
929     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
930     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
931     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
932     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
933     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
934     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
935     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
936     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
937     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
938     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
939     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
940     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
941     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
942     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
943
944     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
945     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
946     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
947     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
948
949     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
950     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
951     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
952     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
953     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
954
955     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
956     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
957     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
958     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
960     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
961
962 #if 0
963     // Not sure we want to do this since there are no 256-bit integer
964     // operations in AVX
965
966     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
967     // This includes 256-bit vectors
968     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
969       EVT VT = (MVT::SimpleValueType)i;
970
971       // Do not attempt to custom lower non-power-of-2 vectors
972       if (!isPowerOf2_32(VT.getVectorNumElements()))
973         continue;
974
975       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
976       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
977       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
978     }
979
980     if (Subtarget->is64Bit()) {
981       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
982       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
983     }
984 #endif
985
986 #if 0
987     // Not sure we want to do this since there are no 256-bit integer
988     // operations in AVX
989
990     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
991     // Including 256-bit vectors
992     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
993       EVT VT = (MVT::SimpleValueType)i;
994
995       if (!VT.is256BitVector()) {
996         continue;
997       }
998       setOperationAction(ISD::AND,    VT, Promote);
999       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1000       setOperationAction(ISD::OR,     VT, Promote);
1001       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1002       setOperationAction(ISD::XOR,    VT, Promote);
1003       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1004       setOperationAction(ISD::LOAD,   VT, Promote);
1005       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1006       setOperationAction(ISD::SELECT, VT, Promote);
1007       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1008     }
1009
1010     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1011 #endif
1012   }
1013
1014   // We want to custom lower some of our intrinsics.
1015   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1016
1017   // Add/Sub/Mul with overflow operations are custom lowered.
1018   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1019   setOperationAction(ISD::SADDO, MVT::i64, Custom);
1020   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1021   setOperationAction(ISD::UADDO, MVT::i64, Custom);
1022   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1023   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
1024   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1025   setOperationAction(ISD::USUBO, MVT::i64, Custom);
1026   setOperationAction(ISD::SMULO, MVT::i32, Custom);
1027   setOperationAction(ISD::SMULO, MVT::i64, Custom);
1028
1029   if (!Subtarget->is64Bit()) {
1030     // These libcalls are not available in 32-bit.
1031     setLibcallName(RTLIB::SHL_I128, 0);
1032     setLibcallName(RTLIB::SRL_I128, 0);
1033     setLibcallName(RTLIB::SRA_I128, 0);
1034   }
1035
1036   // We have target-specific dag combine patterns for the following nodes:
1037   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1038   setTargetDAGCombine(ISD::BUILD_VECTOR);
1039   setTargetDAGCombine(ISD::SELECT);
1040   setTargetDAGCombine(ISD::SHL);
1041   setTargetDAGCombine(ISD::SRA);
1042   setTargetDAGCombine(ISD::SRL);
1043   setTargetDAGCombine(ISD::OR);
1044   setTargetDAGCombine(ISD::STORE);
1045   setTargetDAGCombine(ISD::MEMBARRIER);
1046   setTargetDAGCombine(ISD::ZERO_EXTEND);
1047   if (Subtarget->is64Bit())
1048     setTargetDAGCombine(ISD::MUL);
1049
1050   computeRegisterProperties();
1051
1052   // FIXME: These should be based on subtarget info. Plus, the values should
1053   // be smaller when we are in optimizing for size mode.
1054   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1055   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1056   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1057   setPrefLoopAlignment(16);
1058   benefitFromCodePlacementOpt = true;
1059 }
1060
1061
1062 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1063   return MVT::i8;
1064 }
1065
1066
1067 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1068 /// the desired ByVal argument alignment.
1069 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1070   if (MaxAlign == 16)
1071     return;
1072   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1073     if (VTy->getBitWidth() == 128)
1074       MaxAlign = 16;
1075   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1076     unsigned EltAlign = 0;
1077     getMaxByValAlign(ATy->getElementType(), EltAlign);
1078     if (EltAlign > MaxAlign)
1079       MaxAlign = EltAlign;
1080   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1081     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1082       unsigned EltAlign = 0;
1083       getMaxByValAlign(STy->getElementType(i), EltAlign);
1084       if (EltAlign > MaxAlign)
1085         MaxAlign = EltAlign;
1086       if (MaxAlign == 16)
1087         break;
1088     }
1089   }
1090   return;
1091 }
1092
1093 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1094 /// function arguments in the caller parameter area. For X86, aggregates
1095 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1096 /// are at 4-byte boundaries.
1097 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1098   if (Subtarget->is64Bit()) {
1099     // Max of 8 and alignment of type.
1100     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1101     if (TyAlign > 8)
1102       return TyAlign;
1103     return 8;
1104   }
1105
1106   unsigned Align = 4;
1107   if (Subtarget->hasSSE1())
1108     getMaxByValAlign(Ty, Align);
1109   return Align;
1110 }
1111
1112 /// getOptimalMemOpType - Returns the target specific optimal type for load
1113 /// and store operations as a result of memset, memcpy, and memmove
1114 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1115 /// determining it.
1116 EVT
1117 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1118                                        bool isSrcConst, bool isSrcStr,
1119                                        SelectionDAG &DAG) const {
1120   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1121   // linux.  This is because the stack realignment code can't handle certain
1122   // cases like PR2962.  This should be removed when PR2962 is fixed.
1123   const Function *F = DAG.getMachineFunction().getFunction();
1124   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1125   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1126     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1127       return MVT::v4i32;
1128     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1129       return MVT::v4f32;
1130   }
1131   if (Subtarget->is64Bit() && Size >= 8)
1132     return MVT::i64;
1133   return MVT::i32;
1134 }
1135
1136 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1137 /// current function.  The returned value is a member of the
1138 /// MachineJumpTableInfo::JTEntryKind enum.
1139 unsigned X86TargetLowering::getJumpTableEncoding() const {
1140   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1141   // symbol.
1142   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1143       Subtarget->isPICStyleGOT())
1144     return MachineJumpTableInfo::EK_Custom32;
1145   
1146   // Otherwise, use the normal jump table encoding heuristics.
1147   return TargetLowering::getJumpTableEncoding();
1148 }
1149
1150 /// getPICBaseSymbol - Return the X86-32 PIC base.
1151 MCSymbol *
1152 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1153                                     MCContext &Ctx) const {
1154   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1155   return Ctx.GetOrCreateTemporarySymbol(Twine(MAI.getPrivateGlobalPrefix())+
1156                                         Twine(MF->getFunctionNumber())+"$pb");
1157 }
1158
1159
1160 const MCExpr *
1161 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1162                                              const MachineBasicBlock *MBB,
1163                                              unsigned uid,MCContext &Ctx) const{
1164   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1165          Subtarget->isPICStyleGOT());
1166   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1167   // entries.
1168   return X86MCTargetExpr::Create(MBB->getSymbol(),
1169                                  X86MCTargetExpr::GOTOFF, Ctx);
1170 }
1171
1172 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1173 /// jumptable.
1174 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1175                                                     SelectionDAG &DAG) const {
1176   if (!Subtarget->is64Bit())
1177     // This doesn't have DebugLoc associated with it, but is not really the
1178     // same as a Register.
1179     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1180                        getPointerTy());
1181   return Table;
1182 }
1183
1184 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1185 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1186 /// MCExpr.
1187 const MCExpr *X86TargetLowering::
1188 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1189                              MCContext &Ctx) const {
1190   // X86-64 uses RIP relative addressing based on the jump table label.
1191   if (Subtarget->isPICStyleRIPRel())
1192     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1193
1194   // Otherwise, the reference is relative to the PIC base.
1195   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1196 }
1197
1198 /// getFunctionAlignment - Return the Log2 alignment of this function.
1199 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1200   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1201 }
1202
1203 //===----------------------------------------------------------------------===//
1204 //               Return Value Calling Convention Implementation
1205 //===----------------------------------------------------------------------===//
1206
1207 #include "X86GenCallingConv.inc"
1208
1209 bool 
1210 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1211                         const SmallVectorImpl<EVT> &OutTys,
1212                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1213                         SelectionDAG &DAG) {
1214   SmallVector<CCValAssign, 16> RVLocs;
1215   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1216                  RVLocs, *DAG.getContext());
1217   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1218 }
1219
1220 SDValue
1221 X86TargetLowering::LowerReturn(SDValue Chain,
1222                                CallingConv::ID CallConv, bool isVarArg,
1223                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1224                                DebugLoc dl, SelectionDAG &DAG) {
1225
1226   SmallVector<CCValAssign, 16> RVLocs;
1227   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1228                  RVLocs, *DAG.getContext());
1229   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1230
1231   // Add the regs to the liveout set for the function.
1232   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1233   for (unsigned i = 0; i != RVLocs.size(); ++i)
1234     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1235       MRI.addLiveOut(RVLocs[i].getLocReg());
1236
1237   SDValue Flag;
1238
1239   SmallVector<SDValue, 6> RetOps;
1240   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1241   // Operand #1 = Bytes To Pop
1242   RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1243
1244   // Copy the result values into the output registers.
1245   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1246     CCValAssign &VA = RVLocs[i];
1247     assert(VA.isRegLoc() && "Can only return in registers!");
1248     SDValue ValToCopy = Outs[i].Val;
1249
1250     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1251     // the RET instruction and handled by the FP Stackifier.
1252     if (VA.getLocReg() == X86::ST0 ||
1253         VA.getLocReg() == X86::ST1) {
1254       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1255       // change the value to the FP stack register class.
1256       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1257         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1258       RetOps.push_back(ValToCopy);
1259       // Don't emit a copytoreg.
1260       continue;
1261     }
1262
1263     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1264     // which is returned in RAX / RDX.
1265     if (Subtarget->is64Bit()) {
1266       EVT ValVT = ValToCopy.getValueType();
1267       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1268         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1269         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1270           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1271       }
1272     }
1273
1274     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1275     Flag = Chain.getValue(1);
1276   }
1277
1278   // The x86-64 ABI for returning structs by value requires that we copy
1279   // the sret argument into %rax for the return. We saved the argument into
1280   // a virtual register in the entry block, so now we copy the value out
1281   // and into %rax.
1282   if (Subtarget->is64Bit() &&
1283       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1284     MachineFunction &MF = DAG.getMachineFunction();
1285     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1286     unsigned Reg = FuncInfo->getSRetReturnReg();
1287     if (!Reg) {
1288       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1289       FuncInfo->setSRetReturnReg(Reg);
1290     }
1291     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1292
1293     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1294     Flag = Chain.getValue(1);
1295
1296     // RAX now acts like a return value.
1297     MRI.addLiveOut(X86::RAX);
1298   }
1299
1300   RetOps[0] = Chain;  // Update chain.
1301
1302   // Add the flag if we have it.
1303   if (Flag.getNode())
1304     RetOps.push_back(Flag);
1305
1306   return DAG.getNode(X86ISD::RET_FLAG, dl,
1307                      MVT::Other, &RetOps[0], RetOps.size());
1308 }
1309
1310 /// LowerCallResult - Lower the result values of a call into the
1311 /// appropriate copies out of appropriate physical registers.
1312 ///
1313 SDValue
1314 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1315                                    CallingConv::ID CallConv, bool isVarArg,
1316                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1317                                    DebugLoc dl, SelectionDAG &DAG,
1318                                    SmallVectorImpl<SDValue> &InVals) {
1319
1320   // Assign locations to each value returned by this call.
1321   SmallVector<CCValAssign, 16> RVLocs;
1322   bool Is64Bit = Subtarget->is64Bit();
1323   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1324                  RVLocs, *DAG.getContext());
1325   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1326
1327   // Copy all of the result registers out of their specified physreg.
1328   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1329     CCValAssign &VA = RVLocs[i];
1330     EVT CopyVT = VA.getValVT();
1331
1332     // If this is x86-64, and we disabled SSE, we can't return FP values
1333     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1334         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1335       llvm_report_error("SSE register return with SSE disabled");
1336     }
1337
1338     // If this is a call to a function that returns an fp value on the floating
1339     // point stack, but where we prefer to use the value in xmm registers, copy
1340     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1341     if ((VA.getLocReg() == X86::ST0 ||
1342          VA.getLocReg() == X86::ST1) &&
1343         isScalarFPTypeInSSEReg(VA.getValVT())) {
1344       CopyVT = MVT::f80;
1345     }
1346
1347     SDValue Val;
1348     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1349       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1350       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1351         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1352                                    MVT::v2i64, InFlag).getValue(1);
1353         Val = Chain.getValue(0);
1354         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1355                           Val, DAG.getConstant(0, MVT::i64));
1356       } else {
1357         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1358                                    MVT::i64, InFlag).getValue(1);
1359         Val = Chain.getValue(0);
1360       }
1361       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1362     } else {
1363       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1364                                  CopyVT, InFlag).getValue(1);
1365       Val = Chain.getValue(0);
1366     }
1367     InFlag = Chain.getValue(2);
1368
1369     if (CopyVT != VA.getValVT()) {
1370       // Round the F80 the right size, which also moves to the appropriate xmm
1371       // register.
1372       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1373                         // This truncation won't change the value.
1374                         DAG.getIntPtrConstant(1));
1375     }
1376
1377     InVals.push_back(Val);
1378   }
1379
1380   return Chain;
1381 }
1382
1383
1384 //===----------------------------------------------------------------------===//
1385 //                C & StdCall & Fast Calling Convention implementation
1386 //===----------------------------------------------------------------------===//
1387 //  StdCall calling convention seems to be standard for many Windows' API
1388 //  routines and around. It differs from C calling convention just a little:
1389 //  callee should clean up the stack, not caller. Symbols should be also
1390 //  decorated in some fancy way :) It doesn't support any vector arguments.
1391 //  For info on fast calling convention see Fast Calling Convention (tail call)
1392 //  implementation LowerX86_32FastCCCallTo.
1393
1394 /// CallIsStructReturn - Determines whether a call uses struct return
1395 /// semantics.
1396 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1397   if (Outs.empty())
1398     return false;
1399
1400   return Outs[0].Flags.isSRet();
1401 }
1402
1403 /// ArgsAreStructReturn - Determines whether a function uses struct
1404 /// return semantics.
1405 static bool
1406 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1407   if (Ins.empty())
1408     return false;
1409
1410   return Ins[0].Flags.isSRet();
1411 }
1412
1413 /// IsCalleePop - Determines whether the callee is required to pop its
1414 /// own arguments. Callee pop is necessary to support tail calls.
1415 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1416   if (IsVarArg)
1417     return false;
1418
1419   switch (CallingConv) {
1420   default:
1421     return false;
1422   case CallingConv::X86_StdCall:
1423     return !Subtarget->is64Bit();
1424   case CallingConv::X86_FastCall:
1425     return !Subtarget->is64Bit();
1426   case CallingConv::Fast:
1427     return GuaranteedTailCallOpt;
1428   case CallingConv::GHC:
1429     return GuaranteedTailCallOpt;
1430   }
1431 }
1432
1433 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1434 /// given CallingConvention value.
1435 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1436   if (Subtarget->is64Bit()) {
1437     if (CC == CallingConv::GHC)
1438       return CC_X86_64_GHC;
1439     else if (Subtarget->isTargetWin64())
1440       return CC_X86_Win64_C;
1441     else
1442       return CC_X86_64_C;
1443   }
1444
1445   if (CC == CallingConv::X86_FastCall)
1446     return CC_X86_32_FastCall;
1447   else if (CC == CallingConv::Fast)
1448     return CC_X86_32_FastCC;
1449   else if (CC == CallingConv::GHC)
1450     return CC_X86_32_GHC;
1451   else
1452     return CC_X86_32_C;
1453 }
1454
1455 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1456 /// by "Src" to address "Dst" with size and alignment information specified by
1457 /// the specific parameter attribute. The copy will be passed as a byval
1458 /// function parameter.
1459 static SDValue
1460 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1461                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1462                           DebugLoc dl) {
1463   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1464   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1465                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1466 }
1467
1468 /// IsTailCallConvention - Return true if the calling convention is one that
1469 /// supports tail call optimization.
1470 static bool IsTailCallConvention(CallingConv::ID CC) {
1471   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1472 }
1473
1474 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1475 /// a tailcall target by changing its ABI.
1476 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1477   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1478 }
1479
1480 SDValue
1481 X86TargetLowering::LowerMemArgument(SDValue Chain,
1482                                     CallingConv::ID CallConv,
1483                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1484                                     DebugLoc dl, SelectionDAG &DAG,
1485                                     const CCValAssign &VA,
1486                                     MachineFrameInfo *MFI,
1487                                     unsigned i) {
1488   // Create the nodes corresponding to a load from this parameter slot.
1489   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1490   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1491   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1492   EVT ValVT;
1493
1494   // If value is passed by pointer we have address passed instead of the value
1495   // itself.
1496   if (VA.getLocInfo() == CCValAssign::Indirect)
1497     ValVT = VA.getLocVT();
1498   else
1499     ValVT = VA.getValVT();
1500
1501   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1502   // changed with more analysis.
1503   // In case of tail call optimization mark all arguments mutable. Since they
1504   // could be overwritten by lowering of arguments in case of a tail call.
1505   if (Flags.isByVal()) {
1506     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1507                                     VA.getLocMemOffset(), isImmutable, false);
1508     return DAG.getFrameIndex(FI, getPointerTy());
1509   } else {
1510     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1511                                     VA.getLocMemOffset(), isImmutable, false);
1512     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1513     return DAG.getLoad(ValVT, dl, Chain, FIN,
1514                        PseudoSourceValue::getFixedStack(FI), 0,
1515                        false, false, 0);
1516   }
1517 }
1518
1519 SDValue
1520 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1521                                         CallingConv::ID CallConv,
1522                                         bool isVarArg,
1523                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1524                                         DebugLoc dl,
1525                                         SelectionDAG &DAG,
1526                                         SmallVectorImpl<SDValue> &InVals) {
1527
1528   MachineFunction &MF = DAG.getMachineFunction();
1529   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1530
1531   const Function* Fn = MF.getFunction();
1532   if (Fn->hasExternalLinkage() &&
1533       Subtarget->isTargetCygMing() &&
1534       Fn->getName() == "main")
1535     FuncInfo->setForceFramePointer(true);
1536
1537   MachineFrameInfo *MFI = MF.getFrameInfo();
1538   bool Is64Bit = Subtarget->is64Bit();
1539   bool IsWin64 = Subtarget->isTargetWin64();
1540
1541   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1542          "Var args not supported with calling convention fastcc or ghc");
1543
1544   // Assign locations to all of the incoming arguments.
1545   SmallVector<CCValAssign, 16> ArgLocs;
1546   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1547                  ArgLocs, *DAG.getContext());
1548   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1549
1550   unsigned LastVal = ~0U;
1551   SDValue ArgValue;
1552   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1553     CCValAssign &VA = ArgLocs[i];
1554     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1555     // places.
1556     assert(VA.getValNo() != LastVal &&
1557            "Don't support value assigned to multiple locs yet");
1558     LastVal = VA.getValNo();
1559
1560     if (VA.isRegLoc()) {
1561       EVT RegVT = VA.getLocVT();
1562       TargetRegisterClass *RC = NULL;
1563       if (RegVT == MVT::i32)
1564         RC = X86::GR32RegisterClass;
1565       else if (Is64Bit && RegVT == MVT::i64)
1566         RC = X86::GR64RegisterClass;
1567       else if (RegVT == MVT::f32)
1568         RC = X86::FR32RegisterClass;
1569       else if (RegVT == MVT::f64)
1570         RC = X86::FR64RegisterClass;
1571       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1572         RC = X86::VR128RegisterClass;
1573       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1574         RC = X86::VR64RegisterClass;
1575       else
1576         llvm_unreachable("Unknown argument type!");
1577
1578       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1579       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1580
1581       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1582       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1583       // right size.
1584       if (VA.getLocInfo() == CCValAssign::SExt)
1585         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1586                                DAG.getValueType(VA.getValVT()));
1587       else if (VA.getLocInfo() == CCValAssign::ZExt)
1588         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1589                                DAG.getValueType(VA.getValVT()));
1590       else if (VA.getLocInfo() == CCValAssign::BCvt)
1591         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1592
1593       if (VA.isExtInLoc()) {
1594         // Handle MMX values passed in XMM regs.
1595         if (RegVT.isVector()) {
1596           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1597                                  ArgValue, DAG.getConstant(0, MVT::i64));
1598           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1599         } else
1600           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1601       }
1602     } else {
1603       assert(VA.isMemLoc());
1604       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1605     }
1606
1607     // If value is passed via pointer - do a load.
1608     if (VA.getLocInfo() == CCValAssign::Indirect)
1609       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1610                              false, false, 0);
1611
1612     InVals.push_back(ArgValue);
1613   }
1614
1615   // The x86-64 ABI for returning structs by value requires that we copy
1616   // the sret argument into %rax for the return. Save the argument into
1617   // a virtual register so that we can access it from the return points.
1618   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1619     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1620     unsigned Reg = FuncInfo->getSRetReturnReg();
1621     if (!Reg) {
1622       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1623       FuncInfo->setSRetReturnReg(Reg);
1624     }
1625     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1626     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1627   }
1628
1629   unsigned StackSize = CCInfo.getNextStackOffset();
1630   // Align stack specially for tail calls.
1631   if (FuncIsMadeTailCallSafe(CallConv))
1632     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1633
1634   // If the function takes variable number of arguments, make a frame index for
1635   // the start of the first vararg value... for expansion of llvm.va_start.
1636   if (isVarArg) {
1637     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1638       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1639     }
1640     if (Is64Bit) {
1641       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1642
1643       // FIXME: We should really autogenerate these arrays
1644       static const unsigned GPR64ArgRegsWin64[] = {
1645         X86::RCX, X86::RDX, X86::R8,  X86::R9
1646       };
1647       static const unsigned XMMArgRegsWin64[] = {
1648         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1649       };
1650       static const unsigned GPR64ArgRegs64Bit[] = {
1651         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1652       };
1653       static const unsigned XMMArgRegs64Bit[] = {
1654         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1655         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1656       };
1657       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1658
1659       if (IsWin64) {
1660         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1661         GPR64ArgRegs = GPR64ArgRegsWin64;
1662         XMMArgRegs = XMMArgRegsWin64;
1663       } else {
1664         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1665         GPR64ArgRegs = GPR64ArgRegs64Bit;
1666         XMMArgRegs = XMMArgRegs64Bit;
1667       }
1668       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1669                                                        TotalNumIntRegs);
1670       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1671                                                        TotalNumXMMRegs);
1672
1673       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1674       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1675              "SSE register cannot be used when SSE is disabled!");
1676       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1677              "SSE register cannot be used when SSE is disabled!");
1678       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1679         // Kernel mode asks for SSE to be disabled, so don't push them
1680         // on the stack.
1681         TotalNumXMMRegs = 0;
1682
1683       // For X86-64, if there are vararg parameters that are passed via
1684       // registers, then we must store them to their spots on the stack so they
1685       // may be loaded by deferencing the result of va_next.
1686       VarArgsGPOffset = NumIntRegs * 8;
1687       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1688       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1689                                                  TotalNumXMMRegs * 16, 16,
1690                                                  false);
1691
1692       // Store the integer parameter registers.
1693       SmallVector<SDValue, 8> MemOps;
1694       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1695       unsigned Offset = VarArgsGPOffset;
1696       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1697         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1698                                   DAG.getIntPtrConstant(Offset));
1699         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1700                                      X86::GR64RegisterClass);
1701         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1702         SDValue Store =
1703           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1704                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1705                        Offset, false, false, 0);
1706         MemOps.push_back(Store);
1707         Offset += 8;
1708       }
1709
1710       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1711         // Now store the XMM (fp + vector) parameter registers.
1712         SmallVector<SDValue, 11> SaveXMMOps;
1713         SaveXMMOps.push_back(Chain);
1714
1715         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1716         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1717         SaveXMMOps.push_back(ALVal);
1718
1719         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1720         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1721
1722         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1723           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1724                                        X86::VR128RegisterClass);
1725           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1726           SaveXMMOps.push_back(Val);
1727         }
1728         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1729                                      MVT::Other,
1730                                      &SaveXMMOps[0], SaveXMMOps.size()));
1731       }
1732
1733       if (!MemOps.empty())
1734         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1735                             &MemOps[0], MemOps.size());
1736     }
1737   }
1738
1739   // Some CCs need callee pop.
1740   if (IsCalleePop(isVarArg, CallConv)) {
1741     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1742   } else {
1743     BytesToPopOnReturn  = 0; // Callee pops nothing.
1744     // If this is an sret function, the return should pop the hidden pointer.
1745     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1746       BytesToPopOnReturn = 4;
1747   }
1748
1749   if (!Is64Bit) {
1750     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1751     if (CallConv == CallingConv::X86_FastCall)
1752       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1753   }
1754
1755   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1756
1757   return Chain;
1758 }
1759
1760 SDValue
1761 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1762                                     SDValue StackPtr, SDValue Arg,
1763                                     DebugLoc dl, SelectionDAG &DAG,
1764                                     const CCValAssign &VA,
1765                                     ISD::ArgFlagsTy Flags) {
1766   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1767   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1768   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1769   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1770   if (Flags.isByVal()) {
1771     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1772   }
1773   return DAG.getStore(Chain, dl, Arg, PtrOff,
1774                       PseudoSourceValue::getStack(), LocMemOffset,
1775                       false, false, 0);
1776 }
1777
1778 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1779 /// optimization is performed and it is required.
1780 SDValue
1781 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1782                                            SDValue &OutRetAddr, SDValue Chain,
1783                                            bool IsTailCall, bool Is64Bit,
1784                                            int FPDiff, DebugLoc dl) {
1785   // Adjust the Return address stack slot.
1786   EVT VT = getPointerTy();
1787   OutRetAddr = getReturnAddressFrameIndex(DAG);
1788
1789   // Load the "old" Return address.
1790   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1791   return SDValue(OutRetAddr.getNode(), 1);
1792 }
1793
1794 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1795 /// optimization is performed and it is required (FPDiff!=0).
1796 static SDValue
1797 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1798                          SDValue Chain, SDValue RetAddrFrIdx,
1799                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1800   // Store the return address to the appropriate stack slot.
1801   if (!FPDiff) return Chain;
1802   // Calculate the new stack slot for the return address.
1803   int SlotSize = Is64Bit ? 8 : 4;
1804   int NewReturnAddrFI =
1805     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1806   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1807   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1808   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1809                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1810                        false, false, 0);
1811   return Chain;
1812 }
1813
1814 SDValue
1815 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1816                              CallingConv::ID CallConv, bool isVarArg,
1817                              bool &isTailCall,
1818                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1819                              const SmallVectorImpl<ISD::InputArg> &Ins,
1820                              DebugLoc dl, SelectionDAG &DAG,
1821                              SmallVectorImpl<SDValue> &InVals) {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   bool Is64Bit        = Subtarget->is64Bit();
1824   bool IsStructRet    = CallIsStructReturn(Outs);
1825   bool IsSibcall      = false;
1826
1827   if (isTailCall) {
1828     // Check if it's really possible to do a tail call.
1829     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
1830                                                    Outs, Ins, DAG);
1831
1832     // Sibcalls are automatically detected tailcalls which do not require
1833     // ABI changes.
1834     if (!GuaranteedTailCallOpt && isTailCall)
1835       IsSibcall = true;
1836
1837     if (isTailCall)
1838       ++NumTailCalls;
1839   }
1840
1841   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1842          "Var args not supported with calling convention fastcc or ghc");
1843
1844   // Analyze operands of the call, assigning locations to each operand.
1845   SmallVector<CCValAssign, 16> ArgLocs;
1846   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1847                  ArgLocs, *DAG.getContext());
1848   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1849
1850   // Get a count of how many bytes are to be pushed on the stack.
1851   unsigned NumBytes = CCInfo.getNextStackOffset();
1852   if (IsSibcall)
1853     // This is a sibcall. The memory operands are available in caller's
1854     // own caller's stack.
1855     NumBytes = 0;
1856   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1857     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1858
1859   int FPDiff = 0;
1860   if (isTailCall && !IsSibcall) {
1861     // Lower arguments at fp - stackoffset + fpdiff.
1862     unsigned NumBytesCallerPushed =
1863       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1864     FPDiff = NumBytesCallerPushed - NumBytes;
1865
1866     // Set the delta of movement of the returnaddr stackslot.
1867     // But only set if delta is greater than previous delta.
1868     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1869       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1870   }
1871
1872   if (!IsSibcall)
1873     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1874
1875   SDValue RetAddrFrIdx;
1876   // Load return adress for tail calls.
1877   if (isTailCall && FPDiff)
1878     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1879                                     Is64Bit, FPDiff, dl);
1880
1881   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1882   SmallVector<SDValue, 8> MemOpChains;
1883   SDValue StackPtr;
1884
1885   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1886   // of tail call optimization arguments are handle later.
1887   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1888     CCValAssign &VA = ArgLocs[i];
1889     EVT RegVT = VA.getLocVT();
1890     SDValue Arg = Outs[i].Val;
1891     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1892     bool isByVal = Flags.isByVal();
1893
1894     // Promote the value if needed.
1895     switch (VA.getLocInfo()) {
1896     default: llvm_unreachable("Unknown loc info!");
1897     case CCValAssign::Full: break;
1898     case CCValAssign::SExt:
1899       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1900       break;
1901     case CCValAssign::ZExt:
1902       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1903       break;
1904     case CCValAssign::AExt:
1905       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1906         // Special case: passing MMX values in XMM registers.
1907         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1908         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1909         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1910       } else
1911         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1912       break;
1913     case CCValAssign::BCvt:
1914       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1915       break;
1916     case CCValAssign::Indirect: {
1917       // Store the argument.
1918       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1919       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1920       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1921                            PseudoSourceValue::getFixedStack(FI), 0,
1922                            false, false, 0);
1923       Arg = SpillSlot;
1924       break;
1925     }
1926     }
1927
1928     if (VA.isRegLoc()) {
1929       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1930     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1931       assert(VA.isMemLoc());
1932       if (StackPtr.getNode() == 0)
1933         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1934       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1935                                              dl, DAG, VA, Flags));
1936     }
1937   }
1938
1939   if (!MemOpChains.empty())
1940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1941                         &MemOpChains[0], MemOpChains.size());
1942
1943   // Build a sequence of copy-to-reg nodes chained together with token chain
1944   // and flag operands which copy the outgoing args into registers.
1945   SDValue InFlag;
1946   // Tail call byval lowering might overwrite argument registers so in case of
1947   // tail call optimization the copies to registers are lowered later.
1948   if (!isTailCall)
1949     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1950       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1951                                RegsToPass[i].second, InFlag);
1952       InFlag = Chain.getValue(1);
1953     }
1954
1955   if (Subtarget->isPICStyleGOT()) {
1956     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1957     // GOT pointer.
1958     if (!isTailCall) {
1959       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1960                                DAG.getNode(X86ISD::GlobalBaseReg,
1961                                            DebugLoc::getUnknownLoc(),
1962                                            getPointerTy()),
1963                                InFlag);
1964       InFlag = Chain.getValue(1);
1965     } else {
1966       // If we are tail calling and generating PIC/GOT style code load the
1967       // address of the callee into ECX. The value in ecx is used as target of
1968       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1969       // for tail calls on PIC/GOT architectures. Normally we would just put the
1970       // address of GOT into ebx and then call target@PLT. But for tail calls
1971       // ebx would be restored (since ebx is callee saved) before jumping to the
1972       // target@PLT.
1973
1974       // Note: The actual moving to ECX is done further down.
1975       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1976       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1977           !G->getGlobal()->hasProtectedVisibility())
1978         Callee = LowerGlobalAddress(Callee, DAG);
1979       else if (isa<ExternalSymbolSDNode>(Callee))
1980         Callee = LowerExternalSymbol(Callee, DAG);
1981     }
1982   }
1983
1984   if (Is64Bit && isVarArg) {
1985     // From AMD64 ABI document:
1986     // For calls that may call functions that use varargs or stdargs
1987     // (prototype-less calls or calls to functions containing ellipsis (...) in
1988     // the declaration) %al is used as hidden argument to specify the number
1989     // of SSE registers used. The contents of %al do not need to match exactly
1990     // the number of registers, but must be an ubound on the number of SSE
1991     // registers used and is in the range 0 - 8 inclusive.
1992
1993     // FIXME: Verify this on Win64
1994     // Count the number of XMM registers allocated.
1995     static const unsigned XMMArgRegs[] = {
1996       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1997       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1998     };
1999     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2000     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2001            && "SSE registers cannot be used when SSE is disabled");
2002
2003     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2004                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2005     InFlag = Chain.getValue(1);
2006   }
2007
2008
2009   // For tail calls lower the arguments to the 'real' stack slot.
2010   if (isTailCall) {
2011     // Force all the incoming stack arguments to be loaded from the stack
2012     // before any new outgoing arguments are stored to the stack, because the
2013     // outgoing stack slots may alias the incoming argument stack slots, and
2014     // the alias isn't otherwise explicit. This is slightly more conservative
2015     // than necessary, because it means that each store effectively depends
2016     // on every argument instead of just those arguments it would clobber.
2017     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2018
2019     SmallVector<SDValue, 8> MemOpChains2;
2020     SDValue FIN;
2021     int FI = 0;
2022     // Do not flag preceeding copytoreg stuff together with the following stuff.
2023     InFlag = SDValue();
2024     if (GuaranteedTailCallOpt) {
2025       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2026         CCValAssign &VA = ArgLocs[i];
2027         if (VA.isRegLoc())
2028           continue;
2029         assert(VA.isMemLoc());
2030         SDValue Arg = Outs[i].Val;
2031         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2032         // Create frame index.
2033         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2034         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2035         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2036         FIN = DAG.getFrameIndex(FI, getPointerTy());
2037
2038         if (Flags.isByVal()) {
2039           // Copy relative to framepointer.
2040           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2041           if (StackPtr.getNode() == 0)
2042             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2043                                           getPointerTy());
2044           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2045
2046           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2047                                                            ArgChain,
2048                                                            Flags, DAG, dl));
2049         } else {
2050           // Store relative to framepointer.
2051           MemOpChains2.push_back(
2052             DAG.getStore(ArgChain, dl, Arg, FIN,
2053                          PseudoSourceValue::getFixedStack(FI), 0,
2054                          false, false, 0));
2055         }
2056       }
2057     }
2058
2059     if (!MemOpChains2.empty())
2060       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2061                           &MemOpChains2[0], MemOpChains2.size());
2062
2063     // Copy arguments to their registers.
2064     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2065       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2066                                RegsToPass[i].second, InFlag);
2067       InFlag = Chain.getValue(1);
2068     }
2069     InFlag =SDValue();
2070
2071     // Store the return address to the appropriate stack slot.
2072     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2073                                      FPDiff, dl);
2074   }
2075
2076   bool WasGlobalOrExternal = false;
2077   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2078     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2079     // In the 64-bit large code model, we have to make all calls
2080     // through a register, since the call instruction's 32-bit
2081     // pc-relative offset may not be large enough to hold the whole
2082     // address.
2083   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2084     WasGlobalOrExternal = true;
2085     // If the callee is a GlobalAddress node (quite common, every direct call
2086     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2087     // it.
2088
2089     // We should use extra load for direct calls to dllimported functions in
2090     // non-JIT mode.
2091     GlobalValue *GV = G->getGlobal();
2092     if (!GV->hasDLLImportLinkage()) {
2093       unsigned char OpFlags = 0;
2094
2095       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2096       // external symbols most go through the PLT in PIC mode.  If the symbol
2097       // has hidden or protected visibility, or if it is static or local, then
2098       // we don't need to use the PLT - we can directly call it.
2099       if (Subtarget->isTargetELF() &&
2100           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2101           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2102         OpFlags = X86II::MO_PLT;
2103       } else if (Subtarget->isPICStyleStubAny() &&
2104                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2105                Subtarget->getDarwinVers() < 9) {
2106         // PC-relative references to external symbols should go through $stub,
2107         // unless we're building with the leopard linker or later, which
2108         // automatically synthesizes these stubs.
2109         OpFlags = X86II::MO_DARWIN_STUB;
2110       }
2111
2112       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2113                                           G->getOffset(), OpFlags);
2114     }
2115   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2116     WasGlobalOrExternal = true;
2117     unsigned char OpFlags = 0;
2118
2119     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2120     // symbols should go through the PLT.
2121     if (Subtarget->isTargetELF() &&
2122         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2123       OpFlags = X86II::MO_PLT;
2124     } else if (Subtarget->isPICStyleStubAny() &&
2125              Subtarget->getDarwinVers() < 9) {
2126       // PC-relative references to external symbols should go through $stub,
2127       // unless we're building with the leopard linker or later, which
2128       // automatically synthesizes these stubs.
2129       OpFlags = X86II::MO_DARWIN_STUB;
2130     }
2131
2132     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2133                                          OpFlags);
2134   }
2135
2136   if (isTailCall && !WasGlobalOrExternal) {
2137     // Force the address into a (call preserved) caller-saved register since
2138     // tailcall must happen after callee-saved registers are poped.
2139     // FIXME: Give it a special register class that contains caller-saved
2140     // register instead?
2141     unsigned TCReg = Is64Bit ? X86::R11 : X86::EAX;
2142     Chain = DAG.getCopyToReg(Chain,  dl,
2143                              DAG.getRegister(TCReg, getPointerTy()),
2144                              Callee,InFlag);
2145     Callee = DAG.getRegister(TCReg, getPointerTy());
2146   }
2147
2148   // Returns a chain & a flag for retval copy to use.
2149   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2150   SmallVector<SDValue, 8> Ops;
2151
2152   if (!IsSibcall && isTailCall) {
2153     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2154                            DAG.getIntPtrConstant(0, true), InFlag);
2155     InFlag = Chain.getValue(1);
2156   }
2157
2158   Ops.push_back(Chain);
2159   Ops.push_back(Callee);
2160
2161   if (isTailCall)
2162     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2163
2164   // Add argument registers to the end of the list so that they are known live
2165   // into the call.
2166   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2167     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2168                                   RegsToPass[i].second.getValueType()));
2169
2170   // Add an implicit use GOT pointer in EBX.
2171   if (!isTailCall && Subtarget->isPICStyleGOT())
2172     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2173
2174   // Add an implicit use of AL for x86 vararg functions.
2175   if (Is64Bit && isVarArg)
2176     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2177
2178   if (InFlag.getNode())
2179     Ops.push_back(InFlag);
2180
2181   if (isTailCall) {
2182     // If this is the first return lowered for this function, add the regs
2183     // to the liveout set for the function.
2184     if (MF.getRegInfo().liveout_empty()) {
2185       SmallVector<CCValAssign, 16> RVLocs;
2186       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2187                      *DAG.getContext());
2188       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2189       for (unsigned i = 0; i != RVLocs.size(); ++i)
2190         if (RVLocs[i].isRegLoc())
2191           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2192     }
2193
2194     assert(((Callee.getOpcode() == ISD::Register &&
2195                (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2196                 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2197               Callee.getOpcode() == ISD::TargetExternalSymbol ||
2198               Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2199            "Expecting a global address, external symbol, or scratch register");
2200
2201     return DAG.getNode(X86ISD::TC_RETURN, dl,
2202                        NodeTys, &Ops[0], Ops.size());
2203   }
2204
2205   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2206   InFlag = Chain.getValue(1);
2207
2208   // Create the CALLSEQ_END node.
2209   unsigned NumBytesForCalleeToPush;
2210   if (IsCalleePop(isVarArg, CallConv))
2211     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2212   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2213     // If this is a call to a struct-return function, the callee
2214     // pops the hidden struct pointer, so we have to push it back.
2215     // This is common for Darwin/X86, Linux & Mingw32 targets.
2216     NumBytesForCalleeToPush = 4;
2217   else
2218     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2219
2220   // Returns a flag for retval copy to use.
2221   if (!IsSibcall) {
2222     Chain = DAG.getCALLSEQ_END(Chain,
2223                                DAG.getIntPtrConstant(NumBytes, true),
2224                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2225                                                      true),
2226                                InFlag);
2227     InFlag = Chain.getValue(1);
2228   }
2229
2230   // Handle result values, copying them out of physregs into vregs that we
2231   // return.
2232   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2233                          Ins, dl, DAG, InVals);
2234 }
2235
2236
2237 //===----------------------------------------------------------------------===//
2238 //                Fast Calling Convention (tail call) implementation
2239 //===----------------------------------------------------------------------===//
2240
2241 //  Like std call, callee cleans arguments, convention except that ECX is
2242 //  reserved for storing the tail called function address. Only 2 registers are
2243 //  free for argument passing (inreg). Tail call optimization is performed
2244 //  provided:
2245 //                * tailcallopt is enabled
2246 //                * caller/callee are fastcc
2247 //  On X86_64 architecture with GOT-style position independent code only local
2248 //  (within module) calls are supported at the moment.
2249 //  To keep the stack aligned according to platform abi the function
2250 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2251 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2252 //  If a tail called function callee has more arguments than the caller the
2253 //  caller needs to make sure that there is room to move the RETADDR to. This is
2254 //  achieved by reserving an area the size of the argument delta right after the
2255 //  original REtADDR, but before the saved framepointer or the spilled registers
2256 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2257 //  stack layout:
2258 //    arg1
2259 //    arg2
2260 //    RETADDR
2261 //    [ new RETADDR
2262 //      move area ]
2263 //    (possible EBP)
2264 //    ESI
2265 //    EDI
2266 //    local1 ..
2267
2268 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2269 /// for a 16 byte align requirement.
2270 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2271                                                         SelectionDAG& DAG) {
2272   MachineFunction &MF = DAG.getMachineFunction();
2273   const TargetMachine &TM = MF.getTarget();
2274   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2275   unsigned StackAlignment = TFI.getStackAlignment();
2276   uint64_t AlignMask = StackAlignment - 1;
2277   int64_t Offset = StackSize;
2278   uint64_t SlotSize = TD->getPointerSize();
2279   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2280     // Number smaller than 12 so just add the difference.
2281     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2282   } else {
2283     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2284     Offset = ((~AlignMask) & Offset) + StackAlignment +
2285       (StackAlignment-SlotSize);
2286   }
2287   return Offset;
2288 }
2289
2290 /// MatchingStackOffset - Return true if the given stack call argument is
2291 /// already available in the same position (relatively) of the caller's
2292 /// incoming argument stack.
2293 static
2294 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2295                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2296                          const X86InstrInfo *TII) {
2297   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2298   int FI = INT_MAX;
2299   if (Arg.getOpcode() == ISD::CopyFromReg) {
2300     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2301     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2302       return false;
2303     MachineInstr *Def = MRI->getVRegDef(VR);
2304     if (!Def)
2305       return false;
2306     if (!Flags.isByVal()) {
2307       if (!TII->isLoadFromStackSlot(Def, FI))
2308         return false;
2309     } else {
2310       unsigned Opcode = Def->getOpcode();
2311       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2312           Def->getOperand(1).isFI()) {
2313         FI = Def->getOperand(1).getIndex();
2314         Bytes = Flags.getByValSize();
2315       } else
2316         return false;
2317     }
2318   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2319     if (Flags.isByVal())
2320       // ByVal argument is passed in as a pointer but it's now being
2321       // dereferenced. e.g.
2322       // define @foo(%struct.X* %A) {
2323       //   tail call @bar(%struct.X* byval %A)
2324       // }
2325       return false;
2326     SDValue Ptr = Ld->getBasePtr();
2327     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2328     if (!FINode)
2329       return false;
2330     FI = FINode->getIndex();
2331   } else
2332     return false;
2333
2334   assert(FI != INT_MAX);
2335   if (!MFI->isFixedObjectIndex(FI))
2336     return false;
2337   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2338 }
2339
2340 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2341 /// for tail call optimization. Targets which want to do tail call
2342 /// optimization should implement this function.
2343 bool
2344 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2345                                                      CallingConv::ID CalleeCC,
2346                                                      bool isVarArg,
2347                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2348                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2349                                                      SelectionDAG& DAG) const {
2350   if (!IsTailCallConvention(CalleeCC) &&
2351       CalleeCC != CallingConv::C)
2352     return false;
2353
2354   // If -tailcallopt is specified, make fastcc functions tail-callable.
2355   const Function *CallerF = DAG.getMachineFunction().getFunction();
2356   if (GuaranteedTailCallOpt) {
2357     if (IsTailCallConvention(CalleeCC) &&
2358         CallerF->getCallingConv() == CalleeCC)
2359       return true;
2360     return false;
2361   }
2362
2363   // Look for obvious safe cases to perform tail call optimization that does not
2364   // requite ABI changes. This is what gcc calls sibcall.
2365
2366   // Do not tail call optimize vararg calls for now.
2367   if (isVarArg)
2368     return false;
2369
2370   // If the callee takes no arguments then go on to check the results of the
2371   // call.
2372   if (!Outs.empty()) {
2373     // Check if stack adjustment is needed. For now, do not do this if any
2374     // argument is passed on the stack.
2375     SmallVector<CCValAssign, 16> ArgLocs;
2376     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2377                    ArgLocs, *DAG.getContext());
2378     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2379     if (CCInfo.getNextStackOffset()) {
2380       MachineFunction &MF = DAG.getMachineFunction();
2381       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2382         return false;
2383       if (Subtarget->isTargetWin64())
2384         // Win64 ABI has additional complications.
2385         return false;
2386
2387       // Check if the arguments are already laid out in the right way as
2388       // the caller's fixed stack objects.
2389       MachineFrameInfo *MFI = MF.getFrameInfo();
2390       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2391       const X86InstrInfo *TII =
2392         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2393       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2394         CCValAssign &VA = ArgLocs[i];
2395         EVT RegVT = VA.getLocVT();
2396         SDValue Arg = Outs[i].Val;
2397         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2398         if (VA.getLocInfo() == CCValAssign::Indirect)
2399           return false;
2400         if (!VA.isRegLoc()) {
2401           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2402                                    MFI, MRI, TII))
2403             return false;
2404         }
2405       }
2406     }
2407   }
2408
2409   return true;
2410 }
2411
2412 FastISel *
2413 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2414                             DwarfWriter *dw,
2415                             DenseMap<const Value *, unsigned> &vm,
2416                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2417                             DenseMap<const AllocaInst *, int> &am
2418 #ifndef NDEBUG
2419                           , SmallSet<Instruction*, 8> &cil
2420 #endif
2421                                   ) {
2422   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2423 #ifndef NDEBUG
2424                              , cil
2425 #endif
2426                              );
2427 }
2428
2429
2430 //===----------------------------------------------------------------------===//
2431 //                           Other Lowering Hooks
2432 //===----------------------------------------------------------------------===//
2433
2434
2435 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2436   MachineFunction &MF = DAG.getMachineFunction();
2437   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2438   int ReturnAddrIndex = FuncInfo->getRAIndex();
2439
2440   if (ReturnAddrIndex == 0) {
2441     // Set up a frame object for the return address.
2442     uint64_t SlotSize = TD->getPointerSize();
2443     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2444                                                            false, false);
2445     FuncInfo->setRAIndex(ReturnAddrIndex);
2446   }
2447
2448   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2449 }
2450
2451
2452 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2453                                        bool hasSymbolicDisplacement) {
2454   // Offset should fit into 32 bit immediate field.
2455   if (!isInt32(Offset))
2456     return false;
2457
2458   // If we don't have a symbolic displacement - we don't have any extra
2459   // restrictions.
2460   if (!hasSymbolicDisplacement)
2461     return true;
2462
2463   // FIXME: Some tweaks might be needed for medium code model.
2464   if (M != CodeModel::Small && M != CodeModel::Kernel)
2465     return false;
2466
2467   // For small code model we assume that latest object is 16MB before end of 31
2468   // bits boundary. We may also accept pretty large negative constants knowing
2469   // that all objects are in the positive half of address space.
2470   if (M == CodeModel::Small && Offset < 16*1024*1024)
2471     return true;
2472
2473   // For kernel code model we know that all object resist in the negative half
2474   // of 32bits address space. We may not accept negative offsets, since they may
2475   // be just off and we may accept pretty large positive ones.
2476   if (M == CodeModel::Kernel && Offset > 0)
2477     return true;
2478
2479   return false;
2480 }
2481
2482 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2483 /// specific condition code, returning the condition code and the LHS/RHS of the
2484 /// comparison to make.
2485 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2486                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2487   if (!isFP) {
2488     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2489       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2490         // X > -1   -> X == 0, jump !sign.
2491         RHS = DAG.getConstant(0, RHS.getValueType());
2492         return X86::COND_NS;
2493       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2494         // X < 0   -> X == 0, jump on sign.
2495         return X86::COND_S;
2496       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2497         // X < 1   -> X <= 0
2498         RHS = DAG.getConstant(0, RHS.getValueType());
2499         return X86::COND_LE;
2500       }
2501     }
2502
2503     switch (SetCCOpcode) {
2504     default: llvm_unreachable("Invalid integer condition!");
2505     case ISD::SETEQ:  return X86::COND_E;
2506     case ISD::SETGT:  return X86::COND_G;
2507     case ISD::SETGE:  return X86::COND_GE;
2508     case ISD::SETLT:  return X86::COND_L;
2509     case ISD::SETLE:  return X86::COND_LE;
2510     case ISD::SETNE:  return X86::COND_NE;
2511     case ISD::SETULT: return X86::COND_B;
2512     case ISD::SETUGT: return X86::COND_A;
2513     case ISD::SETULE: return X86::COND_BE;
2514     case ISD::SETUGE: return X86::COND_AE;
2515     }
2516   }
2517
2518   // First determine if it is required or is profitable to flip the operands.
2519
2520   // If LHS is a foldable load, but RHS is not, flip the condition.
2521   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2522       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2523     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2524     std::swap(LHS, RHS);
2525   }
2526
2527   switch (SetCCOpcode) {
2528   default: break;
2529   case ISD::SETOLT:
2530   case ISD::SETOLE:
2531   case ISD::SETUGT:
2532   case ISD::SETUGE:
2533     std::swap(LHS, RHS);
2534     break;
2535   }
2536
2537   // On a floating point condition, the flags are set as follows:
2538   // ZF  PF  CF   op
2539   //  0 | 0 | 0 | X > Y
2540   //  0 | 0 | 1 | X < Y
2541   //  1 | 0 | 0 | X == Y
2542   //  1 | 1 | 1 | unordered
2543   switch (SetCCOpcode) {
2544   default: llvm_unreachable("Condcode should be pre-legalized away");
2545   case ISD::SETUEQ:
2546   case ISD::SETEQ:   return X86::COND_E;
2547   case ISD::SETOLT:              // flipped
2548   case ISD::SETOGT:
2549   case ISD::SETGT:   return X86::COND_A;
2550   case ISD::SETOLE:              // flipped
2551   case ISD::SETOGE:
2552   case ISD::SETGE:   return X86::COND_AE;
2553   case ISD::SETUGT:              // flipped
2554   case ISD::SETULT:
2555   case ISD::SETLT:   return X86::COND_B;
2556   case ISD::SETUGE:              // flipped
2557   case ISD::SETULE:
2558   case ISD::SETLE:   return X86::COND_BE;
2559   case ISD::SETONE:
2560   case ISD::SETNE:   return X86::COND_NE;
2561   case ISD::SETUO:   return X86::COND_P;
2562   case ISD::SETO:    return X86::COND_NP;
2563   case ISD::SETOEQ:
2564   case ISD::SETUNE:  return X86::COND_INVALID;
2565   }
2566 }
2567
2568 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2569 /// code. Current x86 isa includes the following FP cmov instructions:
2570 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2571 static bool hasFPCMov(unsigned X86CC) {
2572   switch (X86CC) {
2573   default:
2574     return false;
2575   case X86::COND_B:
2576   case X86::COND_BE:
2577   case X86::COND_E:
2578   case X86::COND_P:
2579   case X86::COND_A:
2580   case X86::COND_AE:
2581   case X86::COND_NE:
2582   case X86::COND_NP:
2583     return true;
2584   }
2585 }
2586
2587 /// isFPImmLegal - Returns true if the target can instruction select the
2588 /// specified FP immediate natively. If false, the legalizer will
2589 /// materialize the FP immediate as a load from a constant pool.
2590 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2591   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2592     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2593       return true;
2594   }
2595   return false;
2596 }
2597
2598 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2599 /// the specified range (L, H].
2600 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2601   return (Val < 0) || (Val >= Low && Val < Hi);
2602 }
2603
2604 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2605 /// specified value.
2606 static bool isUndefOrEqual(int Val, int CmpVal) {
2607   if (Val < 0 || Val == CmpVal)
2608     return true;
2609   return false;
2610 }
2611
2612 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2613 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2614 /// the second operand.
2615 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2616   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2617     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2618   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2619     return (Mask[0] < 2 && Mask[1] < 2);
2620   return false;
2621 }
2622
2623 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2624   SmallVector<int, 8> M;
2625   N->getMask(M);
2626   return ::isPSHUFDMask(M, N->getValueType(0));
2627 }
2628
2629 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2630 /// is suitable for input to PSHUFHW.
2631 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2632   if (VT != MVT::v8i16)
2633     return false;
2634
2635   // Lower quadword copied in order or undef.
2636   for (int i = 0; i != 4; ++i)
2637     if (Mask[i] >= 0 && Mask[i] != i)
2638       return false;
2639
2640   // Upper quadword shuffled.
2641   for (int i = 4; i != 8; ++i)
2642     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2643       return false;
2644
2645   return true;
2646 }
2647
2648 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2649   SmallVector<int, 8> M;
2650   N->getMask(M);
2651   return ::isPSHUFHWMask(M, N->getValueType(0));
2652 }
2653
2654 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2655 /// is suitable for input to PSHUFLW.
2656 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2657   if (VT != MVT::v8i16)
2658     return false;
2659
2660   // Upper quadword copied in order.
2661   for (int i = 4; i != 8; ++i)
2662     if (Mask[i] >= 0 && Mask[i] != i)
2663       return false;
2664
2665   // Lower quadword shuffled.
2666   for (int i = 0; i != 4; ++i)
2667     if (Mask[i] >= 4)
2668       return false;
2669
2670   return true;
2671 }
2672
2673 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2674   SmallVector<int, 8> M;
2675   N->getMask(M);
2676   return ::isPSHUFLWMask(M, N->getValueType(0));
2677 }
2678
2679 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2680 /// is suitable for input to PALIGNR.
2681 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2682                           bool hasSSSE3) {
2683   int i, e = VT.getVectorNumElements();
2684   
2685   // Do not handle v2i64 / v2f64 shuffles with palignr.
2686   if (e < 4 || !hasSSSE3)
2687     return false;
2688   
2689   for (i = 0; i != e; ++i)
2690     if (Mask[i] >= 0)
2691       break;
2692   
2693   // All undef, not a palignr.
2694   if (i == e)
2695     return false;
2696
2697   // Determine if it's ok to perform a palignr with only the LHS, since we
2698   // don't have access to the actual shuffle elements to see if RHS is undef.
2699   bool Unary = Mask[i] < (int)e;
2700   bool NeedsUnary = false;
2701
2702   int s = Mask[i] - i;
2703   
2704   // Check the rest of the elements to see if they are consecutive.
2705   for (++i; i != e; ++i) {
2706     int m = Mask[i];
2707     if (m < 0) 
2708       continue;
2709     
2710     Unary = Unary && (m < (int)e);
2711     NeedsUnary = NeedsUnary || (m < s);
2712
2713     if (NeedsUnary && !Unary)
2714       return false;
2715     if (Unary && m != ((s+i) & (e-1)))
2716       return false;
2717     if (!Unary && m != (s+i))
2718       return false;
2719   }
2720   return true;
2721 }
2722
2723 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2724   SmallVector<int, 8> M;
2725   N->getMask(M);
2726   return ::isPALIGNRMask(M, N->getValueType(0), true);
2727 }
2728
2729 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2730 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2731 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2732   int NumElems = VT.getVectorNumElements();
2733   if (NumElems != 2 && NumElems != 4)
2734     return false;
2735
2736   int Half = NumElems / 2;
2737   for (int i = 0; i < Half; ++i)
2738     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2739       return false;
2740   for (int i = Half; i < NumElems; ++i)
2741     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2742       return false;
2743
2744   return true;
2745 }
2746
2747 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2748   SmallVector<int, 8> M;
2749   N->getMask(M);
2750   return ::isSHUFPMask(M, N->getValueType(0));
2751 }
2752
2753 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2754 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2755 /// half elements to come from vector 1 (which would equal the dest.) and
2756 /// the upper half to come from vector 2.
2757 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2758   int NumElems = VT.getVectorNumElements();
2759
2760   if (NumElems != 2 && NumElems != 4)
2761     return false;
2762
2763   int Half = NumElems / 2;
2764   for (int i = 0; i < Half; ++i)
2765     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2766       return false;
2767   for (int i = Half; i < NumElems; ++i)
2768     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2769       return false;
2770   return true;
2771 }
2772
2773 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2774   SmallVector<int, 8> M;
2775   N->getMask(M);
2776   return isCommutedSHUFPMask(M, N->getValueType(0));
2777 }
2778
2779 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2780 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2781 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2782   if (N->getValueType(0).getVectorNumElements() != 4)
2783     return false;
2784
2785   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2786   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2787          isUndefOrEqual(N->getMaskElt(1), 7) &&
2788          isUndefOrEqual(N->getMaskElt(2), 2) &&
2789          isUndefOrEqual(N->getMaskElt(3), 3);
2790 }
2791
2792 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2793 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2794 /// <2, 3, 2, 3>
2795 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2796   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2797   
2798   if (NumElems != 4)
2799     return false;
2800   
2801   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2802   isUndefOrEqual(N->getMaskElt(1), 3) &&
2803   isUndefOrEqual(N->getMaskElt(2), 2) &&
2804   isUndefOrEqual(N->getMaskElt(3), 3);
2805 }
2806
2807 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2808 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2809 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2810   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2811
2812   if (NumElems != 2 && NumElems != 4)
2813     return false;
2814
2815   for (unsigned i = 0; i < NumElems/2; ++i)
2816     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2817       return false;
2818
2819   for (unsigned i = NumElems/2; i < NumElems; ++i)
2820     if (!isUndefOrEqual(N->getMaskElt(i), i))
2821       return false;
2822
2823   return true;
2824 }
2825
2826 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2827 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2828 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2829   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2830
2831   if (NumElems != 2 && NumElems != 4)
2832     return false;
2833
2834   for (unsigned i = 0; i < NumElems/2; ++i)
2835     if (!isUndefOrEqual(N->getMaskElt(i), i))
2836       return false;
2837
2838   for (unsigned i = 0; i < NumElems/2; ++i)
2839     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2840       return false;
2841
2842   return true;
2843 }
2844
2845 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2846 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2847 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2848                          bool V2IsSplat = false) {
2849   int NumElts = VT.getVectorNumElements();
2850   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2851     return false;
2852
2853   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2854     int BitI  = Mask[i];
2855     int BitI1 = Mask[i+1];
2856     if (!isUndefOrEqual(BitI, j))
2857       return false;
2858     if (V2IsSplat) {
2859       if (!isUndefOrEqual(BitI1, NumElts))
2860         return false;
2861     } else {
2862       if (!isUndefOrEqual(BitI1, j + NumElts))
2863         return false;
2864     }
2865   }
2866   return true;
2867 }
2868
2869 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2870   SmallVector<int, 8> M;
2871   N->getMask(M);
2872   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2873 }
2874
2875 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2876 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2877 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2878                          bool V2IsSplat = false) {
2879   int NumElts = VT.getVectorNumElements();
2880   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2881     return false;
2882
2883   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2884     int BitI  = Mask[i];
2885     int BitI1 = Mask[i+1];
2886     if (!isUndefOrEqual(BitI, j + NumElts/2))
2887       return false;
2888     if (V2IsSplat) {
2889       if (isUndefOrEqual(BitI1, NumElts))
2890         return false;
2891     } else {
2892       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2893         return false;
2894     }
2895   }
2896   return true;
2897 }
2898
2899 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2900   SmallVector<int, 8> M;
2901   N->getMask(M);
2902   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2903 }
2904
2905 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2906 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2907 /// <0, 0, 1, 1>
2908 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2909   int NumElems = VT.getVectorNumElements();
2910   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2911     return false;
2912
2913   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2914     int BitI  = Mask[i];
2915     int BitI1 = Mask[i+1];
2916     if (!isUndefOrEqual(BitI, j))
2917       return false;
2918     if (!isUndefOrEqual(BitI1, j))
2919       return false;
2920   }
2921   return true;
2922 }
2923
2924 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2925   SmallVector<int, 8> M;
2926   N->getMask(M);
2927   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2928 }
2929
2930 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2931 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2932 /// <2, 2, 3, 3>
2933 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2934   int NumElems = VT.getVectorNumElements();
2935   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2936     return false;
2937
2938   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2939     int BitI  = Mask[i];
2940     int BitI1 = Mask[i+1];
2941     if (!isUndefOrEqual(BitI, j))
2942       return false;
2943     if (!isUndefOrEqual(BitI1, j))
2944       return false;
2945   }
2946   return true;
2947 }
2948
2949 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2950   SmallVector<int, 8> M;
2951   N->getMask(M);
2952   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2953 }
2954
2955 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2956 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2957 /// MOVSD, and MOVD, i.e. setting the lowest element.
2958 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2959   if (VT.getVectorElementType().getSizeInBits() < 32)
2960     return false;
2961
2962   int NumElts = VT.getVectorNumElements();
2963
2964   if (!isUndefOrEqual(Mask[0], NumElts))
2965     return false;
2966
2967   for (int i = 1; i < NumElts; ++i)
2968     if (!isUndefOrEqual(Mask[i], i))
2969       return false;
2970
2971   return true;
2972 }
2973
2974 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2975   SmallVector<int, 8> M;
2976   N->getMask(M);
2977   return ::isMOVLMask(M, N->getValueType(0));
2978 }
2979
2980 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2981 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2982 /// element of vector 2 and the other elements to come from vector 1 in order.
2983 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2984                                bool V2IsSplat = false, bool V2IsUndef = false) {
2985   int NumOps = VT.getVectorNumElements();
2986   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2987     return false;
2988
2989   if (!isUndefOrEqual(Mask[0], 0))
2990     return false;
2991
2992   for (int i = 1; i < NumOps; ++i)
2993     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2994           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2995           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2996       return false;
2997
2998   return true;
2999 }
3000
3001 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3002                            bool V2IsUndef = false) {
3003   SmallVector<int, 8> M;
3004   N->getMask(M);
3005   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3006 }
3007
3008 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3009 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3010 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3011   if (N->getValueType(0).getVectorNumElements() != 4)
3012     return false;
3013
3014   // Expect 1, 1, 3, 3
3015   for (unsigned i = 0; i < 2; ++i) {
3016     int Elt = N->getMaskElt(i);
3017     if (Elt >= 0 && Elt != 1)
3018       return false;
3019   }
3020
3021   bool HasHi = false;
3022   for (unsigned i = 2; i < 4; ++i) {
3023     int Elt = N->getMaskElt(i);
3024     if (Elt >= 0 && Elt != 3)
3025       return false;
3026     if (Elt == 3)
3027       HasHi = true;
3028   }
3029   // Don't use movshdup if it can be done with a shufps.
3030   // FIXME: verify that matching u, u, 3, 3 is what we want.
3031   return HasHi;
3032 }
3033
3034 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3035 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3036 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3037   if (N->getValueType(0).getVectorNumElements() != 4)
3038     return false;
3039
3040   // Expect 0, 0, 2, 2
3041   for (unsigned i = 0; i < 2; ++i)
3042     if (N->getMaskElt(i) > 0)
3043       return false;
3044
3045   bool HasHi = false;
3046   for (unsigned i = 2; i < 4; ++i) {
3047     int Elt = N->getMaskElt(i);
3048     if (Elt >= 0 && Elt != 2)
3049       return false;
3050     if (Elt == 2)
3051       HasHi = true;
3052   }
3053   // Don't use movsldup if it can be done with a shufps.
3054   return HasHi;
3055 }
3056
3057 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3058 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3059 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3060   int e = N->getValueType(0).getVectorNumElements() / 2;
3061
3062   for (int i = 0; i < e; ++i)
3063     if (!isUndefOrEqual(N->getMaskElt(i), i))
3064       return false;
3065   for (int i = 0; i < e; ++i)
3066     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3067       return false;
3068   return true;
3069 }
3070
3071 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3072 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3073 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3074   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3075   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3076
3077   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3078   unsigned Mask = 0;
3079   for (int i = 0; i < NumOperands; ++i) {
3080     int Val = SVOp->getMaskElt(NumOperands-i-1);
3081     if (Val < 0) Val = 0;
3082     if (Val >= NumOperands) Val -= NumOperands;
3083     Mask |= Val;
3084     if (i != NumOperands - 1)
3085       Mask <<= Shift;
3086   }
3087   return Mask;
3088 }
3089
3090 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3091 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3092 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3093   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3094   unsigned Mask = 0;
3095   // 8 nodes, but we only care about the last 4.
3096   for (unsigned i = 7; i >= 4; --i) {
3097     int Val = SVOp->getMaskElt(i);
3098     if (Val >= 0)
3099       Mask |= (Val - 4);
3100     if (i != 4)
3101       Mask <<= 2;
3102   }
3103   return Mask;
3104 }
3105
3106 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3107 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3108 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3110   unsigned Mask = 0;
3111   // 8 nodes, but we only care about the first 4.
3112   for (int i = 3; i >= 0; --i) {
3113     int Val = SVOp->getMaskElt(i);
3114     if (Val >= 0)
3115       Mask |= Val;
3116     if (i != 0)
3117       Mask <<= 2;
3118   }
3119   return Mask;
3120 }
3121
3122 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3123 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3124 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3126   EVT VVT = N->getValueType(0);
3127   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3128   int Val = 0;
3129
3130   unsigned i, e;
3131   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3132     Val = SVOp->getMaskElt(i);
3133     if (Val >= 0)
3134       break;
3135   }
3136   return (Val - i) * EltSize;
3137 }
3138
3139 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3140 /// constant +0.0.
3141 bool X86::isZeroNode(SDValue Elt) {
3142   return ((isa<ConstantSDNode>(Elt) &&
3143            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3144           (isa<ConstantFPSDNode>(Elt) &&
3145            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3146 }
3147
3148 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3149 /// their permute mask.
3150 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3151                                     SelectionDAG &DAG) {
3152   EVT VT = SVOp->getValueType(0);
3153   unsigned NumElems = VT.getVectorNumElements();
3154   SmallVector<int, 8> MaskVec;
3155
3156   for (unsigned i = 0; i != NumElems; ++i) {
3157     int idx = SVOp->getMaskElt(i);
3158     if (idx < 0)
3159       MaskVec.push_back(idx);
3160     else if (idx < (int)NumElems)
3161       MaskVec.push_back(idx + NumElems);
3162     else
3163       MaskVec.push_back(idx - NumElems);
3164   }
3165   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3166                               SVOp->getOperand(0), &MaskVec[0]);
3167 }
3168
3169 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3170 /// the two vector operands have swapped position.
3171 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3172   unsigned NumElems = VT.getVectorNumElements();
3173   for (unsigned i = 0; i != NumElems; ++i) {
3174     int idx = Mask[i];
3175     if (idx < 0)
3176       continue;
3177     else if (idx < (int)NumElems)
3178       Mask[i] = idx + NumElems;
3179     else
3180       Mask[i] = idx - NumElems;
3181   }
3182 }
3183
3184 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3185 /// match movhlps. The lower half elements should come from upper half of
3186 /// V1 (and in order), and the upper half elements should come from the upper
3187 /// half of V2 (and in order).
3188 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3189   if (Op->getValueType(0).getVectorNumElements() != 4)
3190     return false;
3191   for (unsigned i = 0, e = 2; i != e; ++i)
3192     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3193       return false;
3194   for (unsigned i = 2; i != 4; ++i)
3195     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3196       return false;
3197   return true;
3198 }
3199
3200 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3201 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3202 /// required.
3203 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3204   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3205     return false;
3206   N = N->getOperand(0).getNode();
3207   if (!ISD::isNON_EXTLoad(N))
3208     return false;
3209   if (LD)
3210     *LD = cast<LoadSDNode>(N);
3211   return true;
3212 }
3213
3214 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3215 /// match movlp{s|d}. The lower half elements should come from lower half of
3216 /// V1 (and in order), and the upper half elements should come from the upper
3217 /// half of V2 (and in order). And since V1 will become the source of the
3218 /// MOVLP, it must be either a vector load or a scalar load to vector.
3219 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3220                                ShuffleVectorSDNode *Op) {
3221   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3222     return false;
3223   // Is V2 is a vector load, don't do this transformation. We will try to use
3224   // load folding shufps op.
3225   if (ISD::isNON_EXTLoad(V2))
3226     return false;
3227
3228   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3229
3230   if (NumElems != 2 && NumElems != 4)
3231     return false;
3232   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3233     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3234       return false;
3235   for (unsigned i = NumElems/2; i != NumElems; ++i)
3236     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3237       return false;
3238   return true;
3239 }
3240
3241 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3242 /// all the same.
3243 static bool isSplatVector(SDNode *N) {
3244   if (N->getOpcode() != ISD::BUILD_VECTOR)
3245     return false;
3246
3247   SDValue SplatValue = N->getOperand(0);
3248   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3249     if (N->getOperand(i) != SplatValue)
3250       return false;
3251   return true;
3252 }
3253
3254 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3255 /// to an zero vector.
3256 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3257 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3258   SDValue V1 = N->getOperand(0);
3259   SDValue V2 = N->getOperand(1);
3260   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3261   for (unsigned i = 0; i != NumElems; ++i) {
3262     int Idx = N->getMaskElt(i);
3263     if (Idx >= (int)NumElems) {
3264       unsigned Opc = V2.getOpcode();
3265       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3266         continue;
3267       if (Opc != ISD::BUILD_VECTOR ||
3268           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3269         return false;
3270     } else if (Idx >= 0) {
3271       unsigned Opc = V1.getOpcode();
3272       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3273         continue;
3274       if (Opc != ISD::BUILD_VECTOR ||
3275           !X86::isZeroNode(V1.getOperand(Idx)))
3276         return false;
3277     }
3278   }
3279   return true;
3280 }
3281
3282 /// getZeroVector - Returns a vector of specified type with all zero elements.
3283 ///
3284 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3285                              DebugLoc dl) {
3286   assert(VT.isVector() && "Expected a vector type");
3287
3288   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3289   // type.  This ensures they get CSE'd.
3290   SDValue Vec;
3291   if (VT.getSizeInBits() == 64) { // MMX
3292     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3293     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3294   } else if (HasSSE2) {  // SSE2
3295     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3296     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3297   } else { // SSE1
3298     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3299     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3300   }
3301   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3302 }
3303
3304 /// getOnesVector - Returns a vector of specified type with all bits set.
3305 ///
3306 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3307   assert(VT.isVector() && "Expected a vector type");
3308
3309   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3310   // type.  This ensures they get CSE'd.
3311   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3312   SDValue Vec;
3313   if (VT.getSizeInBits() == 64)  // MMX
3314     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3315   else                                              // SSE
3316     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3317   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3318 }
3319
3320
3321 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3322 /// that point to V2 points to its first element.
3323 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3324   EVT VT = SVOp->getValueType(0);
3325   unsigned NumElems = VT.getVectorNumElements();
3326
3327   bool Changed = false;
3328   SmallVector<int, 8> MaskVec;
3329   SVOp->getMask(MaskVec);
3330
3331   for (unsigned i = 0; i != NumElems; ++i) {
3332     if (MaskVec[i] > (int)NumElems) {
3333       MaskVec[i] = NumElems;
3334       Changed = true;
3335     }
3336   }
3337   if (Changed)
3338     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3339                                 SVOp->getOperand(1), &MaskVec[0]);
3340   return SDValue(SVOp, 0);
3341 }
3342
3343 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3344 /// operation of specified width.
3345 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3346                        SDValue V2) {
3347   unsigned NumElems = VT.getVectorNumElements();
3348   SmallVector<int, 8> Mask;
3349   Mask.push_back(NumElems);
3350   for (unsigned i = 1; i != NumElems; ++i)
3351     Mask.push_back(i);
3352   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3353 }
3354
3355 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3356 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3357                           SDValue V2) {
3358   unsigned NumElems = VT.getVectorNumElements();
3359   SmallVector<int, 8> Mask;
3360   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3361     Mask.push_back(i);
3362     Mask.push_back(i + NumElems);
3363   }
3364   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3365 }
3366
3367 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3368 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3369                           SDValue V2) {
3370   unsigned NumElems = VT.getVectorNumElements();
3371   unsigned Half = NumElems/2;
3372   SmallVector<int, 8> Mask;
3373   for (unsigned i = 0; i != Half; ++i) {
3374     Mask.push_back(i + Half);
3375     Mask.push_back(i + NumElems + Half);
3376   }
3377   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3378 }
3379
3380 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3381 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3382                             bool HasSSE2) {
3383   if (SV->getValueType(0).getVectorNumElements() <= 4)
3384     return SDValue(SV, 0);
3385
3386   EVT PVT = MVT::v4f32;
3387   EVT VT = SV->getValueType(0);
3388   DebugLoc dl = SV->getDebugLoc();
3389   SDValue V1 = SV->getOperand(0);
3390   int NumElems = VT.getVectorNumElements();
3391   int EltNo = SV->getSplatIndex();
3392
3393   // unpack elements to the correct location
3394   while (NumElems > 4) {
3395     if (EltNo < NumElems/2) {
3396       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3397     } else {
3398       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3399       EltNo -= NumElems/2;
3400     }
3401     NumElems >>= 1;
3402   }
3403
3404   // Perform the splat.
3405   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3406   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3407   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3408   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3409 }
3410
3411 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3412 /// vector of zero or undef vector.  This produces a shuffle where the low
3413 /// element of V2 is swizzled into the zero/undef vector, landing at element
3414 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3415 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3416                                              bool isZero, bool HasSSE2,
3417                                              SelectionDAG &DAG) {
3418   EVT VT = V2.getValueType();
3419   SDValue V1 = isZero
3420     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3421   unsigned NumElems = VT.getVectorNumElements();
3422   SmallVector<int, 16> MaskVec;
3423   for (unsigned i = 0; i != NumElems; ++i)
3424     // If this is the insertion idx, put the low elt of V2 here.
3425     MaskVec.push_back(i == Idx ? NumElems : i);
3426   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3427 }
3428
3429 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3430 /// a shuffle that is zero.
3431 static
3432 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3433                                   bool Low, SelectionDAG &DAG) {
3434   unsigned NumZeros = 0;
3435   for (int i = 0; i < NumElems; ++i) {
3436     unsigned Index = Low ? i : NumElems-i-1;
3437     int Idx = SVOp->getMaskElt(Index);
3438     if (Idx < 0) {
3439       ++NumZeros;
3440       continue;
3441     }
3442     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3443     if (Elt.getNode() && X86::isZeroNode(Elt))
3444       ++NumZeros;
3445     else
3446       break;
3447   }
3448   return NumZeros;
3449 }
3450
3451 /// isVectorShift - Returns true if the shuffle can be implemented as a
3452 /// logical left or right shift of a vector.
3453 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3454 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3455                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3456   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3457
3458   isLeft = true;
3459   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3460   if (!NumZeros) {
3461     isLeft = false;
3462     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3463     if (!NumZeros)
3464       return false;
3465   }
3466   bool SeenV1 = false;
3467   bool SeenV2 = false;
3468   for (int i = NumZeros; i < NumElems; ++i) {
3469     int Val = isLeft ? (i - NumZeros) : i;
3470     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3471     if (Idx < 0)
3472       continue;
3473     if (Idx < NumElems)
3474       SeenV1 = true;
3475     else {
3476       Idx -= NumElems;
3477       SeenV2 = true;
3478     }
3479     if (Idx != Val)
3480       return false;
3481   }
3482   if (SeenV1 && SeenV2)
3483     return false;
3484
3485   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3486   ShAmt = NumZeros;
3487   return true;
3488 }
3489
3490
3491 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3492 ///
3493 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3494                                        unsigned NumNonZero, unsigned NumZero,
3495                                        SelectionDAG &DAG, TargetLowering &TLI) {
3496   if (NumNonZero > 8)
3497     return SDValue();
3498
3499   DebugLoc dl = Op.getDebugLoc();
3500   SDValue V(0, 0);
3501   bool First = true;
3502   for (unsigned i = 0; i < 16; ++i) {
3503     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3504     if (ThisIsNonZero && First) {
3505       if (NumZero)
3506         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3507       else
3508         V = DAG.getUNDEF(MVT::v8i16);
3509       First = false;
3510     }
3511
3512     if ((i & 1) != 0) {
3513       SDValue ThisElt(0, 0), LastElt(0, 0);
3514       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3515       if (LastIsNonZero) {
3516         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3517                               MVT::i16, Op.getOperand(i-1));
3518       }
3519       if (ThisIsNonZero) {
3520         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3521         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3522                               ThisElt, DAG.getConstant(8, MVT::i8));
3523         if (LastIsNonZero)
3524           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3525       } else
3526         ThisElt = LastElt;
3527
3528       if (ThisElt.getNode())
3529         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3530                         DAG.getIntPtrConstant(i/2));
3531     }
3532   }
3533
3534   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3535 }
3536
3537 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3538 ///
3539 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3540                                        unsigned NumNonZero, unsigned NumZero,
3541                                        SelectionDAG &DAG, TargetLowering &TLI) {
3542   if (NumNonZero > 4)
3543     return SDValue();
3544
3545   DebugLoc dl = Op.getDebugLoc();
3546   SDValue V(0, 0);
3547   bool First = true;
3548   for (unsigned i = 0; i < 8; ++i) {
3549     bool isNonZero = (NonZeros & (1 << i)) != 0;
3550     if (isNonZero) {
3551       if (First) {
3552         if (NumZero)
3553           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3554         else
3555           V = DAG.getUNDEF(MVT::v8i16);
3556         First = false;
3557       }
3558       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3559                       MVT::v8i16, V, Op.getOperand(i),
3560                       DAG.getIntPtrConstant(i));
3561     }
3562   }
3563
3564   return V;
3565 }
3566
3567 /// getVShift - Return a vector logical shift node.
3568 ///
3569 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3570                          unsigned NumBits, SelectionDAG &DAG,
3571                          const TargetLowering &TLI, DebugLoc dl) {
3572   bool isMMX = VT.getSizeInBits() == 64;
3573   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3574   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3575   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3576   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3577                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3578                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3579 }
3580
3581 SDValue
3582 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3583                                           SelectionDAG &DAG) {
3584   
3585   // Check if the scalar load can be widened into a vector load. And if
3586   // the address is "base + cst" see if the cst can be "absorbed" into
3587   // the shuffle mask.
3588   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3589     SDValue Ptr = LD->getBasePtr();
3590     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3591       return SDValue();
3592     EVT PVT = LD->getValueType(0);
3593     if (PVT != MVT::i32 && PVT != MVT::f32)
3594       return SDValue();
3595
3596     int FI = -1;
3597     int64_t Offset = 0;
3598     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3599       FI = FINode->getIndex();
3600       Offset = 0;
3601     } else if (Ptr.getOpcode() == ISD::ADD &&
3602                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3603                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3604       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3605       Offset = Ptr.getConstantOperandVal(1);
3606       Ptr = Ptr.getOperand(0);
3607     } else {
3608       return SDValue();
3609     }
3610
3611     SDValue Chain = LD->getChain();
3612     // Make sure the stack object alignment is at least 16.
3613     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3614     if (DAG.InferPtrAlignment(Ptr) < 16) {
3615       if (MFI->isFixedObjectIndex(FI)) {
3616         // Can't change the alignment. FIXME: It's possible to compute
3617         // the exact stack offset and reference FI + adjust offset instead.
3618         // If someone *really* cares about this. That's the way to implement it.
3619         return SDValue();
3620       } else {
3621         MFI->setObjectAlignment(FI, 16);
3622       }
3623     }
3624
3625     // (Offset % 16) must be multiple of 4. Then address is then
3626     // Ptr + (Offset & ~15).
3627     if (Offset < 0)
3628       return SDValue();
3629     if ((Offset % 16) & 3)
3630       return SDValue();
3631     int64_t StartOffset = Offset & ~15;
3632     if (StartOffset)
3633       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3634                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3635
3636     int EltNo = (Offset - StartOffset) >> 2;
3637     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3638     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3639     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3640                              false, false, 0);
3641     // Canonicalize it to a v4i32 shuffle.
3642     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3643     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3644                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3645                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3646   }
3647
3648   return SDValue();
3649 }
3650
3651 SDValue
3652 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3653   DebugLoc dl = Op.getDebugLoc();
3654   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3655   if (ISD::isBuildVectorAllZeros(Op.getNode())
3656       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3657     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3658     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3659     // eliminated on x86-32 hosts.
3660     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3661       return Op;
3662
3663     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3664       return getOnesVector(Op.getValueType(), DAG, dl);
3665     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3666   }
3667
3668   EVT VT = Op.getValueType();
3669   EVT ExtVT = VT.getVectorElementType();
3670   unsigned EVTBits = ExtVT.getSizeInBits();
3671
3672   unsigned NumElems = Op.getNumOperands();
3673   unsigned NumZero  = 0;
3674   unsigned NumNonZero = 0;
3675   unsigned NonZeros = 0;
3676   bool IsAllConstants = true;
3677   SmallSet<SDValue, 8> Values;
3678   for (unsigned i = 0; i < NumElems; ++i) {
3679     SDValue Elt = Op.getOperand(i);
3680     if (Elt.getOpcode() == ISD::UNDEF)
3681       continue;
3682     Values.insert(Elt);
3683     if (Elt.getOpcode() != ISD::Constant &&
3684         Elt.getOpcode() != ISD::ConstantFP)
3685       IsAllConstants = false;
3686     if (X86::isZeroNode(Elt))
3687       NumZero++;
3688     else {
3689       NonZeros |= (1 << i);
3690       NumNonZero++;
3691     }
3692   }
3693
3694   if (NumNonZero == 0) {
3695     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3696     return DAG.getUNDEF(VT);
3697   }
3698
3699   // Special case for single non-zero, non-undef, element.
3700   if (NumNonZero == 1) {
3701     unsigned Idx = CountTrailingZeros_32(NonZeros);
3702     SDValue Item = Op.getOperand(Idx);
3703
3704     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3705     // the value are obviously zero, truncate the value to i32 and do the
3706     // insertion that way.  Only do this if the value is non-constant or if the
3707     // value is a constant being inserted into element 0.  It is cheaper to do
3708     // a constant pool load than it is to do a movd + shuffle.
3709     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3710         (!IsAllConstants || Idx == 0)) {
3711       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3712         // Handle MMX and SSE both.
3713         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3714         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3715
3716         // Truncate the value (which may itself be a constant) to i32, and
3717         // convert it to a vector with movd (S2V+shuffle to zero extend).
3718         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3719         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3720         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3721                                            Subtarget->hasSSE2(), DAG);
3722
3723         // Now we have our 32-bit value zero extended in the low element of
3724         // a vector.  If Idx != 0, swizzle it into place.
3725         if (Idx != 0) {
3726           SmallVector<int, 4> Mask;
3727           Mask.push_back(Idx);
3728           for (unsigned i = 1; i != VecElts; ++i)
3729             Mask.push_back(i);
3730           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3731                                       DAG.getUNDEF(Item.getValueType()),
3732                                       &Mask[0]);
3733         }
3734         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3735       }
3736     }
3737
3738     // If we have a constant or non-constant insertion into the low element of
3739     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3740     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3741     // depending on what the source datatype is.
3742     if (Idx == 0) {
3743       if (NumZero == 0) {
3744         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3745       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3746           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3747         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3748         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3749         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3750                                            DAG);
3751       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3752         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3753         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3754         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3755         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3756                                            Subtarget->hasSSE2(), DAG);
3757         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3758       }
3759     }
3760
3761     // Is it a vector logical left shift?
3762     if (NumElems == 2 && Idx == 1 &&
3763         X86::isZeroNode(Op.getOperand(0)) &&
3764         !X86::isZeroNode(Op.getOperand(1))) {
3765       unsigned NumBits = VT.getSizeInBits();
3766       return getVShift(true, VT,
3767                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3768                                    VT, Op.getOperand(1)),
3769                        NumBits/2, DAG, *this, dl);
3770     }
3771
3772     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3773       return SDValue();
3774
3775     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3776     // is a non-constant being inserted into an element other than the low one,
3777     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3778     // movd/movss) to move this into the low element, then shuffle it into
3779     // place.
3780     if (EVTBits == 32) {
3781       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3782
3783       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3784       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3785                                          Subtarget->hasSSE2(), DAG);
3786       SmallVector<int, 8> MaskVec;
3787       for (unsigned i = 0; i < NumElems; i++)
3788         MaskVec.push_back(i == Idx ? 0 : 1);
3789       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3790     }
3791   }
3792
3793   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3794   if (Values.size() == 1) {
3795     if (EVTBits == 32) {
3796       // Instead of a shuffle like this:
3797       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3798       // Check if it's possible to issue this instead.
3799       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3800       unsigned Idx = CountTrailingZeros_32(NonZeros);
3801       SDValue Item = Op.getOperand(Idx);
3802       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3803         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3804     }
3805     return SDValue();
3806   }
3807
3808   // A vector full of immediates; various special cases are already
3809   // handled, so this is best done with a single constant-pool load.
3810   if (IsAllConstants)
3811     return SDValue();
3812
3813   // Let legalizer expand 2-wide build_vectors.
3814   if (EVTBits == 64) {
3815     if (NumNonZero == 1) {
3816       // One half is zero or undef.
3817       unsigned Idx = CountTrailingZeros_32(NonZeros);
3818       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3819                                  Op.getOperand(Idx));
3820       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3821                                          Subtarget->hasSSE2(), DAG);
3822     }
3823     return SDValue();
3824   }
3825
3826   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3827   if (EVTBits == 8 && NumElems == 16) {
3828     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3829                                         *this);
3830     if (V.getNode()) return V;
3831   }
3832
3833   if (EVTBits == 16 && NumElems == 8) {
3834     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3835                                         *this);
3836     if (V.getNode()) return V;
3837   }
3838
3839   // If element VT is == 32 bits, turn it into a number of shuffles.
3840   SmallVector<SDValue, 8> V;
3841   V.resize(NumElems);
3842   if (NumElems == 4 && NumZero > 0) {
3843     for (unsigned i = 0; i < 4; ++i) {
3844       bool isZero = !(NonZeros & (1 << i));
3845       if (isZero)
3846         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3847       else
3848         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3849     }
3850
3851     for (unsigned i = 0; i < 2; ++i) {
3852       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3853         default: break;
3854         case 0:
3855           V[i] = V[i*2];  // Must be a zero vector.
3856           break;
3857         case 1:
3858           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3859           break;
3860         case 2:
3861           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3862           break;
3863         case 3:
3864           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3865           break;
3866       }
3867     }
3868
3869     SmallVector<int, 8> MaskVec;
3870     bool Reverse = (NonZeros & 0x3) == 2;
3871     for (unsigned i = 0; i < 2; ++i)
3872       MaskVec.push_back(Reverse ? 1-i : i);
3873     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3874     for (unsigned i = 0; i < 2; ++i)
3875       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3876     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3877   }
3878
3879   if (Values.size() > 2) {
3880     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3881     // values to be inserted is equal to the number of elements, in which case
3882     // use the unpack code below in the hopes of matching the consecutive elts
3883     // load merge pattern for shuffles.
3884     // FIXME: We could probably just check that here directly.
3885     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3886         getSubtarget()->hasSSE41()) {
3887       V[0] = DAG.getUNDEF(VT);
3888       for (unsigned i = 0; i < NumElems; ++i)
3889         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3890           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3891                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3892       return V[0];
3893     }
3894     // Expand into a number of unpckl*.
3895     // e.g. for v4f32
3896     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3897     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3898     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3899     for (unsigned i = 0; i < NumElems; ++i)
3900       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3901     NumElems >>= 1;
3902     while (NumElems != 0) {
3903       for (unsigned i = 0; i < NumElems; ++i)
3904         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3905       NumElems >>= 1;
3906     }
3907     return V[0];
3908   }
3909
3910   return SDValue();
3911 }
3912
3913 SDValue
3914 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3915   // We support concatenate two MMX registers and place them in a MMX
3916   // register.  This is better than doing a stack convert.
3917   DebugLoc dl = Op.getDebugLoc();
3918   EVT ResVT = Op.getValueType();
3919   assert(Op.getNumOperands() == 2);
3920   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3921          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3922   int Mask[2];
3923   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3924   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3925   InVec = Op.getOperand(1);
3926   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3927     unsigned NumElts = ResVT.getVectorNumElements();
3928     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3929     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3930                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3931   } else {
3932     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3933     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3934     Mask[0] = 0; Mask[1] = 2;
3935     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3936   }
3937   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3938 }
3939
3940 // v8i16 shuffles - Prefer shuffles in the following order:
3941 // 1. [all]   pshuflw, pshufhw, optional move
3942 // 2. [ssse3] 1 x pshufb
3943 // 3. [ssse3] 2 x pshufb + 1 x por
3944 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3945 static
3946 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3947                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3948   SDValue V1 = SVOp->getOperand(0);
3949   SDValue V2 = SVOp->getOperand(1);
3950   DebugLoc dl = SVOp->getDebugLoc();
3951   SmallVector<int, 8> MaskVals;
3952
3953   // Determine if more than 1 of the words in each of the low and high quadwords
3954   // of the result come from the same quadword of one of the two inputs.  Undef
3955   // mask values count as coming from any quadword, for better codegen.
3956   SmallVector<unsigned, 4> LoQuad(4);
3957   SmallVector<unsigned, 4> HiQuad(4);
3958   BitVector InputQuads(4);
3959   for (unsigned i = 0; i < 8; ++i) {
3960     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3961     int EltIdx = SVOp->getMaskElt(i);
3962     MaskVals.push_back(EltIdx);
3963     if (EltIdx < 0) {
3964       ++Quad[0];
3965       ++Quad[1];
3966       ++Quad[2];
3967       ++Quad[3];
3968       continue;
3969     }
3970     ++Quad[EltIdx / 4];
3971     InputQuads.set(EltIdx / 4);
3972   }
3973
3974   int BestLoQuad = -1;
3975   unsigned MaxQuad = 1;
3976   for (unsigned i = 0; i < 4; ++i) {
3977     if (LoQuad[i] > MaxQuad) {
3978       BestLoQuad = i;
3979       MaxQuad = LoQuad[i];
3980     }
3981   }
3982
3983   int BestHiQuad = -1;
3984   MaxQuad = 1;
3985   for (unsigned i = 0; i < 4; ++i) {
3986     if (HiQuad[i] > MaxQuad) {
3987       BestHiQuad = i;
3988       MaxQuad = HiQuad[i];
3989     }
3990   }
3991
3992   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3993   // of the two input vectors, shuffle them into one input vector so only a
3994   // single pshufb instruction is necessary. If There are more than 2 input
3995   // quads, disable the next transformation since it does not help SSSE3.
3996   bool V1Used = InputQuads[0] || InputQuads[1];
3997   bool V2Used = InputQuads[2] || InputQuads[3];
3998   if (TLI.getSubtarget()->hasSSSE3()) {
3999     if (InputQuads.count() == 2 && V1Used && V2Used) {
4000       BestLoQuad = InputQuads.find_first();
4001       BestHiQuad = InputQuads.find_next(BestLoQuad);
4002     }
4003     if (InputQuads.count() > 2) {
4004       BestLoQuad = -1;
4005       BestHiQuad = -1;
4006     }
4007   }
4008
4009   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4010   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4011   // words from all 4 input quadwords.
4012   SDValue NewV;
4013   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4014     SmallVector<int, 8> MaskV;
4015     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4016     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4017     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4018                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4019                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4020     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4021
4022     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4023     // source words for the shuffle, to aid later transformations.
4024     bool AllWordsInNewV = true;
4025     bool InOrder[2] = { true, true };
4026     for (unsigned i = 0; i != 8; ++i) {
4027       int idx = MaskVals[i];
4028       if (idx != (int)i)
4029         InOrder[i/4] = false;
4030       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4031         continue;
4032       AllWordsInNewV = false;
4033       break;
4034     }
4035
4036     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4037     if (AllWordsInNewV) {
4038       for (int i = 0; i != 8; ++i) {
4039         int idx = MaskVals[i];
4040         if (idx < 0)
4041           continue;
4042         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4043         if ((idx != i) && idx < 4)
4044           pshufhw = false;
4045         if ((idx != i) && idx > 3)
4046           pshuflw = false;
4047       }
4048       V1 = NewV;
4049       V2Used = false;
4050       BestLoQuad = 0;
4051       BestHiQuad = 1;
4052     }
4053
4054     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4055     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4056     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4057       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4058                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4059     }
4060   }
4061
4062   // If we have SSSE3, and all words of the result are from 1 input vector,
4063   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4064   // is present, fall back to case 4.
4065   if (TLI.getSubtarget()->hasSSSE3()) {
4066     SmallVector<SDValue,16> pshufbMask;
4067
4068     // If we have elements from both input vectors, set the high bit of the
4069     // shuffle mask element to zero out elements that come from V2 in the V1
4070     // mask, and elements that come from V1 in the V2 mask, so that the two
4071     // results can be OR'd together.
4072     bool TwoInputs = V1Used && V2Used;
4073     for (unsigned i = 0; i != 8; ++i) {
4074       int EltIdx = MaskVals[i] * 2;
4075       if (TwoInputs && (EltIdx >= 16)) {
4076         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4077         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4078         continue;
4079       }
4080       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4081       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4082     }
4083     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4084     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4085                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4086                                  MVT::v16i8, &pshufbMask[0], 16));
4087     if (!TwoInputs)
4088       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4089
4090     // Calculate the shuffle mask for the second input, shuffle it, and
4091     // OR it with the first shuffled input.
4092     pshufbMask.clear();
4093     for (unsigned i = 0; i != 8; ++i) {
4094       int EltIdx = MaskVals[i] * 2;
4095       if (EltIdx < 16) {
4096         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4097         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4098         continue;
4099       }
4100       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4101       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4102     }
4103     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4104     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4105                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4106                                  MVT::v16i8, &pshufbMask[0], 16));
4107     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4108     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4109   }
4110
4111   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4112   // and update MaskVals with new element order.
4113   BitVector InOrder(8);
4114   if (BestLoQuad >= 0) {
4115     SmallVector<int, 8> MaskV;
4116     for (int i = 0; i != 4; ++i) {
4117       int idx = MaskVals[i];
4118       if (idx < 0) {
4119         MaskV.push_back(-1);
4120         InOrder.set(i);
4121       } else if ((idx / 4) == BestLoQuad) {
4122         MaskV.push_back(idx & 3);
4123         InOrder.set(i);
4124       } else {
4125         MaskV.push_back(-1);
4126       }
4127     }
4128     for (unsigned i = 4; i != 8; ++i)
4129       MaskV.push_back(i);
4130     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4131                                 &MaskV[0]);
4132   }
4133
4134   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4135   // and update MaskVals with the new element order.
4136   if (BestHiQuad >= 0) {
4137     SmallVector<int, 8> MaskV;
4138     for (unsigned i = 0; i != 4; ++i)
4139       MaskV.push_back(i);
4140     for (unsigned i = 4; i != 8; ++i) {
4141       int idx = MaskVals[i];
4142       if (idx < 0) {
4143         MaskV.push_back(-1);
4144         InOrder.set(i);
4145       } else if ((idx / 4) == BestHiQuad) {
4146         MaskV.push_back((idx & 3) + 4);
4147         InOrder.set(i);
4148       } else {
4149         MaskV.push_back(-1);
4150       }
4151     }
4152     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4153                                 &MaskV[0]);
4154   }
4155
4156   // In case BestHi & BestLo were both -1, which means each quadword has a word
4157   // from each of the four input quadwords, calculate the InOrder bitvector now
4158   // before falling through to the insert/extract cleanup.
4159   if (BestLoQuad == -1 && BestHiQuad == -1) {
4160     NewV = V1;
4161     for (int i = 0; i != 8; ++i)
4162       if (MaskVals[i] < 0 || MaskVals[i] == i)
4163         InOrder.set(i);
4164   }
4165
4166   // The other elements are put in the right place using pextrw and pinsrw.
4167   for (unsigned i = 0; i != 8; ++i) {
4168     if (InOrder[i])
4169       continue;
4170     int EltIdx = MaskVals[i];
4171     if (EltIdx < 0)
4172       continue;
4173     SDValue ExtOp = (EltIdx < 8)
4174     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4175                   DAG.getIntPtrConstant(EltIdx))
4176     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4177                   DAG.getIntPtrConstant(EltIdx - 8));
4178     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4179                        DAG.getIntPtrConstant(i));
4180   }
4181   return NewV;
4182 }
4183
4184 // v16i8 shuffles - Prefer shuffles in the following order:
4185 // 1. [ssse3] 1 x pshufb
4186 // 2. [ssse3] 2 x pshufb + 1 x por
4187 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4188 static
4189 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4190                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4191   SDValue V1 = SVOp->getOperand(0);
4192   SDValue V2 = SVOp->getOperand(1);
4193   DebugLoc dl = SVOp->getDebugLoc();
4194   SmallVector<int, 16> MaskVals;
4195   SVOp->getMask(MaskVals);
4196
4197   // If we have SSSE3, case 1 is generated when all result bytes come from
4198   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4199   // present, fall back to case 3.
4200   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4201   bool V1Only = true;
4202   bool V2Only = true;
4203   for (unsigned i = 0; i < 16; ++i) {
4204     int EltIdx = MaskVals[i];
4205     if (EltIdx < 0)
4206       continue;
4207     if (EltIdx < 16)
4208       V2Only = false;
4209     else
4210       V1Only = false;
4211   }
4212
4213   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4214   if (TLI.getSubtarget()->hasSSSE3()) {
4215     SmallVector<SDValue,16> pshufbMask;
4216
4217     // If all result elements are from one input vector, then only translate
4218     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4219     //
4220     // Otherwise, we have elements from both input vectors, and must zero out
4221     // elements that come from V2 in the first mask, and V1 in the second mask
4222     // so that we can OR them together.
4223     bool TwoInputs = !(V1Only || V2Only);
4224     for (unsigned i = 0; i != 16; ++i) {
4225       int EltIdx = MaskVals[i];
4226       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4227         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4228         continue;
4229       }
4230       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4231     }
4232     // If all the elements are from V2, assign it to V1 and return after
4233     // building the first pshufb.
4234     if (V2Only)
4235       V1 = V2;
4236     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4237                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4238                                  MVT::v16i8, &pshufbMask[0], 16));
4239     if (!TwoInputs)
4240       return V1;
4241
4242     // Calculate the shuffle mask for the second input, shuffle it, and
4243     // OR it with the first shuffled input.
4244     pshufbMask.clear();
4245     for (unsigned i = 0; i != 16; ++i) {
4246       int EltIdx = MaskVals[i];
4247       if (EltIdx < 16) {
4248         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4249         continue;
4250       }
4251       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4252     }
4253     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4254                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4255                                  MVT::v16i8, &pshufbMask[0], 16));
4256     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4257   }
4258
4259   // No SSSE3 - Calculate in place words and then fix all out of place words
4260   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4261   // the 16 different words that comprise the two doublequadword input vectors.
4262   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4263   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4264   SDValue NewV = V2Only ? V2 : V1;
4265   for (int i = 0; i != 8; ++i) {
4266     int Elt0 = MaskVals[i*2];
4267     int Elt1 = MaskVals[i*2+1];
4268
4269     // This word of the result is all undef, skip it.
4270     if (Elt0 < 0 && Elt1 < 0)
4271       continue;
4272
4273     // This word of the result is already in the correct place, skip it.
4274     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4275       continue;
4276     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4277       continue;
4278
4279     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4280     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4281     SDValue InsElt;
4282
4283     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4284     // using a single extract together, load it and store it.
4285     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4286       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4287                            DAG.getIntPtrConstant(Elt1 / 2));
4288       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4289                         DAG.getIntPtrConstant(i));
4290       continue;
4291     }
4292
4293     // If Elt1 is defined, extract it from the appropriate source.  If the
4294     // source byte is not also odd, shift the extracted word left 8 bits
4295     // otherwise clear the bottom 8 bits if we need to do an or.
4296     if (Elt1 >= 0) {
4297       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4298                            DAG.getIntPtrConstant(Elt1 / 2));
4299       if ((Elt1 & 1) == 0)
4300         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4301                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4302       else if (Elt0 >= 0)
4303         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4304                              DAG.getConstant(0xFF00, MVT::i16));
4305     }
4306     // If Elt0 is defined, extract it from the appropriate source.  If the
4307     // source byte is not also even, shift the extracted word right 8 bits. If
4308     // Elt1 was also defined, OR the extracted values together before
4309     // inserting them in the result.
4310     if (Elt0 >= 0) {
4311       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4312                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4313       if ((Elt0 & 1) != 0)
4314         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4315                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4316       else if (Elt1 >= 0)
4317         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4318                              DAG.getConstant(0x00FF, MVT::i16));
4319       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4320                          : InsElt0;
4321     }
4322     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4323                        DAG.getIntPtrConstant(i));
4324   }
4325   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4326 }
4327
4328 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4329 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4330 /// done when every pair / quad of shuffle mask elements point to elements in
4331 /// the right sequence. e.g.
4332 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4333 static
4334 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4335                                  SelectionDAG &DAG,
4336                                  TargetLowering &TLI, DebugLoc dl) {
4337   EVT VT = SVOp->getValueType(0);
4338   SDValue V1 = SVOp->getOperand(0);
4339   SDValue V2 = SVOp->getOperand(1);
4340   unsigned NumElems = VT.getVectorNumElements();
4341   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4342   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4343   EVT MaskEltVT = MaskVT.getVectorElementType();
4344   EVT NewVT = MaskVT;
4345   switch (VT.getSimpleVT().SimpleTy) {
4346   default: assert(false && "Unexpected!");
4347   case MVT::v4f32: NewVT = MVT::v2f64; break;
4348   case MVT::v4i32: NewVT = MVT::v2i64; break;
4349   case MVT::v8i16: NewVT = MVT::v4i32; break;
4350   case MVT::v16i8: NewVT = MVT::v4i32; break;
4351   }
4352
4353   if (NewWidth == 2) {
4354     if (VT.isInteger())
4355       NewVT = MVT::v2i64;
4356     else
4357       NewVT = MVT::v2f64;
4358   }
4359   int Scale = NumElems / NewWidth;
4360   SmallVector<int, 8> MaskVec;
4361   for (unsigned i = 0; i < NumElems; i += Scale) {
4362     int StartIdx = -1;
4363     for (int j = 0; j < Scale; ++j) {
4364       int EltIdx = SVOp->getMaskElt(i+j);
4365       if (EltIdx < 0)
4366         continue;
4367       if (StartIdx == -1)
4368         StartIdx = EltIdx - (EltIdx % Scale);
4369       if (EltIdx != StartIdx + j)
4370         return SDValue();
4371     }
4372     if (StartIdx == -1)
4373       MaskVec.push_back(-1);
4374     else
4375       MaskVec.push_back(StartIdx / Scale);
4376   }
4377
4378   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4379   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4380   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4381 }
4382
4383 /// getVZextMovL - Return a zero-extending vector move low node.
4384 ///
4385 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4386                             SDValue SrcOp, SelectionDAG &DAG,
4387                             const X86Subtarget *Subtarget, DebugLoc dl) {
4388   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4389     LoadSDNode *LD = NULL;
4390     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4391       LD = dyn_cast<LoadSDNode>(SrcOp);
4392     if (!LD) {
4393       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4394       // instead.
4395       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4396       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4397           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4398           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4399           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4400         // PR2108
4401         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4402         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4403                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4404                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4405                                                    OpVT,
4406                                                    SrcOp.getOperand(0)
4407                                                           .getOperand(0))));
4408       }
4409     }
4410   }
4411
4412   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4413                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4414                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4415                                              OpVT, SrcOp)));
4416 }
4417
4418 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4419 /// shuffles.
4420 static SDValue
4421 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4422   SDValue V1 = SVOp->getOperand(0);
4423   SDValue V2 = SVOp->getOperand(1);
4424   DebugLoc dl = SVOp->getDebugLoc();
4425   EVT VT = SVOp->getValueType(0);
4426
4427   SmallVector<std::pair<int, int>, 8> Locs;
4428   Locs.resize(4);
4429   SmallVector<int, 8> Mask1(4U, -1);
4430   SmallVector<int, 8> PermMask;
4431   SVOp->getMask(PermMask);
4432
4433   unsigned NumHi = 0;
4434   unsigned NumLo = 0;
4435   for (unsigned i = 0; i != 4; ++i) {
4436     int Idx = PermMask[i];
4437     if (Idx < 0) {
4438       Locs[i] = std::make_pair(-1, -1);
4439     } else {
4440       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4441       if (Idx < 4) {
4442         Locs[i] = std::make_pair(0, NumLo);
4443         Mask1[NumLo] = Idx;
4444         NumLo++;
4445       } else {
4446         Locs[i] = std::make_pair(1, NumHi);
4447         if (2+NumHi < 4)
4448           Mask1[2+NumHi] = Idx;
4449         NumHi++;
4450       }
4451     }
4452   }
4453
4454   if (NumLo <= 2 && NumHi <= 2) {
4455     // If no more than two elements come from either vector. This can be
4456     // implemented with two shuffles. First shuffle gather the elements.
4457     // The second shuffle, which takes the first shuffle as both of its
4458     // vector operands, put the elements into the right order.
4459     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4460
4461     SmallVector<int, 8> Mask2(4U, -1);
4462
4463     for (unsigned i = 0; i != 4; ++i) {
4464       if (Locs[i].first == -1)
4465         continue;
4466       else {
4467         unsigned Idx = (i < 2) ? 0 : 4;
4468         Idx += Locs[i].first * 2 + Locs[i].second;
4469         Mask2[i] = Idx;
4470       }
4471     }
4472
4473     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4474   } else if (NumLo == 3 || NumHi == 3) {
4475     // Otherwise, we must have three elements from one vector, call it X, and
4476     // one element from the other, call it Y.  First, use a shufps to build an
4477     // intermediate vector with the one element from Y and the element from X
4478     // that will be in the same half in the final destination (the indexes don't
4479     // matter). Then, use a shufps to build the final vector, taking the half
4480     // containing the element from Y from the intermediate, and the other half
4481     // from X.
4482     if (NumHi == 3) {
4483       // Normalize it so the 3 elements come from V1.
4484       CommuteVectorShuffleMask(PermMask, VT);
4485       std::swap(V1, V2);
4486     }
4487
4488     // Find the element from V2.
4489     unsigned HiIndex;
4490     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4491       int Val = PermMask[HiIndex];
4492       if (Val < 0)
4493         continue;
4494       if (Val >= 4)
4495         break;
4496     }
4497
4498     Mask1[0] = PermMask[HiIndex];
4499     Mask1[1] = -1;
4500     Mask1[2] = PermMask[HiIndex^1];
4501     Mask1[3] = -1;
4502     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4503
4504     if (HiIndex >= 2) {
4505       Mask1[0] = PermMask[0];
4506       Mask1[1] = PermMask[1];
4507       Mask1[2] = HiIndex & 1 ? 6 : 4;
4508       Mask1[3] = HiIndex & 1 ? 4 : 6;
4509       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4510     } else {
4511       Mask1[0] = HiIndex & 1 ? 2 : 0;
4512       Mask1[1] = HiIndex & 1 ? 0 : 2;
4513       Mask1[2] = PermMask[2];
4514       Mask1[3] = PermMask[3];
4515       if (Mask1[2] >= 0)
4516         Mask1[2] += 4;
4517       if (Mask1[3] >= 0)
4518         Mask1[3] += 4;
4519       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4520     }
4521   }
4522
4523   // Break it into (shuffle shuffle_hi, shuffle_lo).
4524   Locs.clear();
4525   SmallVector<int,8> LoMask(4U, -1);
4526   SmallVector<int,8> HiMask(4U, -1);
4527
4528   SmallVector<int,8> *MaskPtr = &LoMask;
4529   unsigned MaskIdx = 0;
4530   unsigned LoIdx = 0;
4531   unsigned HiIdx = 2;
4532   for (unsigned i = 0; i != 4; ++i) {
4533     if (i == 2) {
4534       MaskPtr = &HiMask;
4535       MaskIdx = 1;
4536       LoIdx = 0;
4537       HiIdx = 2;
4538     }
4539     int Idx = PermMask[i];
4540     if (Idx < 0) {
4541       Locs[i] = std::make_pair(-1, -1);
4542     } else if (Idx < 4) {
4543       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4544       (*MaskPtr)[LoIdx] = Idx;
4545       LoIdx++;
4546     } else {
4547       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4548       (*MaskPtr)[HiIdx] = Idx;
4549       HiIdx++;
4550     }
4551   }
4552
4553   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4554   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4555   SmallVector<int, 8> MaskOps;
4556   for (unsigned i = 0; i != 4; ++i) {
4557     if (Locs[i].first == -1) {
4558       MaskOps.push_back(-1);
4559     } else {
4560       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4561       MaskOps.push_back(Idx);
4562     }
4563   }
4564   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4565 }
4566
4567 SDValue
4568 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4569   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4570   SDValue V1 = Op.getOperand(0);
4571   SDValue V2 = Op.getOperand(1);
4572   EVT VT = Op.getValueType();
4573   DebugLoc dl = Op.getDebugLoc();
4574   unsigned NumElems = VT.getVectorNumElements();
4575   bool isMMX = VT.getSizeInBits() == 64;
4576   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4577   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4578   bool V1IsSplat = false;
4579   bool V2IsSplat = false;
4580
4581   if (isZeroShuffle(SVOp))
4582     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4583
4584   // Promote splats to v4f32.
4585   if (SVOp->isSplat()) {
4586     if (isMMX || NumElems < 4)
4587       return Op;
4588     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4589   }
4590
4591   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4592   // do it!
4593   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4594     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4595     if (NewOp.getNode())
4596       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4597                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4598   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4599     // FIXME: Figure out a cleaner way to do this.
4600     // Try to make use of movq to zero out the top part.
4601     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4602       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4603       if (NewOp.getNode()) {
4604         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4605           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4606                               DAG, Subtarget, dl);
4607       }
4608     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4609       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4610       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4611         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4612                             DAG, Subtarget, dl);
4613     }
4614   }
4615
4616   if (X86::isPSHUFDMask(SVOp))
4617     return Op;
4618
4619   // Check if this can be converted into a logical shift.
4620   bool isLeft = false;
4621   unsigned ShAmt = 0;
4622   SDValue ShVal;
4623   bool isShift = getSubtarget()->hasSSE2() &&
4624     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4625   if (isShift && ShVal.hasOneUse()) {
4626     // If the shifted value has multiple uses, it may be cheaper to use
4627     // v_set0 + movlhps or movhlps, etc.
4628     EVT EltVT = VT.getVectorElementType();
4629     ShAmt *= EltVT.getSizeInBits();
4630     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4631   }
4632
4633   if (X86::isMOVLMask(SVOp)) {
4634     if (V1IsUndef)
4635       return V2;
4636     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4637       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4638     if (!isMMX)
4639       return Op;
4640   }
4641
4642   // FIXME: fold these into legal mask.
4643   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4644                  X86::isMOVSLDUPMask(SVOp) ||
4645                  X86::isMOVHLPSMask(SVOp) ||
4646                  X86::isMOVLHPSMask(SVOp) ||
4647                  X86::isMOVLPMask(SVOp)))
4648     return Op;
4649
4650   if (ShouldXformToMOVHLPS(SVOp) ||
4651       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4652     return CommuteVectorShuffle(SVOp, DAG);
4653
4654   if (isShift) {
4655     // No better options. Use a vshl / vsrl.
4656     EVT EltVT = VT.getVectorElementType();
4657     ShAmt *= EltVT.getSizeInBits();
4658     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4659   }
4660
4661   bool Commuted = false;
4662   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4663   // 1,1,1,1 -> v8i16 though.
4664   V1IsSplat = isSplatVector(V1.getNode());
4665   V2IsSplat = isSplatVector(V2.getNode());
4666
4667   // Canonicalize the splat or undef, if present, to be on the RHS.
4668   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4669     Op = CommuteVectorShuffle(SVOp, DAG);
4670     SVOp = cast<ShuffleVectorSDNode>(Op);
4671     V1 = SVOp->getOperand(0);
4672     V2 = SVOp->getOperand(1);
4673     std::swap(V1IsSplat, V2IsSplat);
4674     std::swap(V1IsUndef, V2IsUndef);
4675     Commuted = true;
4676   }
4677
4678   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4679     // Shuffling low element of v1 into undef, just return v1.
4680     if (V2IsUndef)
4681       return V1;
4682     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4683     // the instruction selector will not match, so get a canonical MOVL with
4684     // swapped operands to undo the commute.
4685     return getMOVL(DAG, dl, VT, V2, V1);
4686   }
4687
4688   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4689       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4690       X86::isUNPCKLMask(SVOp) ||
4691       X86::isUNPCKHMask(SVOp))
4692     return Op;
4693
4694   if (V2IsSplat) {
4695     // Normalize mask so all entries that point to V2 points to its first
4696     // element then try to match unpck{h|l} again. If match, return a
4697     // new vector_shuffle with the corrected mask.
4698     SDValue NewMask = NormalizeMask(SVOp, DAG);
4699     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4700     if (NSVOp != SVOp) {
4701       if (X86::isUNPCKLMask(NSVOp, true)) {
4702         return NewMask;
4703       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4704         return NewMask;
4705       }
4706     }
4707   }
4708
4709   if (Commuted) {
4710     // Commute is back and try unpck* again.
4711     // FIXME: this seems wrong.
4712     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4713     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4714     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4715         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4716         X86::isUNPCKLMask(NewSVOp) ||
4717         X86::isUNPCKHMask(NewSVOp))
4718       return NewOp;
4719   }
4720
4721   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4722
4723   // Normalize the node to match x86 shuffle ops if needed
4724   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4725     return CommuteVectorShuffle(SVOp, DAG);
4726
4727   // Check for legal shuffle and return?
4728   SmallVector<int, 16> PermMask;
4729   SVOp->getMask(PermMask);
4730   if (isShuffleMaskLegal(PermMask, VT))
4731     return Op;
4732
4733   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4734   if (VT == MVT::v8i16) {
4735     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4736     if (NewOp.getNode())
4737       return NewOp;
4738   }
4739
4740   if (VT == MVT::v16i8) {
4741     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4742     if (NewOp.getNode())
4743       return NewOp;
4744   }
4745
4746   // Handle all 4 wide cases with a number of shuffles except for MMX.
4747   if (NumElems == 4 && !isMMX)
4748     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4749
4750   return SDValue();
4751 }
4752
4753 SDValue
4754 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4755                                                 SelectionDAG &DAG) {
4756   EVT VT = Op.getValueType();
4757   DebugLoc dl = Op.getDebugLoc();
4758   if (VT.getSizeInBits() == 8) {
4759     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4760                                     Op.getOperand(0), Op.getOperand(1));
4761     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4762                                     DAG.getValueType(VT));
4763     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4764   } else if (VT.getSizeInBits() == 16) {
4765     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4766     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4767     if (Idx == 0)
4768       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4769                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4770                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4771                                                  MVT::v4i32,
4772                                                  Op.getOperand(0)),
4773                                      Op.getOperand(1)));
4774     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4775                                     Op.getOperand(0), Op.getOperand(1));
4776     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4777                                     DAG.getValueType(VT));
4778     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4779   } else if (VT == MVT::f32) {
4780     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4781     // the result back to FR32 register. It's only worth matching if the
4782     // result has a single use which is a store or a bitcast to i32.  And in
4783     // the case of a store, it's not worth it if the index is a constant 0,
4784     // because a MOVSSmr can be used instead, which is smaller and faster.
4785     if (!Op.hasOneUse())
4786       return SDValue();
4787     SDNode *User = *Op.getNode()->use_begin();
4788     if ((User->getOpcode() != ISD::STORE ||
4789          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4790           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4791         (User->getOpcode() != ISD::BIT_CONVERT ||
4792          User->getValueType(0) != MVT::i32))
4793       return SDValue();
4794     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4795                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4796                                               Op.getOperand(0)),
4797                                               Op.getOperand(1));
4798     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4799   } else if (VT == MVT::i32) {
4800     // ExtractPS works with constant index.
4801     if (isa<ConstantSDNode>(Op.getOperand(1)))
4802       return Op;
4803   }
4804   return SDValue();
4805 }
4806
4807
4808 SDValue
4809 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4810   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4811     return SDValue();
4812
4813   if (Subtarget->hasSSE41()) {
4814     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4815     if (Res.getNode())
4816       return Res;
4817   }
4818
4819   EVT VT = Op.getValueType();
4820   DebugLoc dl = Op.getDebugLoc();
4821   // TODO: handle v16i8.
4822   if (VT.getSizeInBits() == 16) {
4823     SDValue Vec = Op.getOperand(0);
4824     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4825     if (Idx == 0)
4826       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4827                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4828                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4829                                                  MVT::v4i32, Vec),
4830                                      Op.getOperand(1)));
4831     // Transform it so it match pextrw which produces a 32-bit result.
4832     EVT EltVT = MVT::i32;
4833     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4834                                     Op.getOperand(0), Op.getOperand(1));
4835     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4836                                     DAG.getValueType(VT));
4837     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4838   } else if (VT.getSizeInBits() == 32) {
4839     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4840     if (Idx == 0)
4841       return Op;
4842
4843     // SHUFPS the element to the lowest double word, then movss.
4844     int Mask[4] = { Idx, -1, -1, -1 };
4845     EVT VVT = Op.getOperand(0).getValueType();
4846     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4847                                        DAG.getUNDEF(VVT), Mask);
4848     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4849                        DAG.getIntPtrConstant(0));
4850   } else if (VT.getSizeInBits() == 64) {
4851     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4852     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4853     //        to match extract_elt for f64.
4854     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4855     if (Idx == 0)
4856       return Op;
4857
4858     // UNPCKHPD the element to the lowest double word, then movsd.
4859     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4860     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4861     int Mask[2] = { 1, -1 };
4862     EVT VVT = Op.getOperand(0).getValueType();
4863     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4864                                        DAG.getUNDEF(VVT), Mask);
4865     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4866                        DAG.getIntPtrConstant(0));
4867   }
4868
4869   return SDValue();
4870 }
4871
4872 SDValue
4873 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4874   EVT VT = Op.getValueType();
4875   EVT EltVT = VT.getVectorElementType();
4876   DebugLoc dl = Op.getDebugLoc();
4877
4878   SDValue N0 = Op.getOperand(0);
4879   SDValue N1 = Op.getOperand(1);
4880   SDValue N2 = Op.getOperand(2);
4881
4882   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4883       isa<ConstantSDNode>(N2)) {
4884     unsigned Opc;
4885     if (VT == MVT::v8i16)
4886       Opc = X86ISD::PINSRW;
4887     else if (VT == MVT::v4i16)
4888       Opc = X86ISD::MMX_PINSRW;
4889     else if (VT == MVT::v16i8)
4890       Opc = X86ISD::PINSRB;
4891     else
4892       Opc = X86ISD::PINSRB;
4893
4894     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4895     // argument.
4896     if (N1.getValueType() != MVT::i32)
4897       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4898     if (N2.getValueType() != MVT::i32)
4899       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4900     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4901   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4902     // Bits [7:6] of the constant are the source select.  This will always be
4903     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4904     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4905     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4906     // Bits [5:4] of the constant are the destination select.  This is the
4907     //  value of the incoming immediate.
4908     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4909     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4910     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4911     // Create this as a scalar to vector..
4912     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4913     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4914   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4915     // PINSR* works with constant index.
4916     return Op;
4917   }
4918   return SDValue();
4919 }
4920
4921 SDValue
4922 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4923   EVT VT = Op.getValueType();
4924   EVT EltVT = VT.getVectorElementType();
4925
4926   if (Subtarget->hasSSE41())
4927     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4928
4929   if (EltVT == MVT::i8)
4930     return SDValue();
4931
4932   DebugLoc dl = Op.getDebugLoc();
4933   SDValue N0 = Op.getOperand(0);
4934   SDValue N1 = Op.getOperand(1);
4935   SDValue N2 = Op.getOperand(2);
4936
4937   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4938     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4939     // as its second argument.
4940     if (N1.getValueType() != MVT::i32)
4941       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4942     if (N2.getValueType() != MVT::i32)
4943       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4944     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4945                        dl, VT, N0, N1, N2);
4946   }
4947   return SDValue();
4948 }
4949
4950 SDValue
4951 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4952   DebugLoc dl = Op.getDebugLoc();
4953   if (Op.getValueType() == MVT::v2f32)
4954     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4955                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4956                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4957                                                Op.getOperand(0))));
4958
4959   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4960     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4961
4962   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4963   EVT VT = MVT::v2i32;
4964   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4965   default: break;
4966   case MVT::v16i8:
4967   case MVT::v8i16:
4968     VT = MVT::v4i32;
4969     break;
4970   }
4971   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4972                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4973 }
4974
4975 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4976 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4977 // one of the above mentioned nodes. It has to be wrapped because otherwise
4978 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4979 // be used to form addressing mode. These wrapped nodes will be selected
4980 // into MOV32ri.
4981 SDValue
4982 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4983   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4984
4985   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4986   // global base reg.
4987   unsigned char OpFlag = 0;
4988   unsigned WrapperKind = X86ISD::Wrapper;
4989   CodeModel::Model M = getTargetMachine().getCodeModel();
4990
4991   if (Subtarget->isPICStyleRIPRel() &&
4992       (M == CodeModel::Small || M == CodeModel::Kernel))
4993     WrapperKind = X86ISD::WrapperRIP;
4994   else if (Subtarget->isPICStyleGOT())
4995     OpFlag = X86II::MO_GOTOFF;
4996   else if (Subtarget->isPICStyleStubPIC())
4997     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4998
4999   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5000                                              CP->getAlignment(),
5001                                              CP->getOffset(), OpFlag);
5002   DebugLoc DL = CP->getDebugLoc();
5003   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5004   // With PIC, the address is actually $g + Offset.
5005   if (OpFlag) {
5006     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5007                          DAG.getNode(X86ISD::GlobalBaseReg,
5008                                      DebugLoc::getUnknownLoc(), getPointerTy()),
5009                          Result);
5010   }
5011
5012   return Result;
5013 }
5014
5015 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
5016   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5017
5018   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5019   // global base reg.
5020   unsigned char OpFlag = 0;
5021   unsigned WrapperKind = X86ISD::Wrapper;
5022   CodeModel::Model M = getTargetMachine().getCodeModel();
5023
5024   if (Subtarget->isPICStyleRIPRel() &&
5025       (M == CodeModel::Small || M == CodeModel::Kernel))
5026     WrapperKind = X86ISD::WrapperRIP;
5027   else if (Subtarget->isPICStyleGOT())
5028     OpFlag = X86II::MO_GOTOFF;
5029   else if (Subtarget->isPICStyleStubPIC())
5030     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5031
5032   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5033                                           OpFlag);
5034   DebugLoc DL = JT->getDebugLoc();
5035   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5036
5037   // With PIC, the address is actually $g + Offset.
5038   if (OpFlag) {
5039     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5040                          DAG.getNode(X86ISD::GlobalBaseReg,
5041                                      DebugLoc::getUnknownLoc(), getPointerTy()),
5042                          Result);
5043   }
5044
5045   return Result;
5046 }
5047
5048 SDValue
5049 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5050   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5051
5052   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5053   // global base reg.
5054   unsigned char OpFlag = 0;
5055   unsigned WrapperKind = X86ISD::Wrapper;
5056   CodeModel::Model M = getTargetMachine().getCodeModel();
5057
5058   if (Subtarget->isPICStyleRIPRel() &&
5059       (M == CodeModel::Small || M == CodeModel::Kernel))
5060     WrapperKind = X86ISD::WrapperRIP;
5061   else if (Subtarget->isPICStyleGOT())
5062     OpFlag = X86II::MO_GOTOFF;
5063   else if (Subtarget->isPICStyleStubPIC())
5064     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5065
5066   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5067
5068   DebugLoc DL = Op.getDebugLoc();
5069   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5070
5071
5072   // With PIC, the address is actually $g + Offset.
5073   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5074       !Subtarget->is64Bit()) {
5075     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5076                          DAG.getNode(X86ISD::GlobalBaseReg,
5077                                      DebugLoc::getUnknownLoc(),
5078                                      getPointerTy()),
5079                          Result);
5080   }
5081
5082   return Result;
5083 }
5084
5085 SDValue
5086 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5087   // Create the TargetBlockAddressAddress node.
5088   unsigned char OpFlags =
5089     Subtarget->ClassifyBlockAddressReference();
5090   CodeModel::Model M = getTargetMachine().getCodeModel();
5091   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5092   DebugLoc dl = Op.getDebugLoc();
5093   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5094                                        /*isTarget=*/true, OpFlags);
5095
5096   if (Subtarget->isPICStyleRIPRel() &&
5097       (M == CodeModel::Small || M == CodeModel::Kernel))
5098     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5099   else
5100     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5101
5102   // With PIC, the address is actually $g + Offset.
5103   if (isGlobalRelativeToPICBase(OpFlags)) {
5104     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5105                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5106                          Result);
5107   }
5108
5109   return Result;
5110 }
5111
5112 SDValue
5113 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5114                                       int64_t Offset,
5115                                       SelectionDAG &DAG) const {
5116   // Create the TargetGlobalAddress node, folding in the constant
5117   // offset if it is legal.
5118   unsigned char OpFlags =
5119     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5120   CodeModel::Model M = getTargetMachine().getCodeModel();
5121   SDValue Result;
5122   if (OpFlags == X86II::MO_NO_FLAG &&
5123       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5124     // A direct static reference to a global.
5125     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5126     Offset = 0;
5127   } else {
5128     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5129   }
5130
5131   if (Subtarget->isPICStyleRIPRel() &&
5132       (M == CodeModel::Small || M == CodeModel::Kernel))
5133     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5134   else
5135     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5136
5137   // With PIC, the address is actually $g + Offset.
5138   if (isGlobalRelativeToPICBase(OpFlags)) {
5139     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5140                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5141                          Result);
5142   }
5143
5144   // For globals that require a load from a stub to get the address, emit the
5145   // load.
5146   if (isGlobalStubReference(OpFlags))
5147     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5148                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5149
5150   // If there was a non-zero offset that we didn't fold, create an explicit
5151   // addition for it.
5152   if (Offset != 0)
5153     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5154                          DAG.getConstant(Offset, getPointerTy()));
5155
5156   return Result;
5157 }
5158
5159 SDValue
5160 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5161   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5162   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5163   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5164 }
5165
5166 static SDValue
5167 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5168            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5169            unsigned char OperandFlags) {
5170   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5171   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5172   DebugLoc dl = GA->getDebugLoc();
5173   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5174                                            GA->getValueType(0),
5175                                            GA->getOffset(),
5176                                            OperandFlags);
5177   if (InFlag) {
5178     SDValue Ops[] = { Chain,  TGA, *InFlag };
5179     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5180   } else {
5181     SDValue Ops[]  = { Chain, TGA };
5182     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5183   }
5184
5185   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5186   MFI->setHasCalls(true);
5187
5188   SDValue Flag = Chain.getValue(1);
5189   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5190 }
5191
5192 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5193 static SDValue
5194 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5195                                 const EVT PtrVT) {
5196   SDValue InFlag;
5197   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5198   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5199                                      DAG.getNode(X86ISD::GlobalBaseReg,
5200                                                  DebugLoc::getUnknownLoc(),
5201                                                  PtrVT), InFlag);
5202   InFlag = Chain.getValue(1);
5203
5204   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5205 }
5206
5207 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5208 static SDValue
5209 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5210                                 const EVT PtrVT) {
5211   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5212                     X86::RAX, X86II::MO_TLSGD);
5213 }
5214
5215 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5216 // "local exec" model.
5217 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5218                                    const EVT PtrVT, TLSModel::Model model,
5219                                    bool is64Bit) {
5220   DebugLoc dl = GA->getDebugLoc();
5221   // Get the Thread Pointer
5222   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5223                              DebugLoc::getUnknownLoc(), PtrVT,
5224                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5225                                              MVT::i32));
5226
5227   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5228                                       NULL, 0, false, false, 0);
5229
5230   unsigned char OperandFlags = 0;
5231   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5232   // initialexec.
5233   unsigned WrapperKind = X86ISD::Wrapper;
5234   if (model == TLSModel::LocalExec) {
5235     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5236   } else if (is64Bit) {
5237     assert(model == TLSModel::InitialExec);
5238     OperandFlags = X86II::MO_GOTTPOFF;
5239     WrapperKind = X86ISD::WrapperRIP;
5240   } else {
5241     assert(model == TLSModel::InitialExec);
5242     OperandFlags = X86II::MO_INDNTPOFF;
5243   }
5244
5245   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5246   // exec)
5247   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5248                                            GA->getOffset(), OperandFlags);
5249   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5250
5251   if (model == TLSModel::InitialExec)
5252     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5253                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5254
5255   // The address of the thread local variable is the add of the thread
5256   // pointer with the offset of the variable.
5257   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5258 }
5259
5260 SDValue
5261 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5262   // TODO: implement the "local dynamic" model
5263   // TODO: implement the "initial exec"model for pic executables
5264   assert(Subtarget->isTargetELF() &&
5265          "TLS not implemented for non-ELF targets");
5266   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5267   const GlobalValue *GV = GA->getGlobal();
5268
5269   // If GV is an alias then use the aliasee for determining
5270   // thread-localness.
5271   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5272     GV = GA->resolveAliasedGlobal(false);
5273
5274   TLSModel::Model model = getTLSModel(GV,
5275                                       getTargetMachine().getRelocationModel());
5276
5277   switch (model) {
5278   case TLSModel::GeneralDynamic:
5279   case TLSModel::LocalDynamic: // not implemented
5280     if (Subtarget->is64Bit())
5281       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5282     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5283
5284   case TLSModel::InitialExec:
5285   case TLSModel::LocalExec:
5286     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5287                                Subtarget->is64Bit());
5288   }
5289
5290   llvm_unreachable("Unreachable");
5291   return SDValue();
5292 }
5293
5294
5295 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5296 /// take a 2 x i32 value to shift plus a shift amount.
5297 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5298   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5299   EVT VT = Op.getValueType();
5300   unsigned VTBits = VT.getSizeInBits();
5301   DebugLoc dl = Op.getDebugLoc();
5302   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5303   SDValue ShOpLo = Op.getOperand(0);
5304   SDValue ShOpHi = Op.getOperand(1);
5305   SDValue ShAmt  = Op.getOperand(2);
5306   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5307                                      DAG.getConstant(VTBits - 1, MVT::i8))
5308                        : DAG.getConstant(0, VT);
5309
5310   SDValue Tmp2, Tmp3;
5311   if (Op.getOpcode() == ISD::SHL_PARTS) {
5312     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5313     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5314   } else {
5315     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5316     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5317   }
5318
5319   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5320                                 DAG.getConstant(VTBits, MVT::i8));
5321   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5322                              AndNode, DAG.getConstant(0, MVT::i8));
5323
5324   SDValue Hi, Lo;
5325   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5326   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5327   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5328
5329   if (Op.getOpcode() == ISD::SHL_PARTS) {
5330     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5331     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5332   } else {
5333     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5334     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5335   }
5336
5337   SDValue Ops[2] = { Lo, Hi };
5338   return DAG.getMergeValues(Ops, 2, dl);
5339 }
5340
5341 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5342   EVT SrcVT = Op.getOperand(0).getValueType();
5343
5344   if (SrcVT.isVector()) {
5345     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5346       return Op;
5347     }
5348     return SDValue();
5349   }
5350
5351   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5352          "Unknown SINT_TO_FP to lower!");
5353
5354   // These are really Legal; return the operand so the caller accepts it as
5355   // Legal.
5356   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5357     return Op;
5358   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5359       Subtarget->is64Bit()) {
5360     return Op;
5361   }
5362
5363   DebugLoc dl = Op.getDebugLoc();
5364   unsigned Size = SrcVT.getSizeInBits()/8;
5365   MachineFunction &MF = DAG.getMachineFunction();
5366   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5367   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5368   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5369                                StackSlot,
5370                                PseudoSourceValue::getFixedStack(SSFI), 0,
5371                                false, false, 0);
5372   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5373 }
5374
5375 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5376                                      SDValue StackSlot,
5377                                      SelectionDAG &DAG) {
5378   // Build the FILD
5379   DebugLoc dl = Op.getDebugLoc();
5380   SDVTList Tys;
5381   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5382   if (useSSE)
5383     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5384   else
5385     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5386   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5387   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5388                                Tys, Ops, array_lengthof(Ops));
5389
5390   if (useSSE) {
5391     Chain = Result.getValue(1);
5392     SDValue InFlag = Result.getValue(2);
5393
5394     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5395     // shouldn't be necessary except that RFP cannot be live across
5396     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5397     MachineFunction &MF = DAG.getMachineFunction();
5398     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5399     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5400     Tys = DAG.getVTList(MVT::Other);
5401     SDValue Ops[] = {
5402       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5403     };
5404     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5405     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5406                          PseudoSourceValue::getFixedStack(SSFI), 0,
5407                          false, false, 0);
5408   }
5409
5410   return Result;
5411 }
5412
5413 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5414 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5415   // This algorithm is not obvious. Here it is in C code, more or less:
5416   /*
5417     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5418       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5419       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5420
5421       // Copy ints to xmm registers.
5422       __m128i xh = _mm_cvtsi32_si128( hi );
5423       __m128i xl = _mm_cvtsi32_si128( lo );
5424
5425       // Combine into low half of a single xmm register.
5426       __m128i x = _mm_unpacklo_epi32( xh, xl );
5427       __m128d d;
5428       double sd;
5429
5430       // Merge in appropriate exponents to give the integer bits the right
5431       // magnitude.
5432       x = _mm_unpacklo_epi32( x, exp );
5433
5434       // Subtract away the biases to deal with the IEEE-754 double precision
5435       // implicit 1.
5436       d = _mm_sub_pd( (__m128d) x, bias );
5437
5438       // All conversions up to here are exact. The correctly rounded result is
5439       // calculated using the current rounding mode using the following
5440       // horizontal add.
5441       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5442       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5443                                 // store doesn't really need to be here (except
5444                                 // maybe to zero the other double)
5445       return sd;
5446     }
5447   */
5448
5449   DebugLoc dl = Op.getDebugLoc();
5450   LLVMContext *Context = DAG.getContext();
5451
5452   // Build some magic constants.
5453   std::vector<Constant*> CV0;
5454   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5455   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5456   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5457   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5458   Constant *C0 = ConstantVector::get(CV0);
5459   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5460
5461   std::vector<Constant*> CV1;
5462   CV1.push_back(
5463     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5464   CV1.push_back(
5465     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5466   Constant *C1 = ConstantVector::get(CV1);
5467   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5468
5469   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5470                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5471                                         Op.getOperand(0),
5472                                         DAG.getIntPtrConstant(1)));
5473   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5474                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5475                                         Op.getOperand(0),
5476                                         DAG.getIntPtrConstant(0)));
5477   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5478   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5479                               PseudoSourceValue::getConstantPool(), 0,
5480                               false, false, 16);
5481   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5482   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5483   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5484                               PseudoSourceValue::getConstantPool(), 0,
5485                               false, false, 16);
5486   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5487
5488   // Add the halves; easiest way is to swap them into another reg first.
5489   int ShufMask[2] = { 1, -1 };
5490   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5491                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5492   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5493   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5494                      DAG.getIntPtrConstant(0));
5495 }
5496
5497 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5498 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5499   DebugLoc dl = Op.getDebugLoc();
5500   // FP constant to bias correct the final result.
5501   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5502                                    MVT::f64);
5503
5504   // Load the 32-bit value into an XMM register.
5505   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5506                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5507                                          Op.getOperand(0),
5508                                          DAG.getIntPtrConstant(0)));
5509
5510   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5511                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5512                      DAG.getIntPtrConstant(0));
5513
5514   // Or the load with the bias.
5515   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5516                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5517                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5518                                                    MVT::v2f64, Load)),
5519                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5520                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5521                                                    MVT::v2f64, Bias)));
5522   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5523                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5524                    DAG.getIntPtrConstant(0));
5525
5526   // Subtract the bias.
5527   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5528
5529   // Handle final rounding.
5530   EVT DestVT = Op.getValueType();
5531
5532   if (DestVT.bitsLT(MVT::f64)) {
5533     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5534                        DAG.getIntPtrConstant(0));
5535   } else if (DestVT.bitsGT(MVT::f64)) {
5536     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5537   }
5538
5539   // Handle final rounding.
5540   return Sub;
5541 }
5542
5543 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5544   SDValue N0 = Op.getOperand(0);
5545   DebugLoc dl = Op.getDebugLoc();
5546
5547   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5548   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5549   // the optimization here.
5550   if (DAG.SignBitIsZero(N0))
5551     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5552
5553   EVT SrcVT = N0.getValueType();
5554   if (SrcVT == MVT::i64) {
5555     // We only handle SSE2 f64 target here; caller can expand the rest.
5556     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5557       return SDValue();
5558
5559     return LowerUINT_TO_FP_i64(Op, DAG);
5560   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5561     return LowerUINT_TO_FP_i32(Op, DAG);
5562   }
5563
5564   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5565
5566   // Make a 64-bit buffer, and use it to build an FILD.
5567   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5568   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5569   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5570                                    getPointerTy(), StackSlot, WordOff);
5571   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5572                                 StackSlot, NULL, 0, false, false, 0);
5573   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5574                                 OffsetSlot, NULL, 0, false, false, 0);
5575   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5576 }
5577
5578 std::pair<SDValue,SDValue> X86TargetLowering::
5579 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5580   DebugLoc dl = Op.getDebugLoc();
5581
5582   EVT DstTy = Op.getValueType();
5583
5584   if (!IsSigned) {
5585     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5586     DstTy = MVT::i64;
5587   }
5588
5589   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5590          DstTy.getSimpleVT() >= MVT::i16 &&
5591          "Unknown FP_TO_SINT to lower!");
5592
5593   // These are really Legal.
5594   if (DstTy == MVT::i32 &&
5595       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5596     return std::make_pair(SDValue(), SDValue());
5597   if (Subtarget->is64Bit() &&
5598       DstTy == MVT::i64 &&
5599       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5600     return std::make_pair(SDValue(), SDValue());
5601
5602   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5603   // stack slot.
5604   MachineFunction &MF = DAG.getMachineFunction();
5605   unsigned MemSize = DstTy.getSizeInBits()/8;
5606   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5607   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5608
5609   unsigned Opc;
5610   switch (DstTy.getSimpleVT().SimpleTy) {
5611   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5612   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5613   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5614   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5615   }
5616
5617   SDValue Chain = DAG.getEntryNode();
5618   SDValue Value = Op.getOperand(0);
5619   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5620     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5621     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5622                          PseudoSourceValue::getFixedStack(SSFI), 0,
5623                          false, false, 0);
5624     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5625     SDValue Ops[] = {
5626       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5627     };
5628     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5629     Chain = Value.getValue(1);
5630     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5631     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5632   }
5633
5634   // Build the FP_TO_INT*_IN_MEM
5635   SDValue Ops[] = { Chain, Value, StackSlot };
5636   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5637
5638   return std::make_pair(FIST, StackSlot);
5639 }
5640
5641 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5642   if (Op.getValueType().isVector()) {
5643     if (Op.getValueType() == MVT::v2i32 &&
5644         Op.getOperand(0).getValueType() == MVT::v2f64) {
5645       return Op;
5646     }
5647     return SDValue();
5648   }
5649
5650   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5651   SDValue FIST = Vals.first, StackSlot = Vals.second;
5652   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5653   if (FIST.getNode() == 0) return Op;
5654
5655   // Load the result.
5656   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5657                      FIST, StackSlot, NULL, 0, false, false, 0);
5658 }
5659
5660 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5661   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5662   SDValue FIST = Vals.first, StackSlot = Vals.second;
5663   assert(FIST.getNode() && "Unexpected failure");
5664
5665   // Load the result.
5666   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5667                      FIST, StackSlot, NULL, 0, false, false, 0);
5668 }
5669
5670 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5671   LLVMContext *Context = DAG.getContext();
5672   DebugLoc dl = Op.getDebugLoc();
5673   EVT VT = Op.getValueType();
5674   EVT EltVT = VT;
5675   if (VT.isVector())
5676     EltVT = VT.getVectorElementType();
5677   std::vector<Constant*> CV;
5678   if (EltVT == MVT::f64) {
5679     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5680     CV.push_back(C);
5681     CV.push_back(C);
5682   } else {
5683     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5684     CV.push_back(C);
5685     CV.push_back(C);
5686     CV.push_back(C);
5687     CV.push_back(C);
5688   }
5689   Constant *C = ConstantVector::get(CV);
5690   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5691   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5692                              PseudoSourceValue::getConstantPool(), 0,
5693                              false, false, 16);
5694   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5695 }
5696
5697 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5698   LLVMContext *Context = DAG.getContext();
5699   DebugLoc dl = Op.getDebugLoc();
5700   EVT VT = Op.getValueType();
5701   EVT EltVT = VT;
5702   if (VT.isVector())
5703     EltVT = VT.getVectorElementType();
5704   std::vector<Constant*> CV;
5705   if (EltVT == MVT::f64) {
5706     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5707     CV.push_back(C);
5708     CV.push_back(C);
5709   } else {
5710     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5711     CV.push_back(C);
5712     CV.push_back(C);
5713     CV.push_back(C);
5714     CV.push_back(C);
5715   }
5716   Constant *C = ConstantVector::get(CV);
5717   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5718   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5719                              PseudoSourceValue::getConstantPool(), 0,
5720                              false, false, 16);
5721   if (VT.isVector()) {
5722     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5723                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5724                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5725                                 Op.getOperand(0)),
5726                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5727   } else {
5728     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5729   }
5730 }
5731
5732 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5733   LLVMContext *Context = DAG.getContext();
5734   SDValue Op0 = Op.getOperand(0);
5735   SDValue Op1 = Op.getOperand(1);
5736   DebugLoc dl = Op.getDebugLoc();
5737   EVT VT = Op.getValueType();
5738   EVT SrcVT = Op1.getValueType();
5739
5740   // If second operand is smaller, extend it first.
5741   if (SrcVT.bitsLT(VT)) {
5742     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5743     SrcVT = VT;
5744   }
5745   // And if it is bigger, shrink it first.
5746   if (SrcVT.bitsGT(VT)) {
5747     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5748     SrcVT = VT;
5749   }
5750
5751   // At this point the operands and the result should have the same
5752   // type, and that won't be f80 since that is not custom lowered.
5753
5754   // First get the sign bit of second operand.
5755   std::vector<Constant*> CV;
5756   if (SrcVT == MVT::f64) {
5757     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5758     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5759   } else {
5760     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5761     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5762     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5763     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5764   }
5765   Constant *C = ConstantVector::get(CV);
5766   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5767   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5768                               PseudoSourceValue::getConstantPool(), 0,
5769                               false, false, 16);
5770   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5771
5772   // Shift sign bit right or left if the two operands have different types.
5773   if (SrcVT.bitsGT(VT)) {
5774     // Op0 is MVT::f32, Op1 is MVT::f64.
5775     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5776     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5777                           DAG.getConstant(32, MVT::i32));
5778     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5779     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5780                           DAG.getIntPtrConstant(0));
5781   }
5782
5783   // Clear first operand sign bit.
5784   CV.clear();
5785   if (VT == MVT::f64) {
5786     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5787     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5788   } else {
5789     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5790     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5791     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5792     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5793   }
5794   C = ConstantVector::get(CV);
5795   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5796   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5797                               PseudoSourceValue::getConstantPool(), 0,
5798                               false, false, 16);
5799   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5800
5801   // Or the value with the sign bit.
5802   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5803 }
5804
5805 /// Emit nodes that will be selected as "test Op0,Op0", or something
5806 /// equivalent.
5807 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5808                                     SelectionDAG &DAG) {
5809   DebugLoc dl = Op.getDebugLoc();
5810
5811   // CF and OF aren't always set the way we want. Determine which
5812   // of these we need.
5813   bool NeedCF = false;
5814   bool NeedOF = false;
5815   switch (X86CC) {
5816   case X86::COND_A: case X86::COND_AE:
5817   case X86::COND_B: case X86::COND_BE:
5818     NeedCF = true;
5819     break;
5820   case X86::COND_G: case X86::COND_GE:
5821   case X86::COND_L: case X86::COND_LE:
5822   case X86::COND_O: case X86::COND_NO:
5823     NeedOF = true;
5824     break;
5825   default: break;
5826   }
5827
5828   // See if we can use the EFLAGS value from the operand instead of
5829   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5830   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5831   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5832     unsigned Opcode = 0;
5833     unsigned NumOperands = 0;
5834     switch (Op.getNode()->getOpcode()) {
5835     case ISD::ADD:
5836       // Due to an isel shortcoming, be conservative if this add is likely to
5837       // be selected as part of a load-modify-store instruction. When the root
5838       // node in a match is a store, isel doesn't know how to remap non-chain
5839       // non-flag uses of other nodes in the match, such as the ADD in this
5840       // case. This leads to the ADD being left around and reselected, with
5841       // the result being two adds in the output.
5842       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5843            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5844         if (UI->getOpcode() == ISD::STORE)
5845           goto default_case;
5846       if (ConstantSDNode *C =
5847             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5848         // An add of one will be selected as an INC.
5849         if (C->getAPIntValue() == 1) {
5850           Opcode = X86ISD::INC;
5851           NumOperands = 1;
5852           break;
5853         }
5854         // An add of negative one (subtract of one) will be selected as a DEC.
5855         if (C->getAPIntValue().isAllOnesValue()) {
5856           Opcode = X86ISD::DEC;
5857           NumOperands = 1;
5858           break;
5859         }
5860       }
5861       // Otherwise use a regular EFLAGS-setting add.
5862       Opcode = X86ISD::ADD;
5863       NumOperands = 2;
5864       break;
5865     case ISD::AND: {
5866       // If the primary and result isn't used, don't bother using X86ISD::AND,
5867       // because a TEST instruction will be better.
5868       bool NonFlagUse = false;
5869       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5870              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5871         SDNode *User = *UI;
5872         unsigned UOpNo = UI.getOperandNo();
5873         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5874           // Look pass truncate.
5875           UOpNo = User->use_begin().getOperandNo();
5876           User = *User->use_begin();
5877         }
5878         if (User->getOpcode() != ISD::BRCOND &&
5879             User->getOpcode() != ISD::SETCC &&
5880             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5881           NonFlagUse = true;
5882           break;
5883         }
5884       }
5885       if (!NonFlagUse)
5886         break;
5887     }
5888     // FALL THROUGH
5889     case ISD::SUB:
5890     case ISD::OR:
5891     case ISD::XOR:
5892       // Due to the ISEL shortcoming noted above, be conservative if this op is
5893       // likely to be selected as part of a load-modify-store instruction.
5894       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5895            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5896         if (UI->getOpcode() == ISD::STORE)
5897           goto default_case;
5898       // Otherwise use a regular EFLAGS-setting instruction.
5899       switch (Op.getNode()->getOpcode()) {
5900       case ISD::SUB: Opcode = X86ISD::SUB; break;
5901       case ISD::OR:  Opcode = X86ISD::OR;  break;
5902       case ISD::XOR: Opcode = X86ISD::XOR; break;
5903       case ISD::AND: Opcode = X86ISD::AND; break;
5904       default: llvm_unreachable("unexpected operator!");
5905       }
5906       NumOperands = 2;
5907       break;
5908     case X86ISD::ADD:
5909     case X86ISD::SUB:
5910     case X86ISD::INC:
5911     case X86ISD::DEC:
5912     case X86ISD::OR:
5913     case X86ISD::XOR:
5914     case X86ISD::AND:
5915       return SDValue(Op.getNode(), 1);
5916     default:
5917     default_case:
5918       break;
5919     }
5920     if (Opcode != 0) {
5921       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5922       SmallVector<SDValue, 4> Ops;
5923       for (unsigned i = 0; i != NumOperands; ++i)
5924         Ops.push_back(Op.getOperand(i));
5925       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5926       DAG.ReplaceAllUsesWith(Op, New);
5927       return SDValue(New.getNode(), 1);
5928     }
5929   }
5930
5931   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5932   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5933                      DAG.getConstant(0, Op.getValueType()));
5934 }
5935
5936 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5937 /// equivalent.
5938 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5939                                    SelectionDAG &DAG) {
5940   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5941     if (C->getAPIntValue() == 0)
5942       return EmitTest(Op0, X86CC, DAG);
5943
5944   DebugLoc dl = Op0.getDebugLoc();
5945   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5946 }
5947
5948 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5949 /// if it's possible.
5950 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
5951                          DebugLoc dl, SelectionDAG &DAG) {
5952   SDValue Op0 = And.getOperand(0);
5953   SDValue Op1 = And.getOperand(1);
5954   if (Op0.getOpcode() == ISD::TRUNCATE)
5955     Op0 = Op0.getOperand(0);
5956   if (Op1.getOpcode() == ISD::TRUNCATE)
5957     Op1 = Op1.getOperand(0);
5958
5959   SDValue LHS, RHS;
5960   if (Op1.getOpcode() == ISD::SHL) {
5961     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
5962       if (And10C->getZExtValue() == 1) {
5963         LHS = Op0;
5964         RHS = Op1.getOperand(1);
5965       }
5966   } else if (Op0.getOpcode() == ISD::SHL) {
5967     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
5968       if (And00C->getZExtValue() == 1) {
5969         LHS = Op1;
5970         RHS = Op0.getOperand(1);
5971       }
5972   } else if (Op1.getOpcode() == ISD::Constant) {
5973     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
5974     SDValue AndLHS = Op0;
5975     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5976       LHS = AndLHS.getOperand(0);
5977       RHS = AndLHS.getOperand(1);
5978     }
5979   }
5980
5981   if (LHS.getNode()) {
5982     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5983     // instruction.  Since the shift amount is in-range-or-undefined, we know
5984     // that doing a bittest on the i16 value is ok.  We extend to i32 because
5985     // the encoding for the i16 version is larger than the i32 version.
5986     if (LHS.getValueType() == MVT::i8)
5987       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5988
5989     // If the operand types disagree, extend the shift amount to match.  Since
5990     // BT ignores high bits (like shifts) we can use anyextend.
5991     if (LHS.getValueType() != RHS.getValueType())
5992       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5993
5994     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5995     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5996     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5997                        DAG.getConstant(Cond, MVT::i8), BT);
5998   }
5999
6000   return SDValue();
6001 }
6002
6003 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
6004   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6005   SDValue Op0 = Op.getOperand(0);
6006   SDValue Op1 = Op.getOperand(1);
6007   DebugLoc dl = Op.getDebugLoc();
6008   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6009
6010   // Optimize to BT if possible.
6011   // Lower (X & (1 << N)) == 0 to BT(X, N).
6012   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6013   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6014   if (Op0.getOpcode() == ISD::AND &&
6015       Op0.hasOneUse() &&
6016       Op1.getOpcode() == ISD::Constant &&
6017       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6018       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6019     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6020     if (NewSetCC.getNode())
6021       return NewSetCC;
6022   }
6023
6024   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6025   if (Op0.getOpcode() == X86ISD::SETCC &&
6026       Op1.getOpcode() == ISD::Constant &&
6027       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6028        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6029       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6030     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6031     bool Invert = (CC == ISD::SETNE) ^
6032       cast<ConstantSDNode>(Op1)->isNullValue();
6033     if (Invert)
6034       CCode = X86::GetOppositeBranchCondition(CCode);
6035     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6036                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6037   }
6038
6039   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6040   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6041   if (X86CC == X86::COND_INVALID)
6042     return SDValue();
6043
6044   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6045
6046   // Use sbb x, x to materialize carry bit into a GPR.
6047   if (X86CC == X86::COND_B)
6048     return DAG.getNode(ISD::AND, dl, MVT::i8,
6049                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6050                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6051                        DAG.getConstant(1, MVT::i8));
6052
6053   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6054                      DAG.getConstant(X86CC, MVT::i8), Cond);
6055 }
6056
6057 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6058   SDValue Cond;
6059   SDValue Op0 = Op.getOperand(0);
6060   SDValue Op1 = Op.getOperand(1);
6061   SDValue CC = Op.getOperand(2);
6062   EVT VT = Op.getValueType();
6063   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6064   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6065   DebugLoc dl = Op.getDebugLoc();
6066
6067   if (isFP) {
6068     unsigned SSECC = 8;
6069     EVT VT0 = Op0.getValueType();
6070     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6071     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6072     bool Swap = false;
6073
6074     switch (SetCCOpcode) {
6075     default: break;
6076     case ISD::SETOEQ:
6077     case ISD::SETEQ:  SSECC = 0; break;
6078     case ISD::SETOGT:
6079     case ISD::SETGT: Swap = true; // Fallthrough
6080     case ISD::SETLT:
6081     case ISD::SETOLT: SSECC = 1; break;
6082     case ISD::SETOGE:
6083     case ISD::SETGE: Swap = true; // Fallthrough
6084     case ISD::SETLE:
6085     case ISD::SETOLE: SSECC = 2; break;
6086     case ISD::SETUO:  SSECC = 3; break;
6087     case ISD::SETUNE:
6088     case ISD::SETNE:  SSECC = 4; break;
6089     case ISD::SETULE: Swap = true;
6090     case ISD::SETUGE: SSECC = 5; break;
6091     case ISD::SETULT: Swap = true;
6092     case ISD::SETUGT: SSECC = 6; break;
6093     case ISD::SETO:   SSECC = 7; break;
6094     }
6095     if (Swap)
6096       std::swap(Op0, Op1);
6097
6098     // In the two special cases we can't handle, emit two comparisons.
6099     if (SSECC == 8) {
6100       if (SetCCOpcode == ISD::SETUEQ) {
6101         SDValue UNORD, EQ;
6102         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6103         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6104         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6105       }
6106       else if (SetCCOpcode == ISD::SETONE) {
6107         SDValue ORD, NEQ;
6108         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6109         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6110         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6111       }
6112       llvm_unreachable("Illegal FP comparison");
6113     }
6114     // Handle all other FP comparisons here.
6115     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6116   }
6117
6118   // We are handling one of the integer comparisons here.  Since SSE only has
6119   // GT and EQ comparisons for integer, swapping operands and multiple
6120   // operations may be required for some comparisons.
6121   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6122   bool Swap = false, Invert = false, FlipSigns = false;
6123
6124   switch (VT.getSimpleVT().SimpleTy) {
6125   default: break;
6126   case MVT::v8i8:
6127   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6128   case MVT::v4i16:
6129   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6130   case MVT::v2i32:
6131   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6132   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6133   }
6134
6135   switch (SetCCOpcode) {
6136   default: break;
6137   case ISD::SETNE:  Invert = true;
6138   case ISD::SETEQ:  Opc = EQOpc; break;
6139   case ISD::SETLT:  Swap = true;
6140   case ISD::SETGT:  Opc = GTOpc; break;
6141   case ISD::SETGE:  Swap = true;
6142   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6143   case ISD::SETULT: Swap = true;
6144   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6145   case ISD::SETUGE: Swap = true;
6146   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6147   }
6148   if (Swap)
6149     std::swap(Op0, Op1);
6150
6151   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6152   // bits of the inputs before performing those operations.
6153   if (FlipSigns) {
6154     EVT EltVT = VT.getVectorElementType();
6155     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6156                                       EltVT);
6157     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6158     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6159                                     SignBits.size());
6160     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6161     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6162   }
6163
6164   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6165
6166   // If the logical-not of the result is required, perform that now.
6167   if (Invert)
6168     Result = DAG.getNOT(dl, Result, VT);
6169
6170   return Result;
6171 }
6172
6173 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6174 static bool isX86LogicalCmp(SDValue Op) {
6175   unsigned Opc = Op.getNode()->getOpcode();
6176   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6177     return true;
6178   if (Op.getResNo() == 1 &&
6179       (Opc == X86ISD::ADD ||
6180        Opc == X86ISD::SUB ||
6181        Opc == X86ISD::SMUL ||
6182        Opc == X86ISD::UMUL ||
6183        Opc == X86ISD::INC ||
6184        Opc == X86ISD::DEC ||
6185        Opc == X86ISD::OR ||
6186        Opc == X86ISD::XOR ||
6187        Opc == X86ISD::AND))
6188     return true;
6189
6190   return false;
6191 }
6192
6193 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6194   bool addTest = true;
6195   SDValue Cond  = Op.getOperand(0);
6196   DebugLoc dl = Op.getDebugLoc();
6197   SDValue CC;
6198
6199   if (Cond.getOpcode() == ISD::SETCC) {
6200     SDValue NewCond = LowerSETCC(Cond, DAG);
6201     if (NewCond.getNode())
6202       Cond = NewCond;
6203   }
6204
6205   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6206   SDValue Op1 = Op.getOperand(1);
6207   SDValue Op2 = Op.getOperand(2);
6208   if (Cond.getOpcode() == X86ISD::SETCC &&
6209       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6210     SDValue Cmp = Cond.getOperand(1);
6211     if (Cmp.getOpcode() == X86ISD::CMP) {
6212       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6213       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6214       ConstantSDNode *RHSC =
6215         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6216       if (N1C && N1C->isAllOnesValue() &&
6217           N2C && N2C->isNullValue() &&
6218           RHSC && RHSC->isNullValue()) {
6219         SDValue CmpOp0 = Cmp.getOperand(0);
6220         Cmp = DAG.getNode(X86ISD::CMP, dl, CmpOp0.getValueType(),
6221                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6222         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6223                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6224       }
6225     }
6226   }
6227
6228   // Look pass (and (setcc_carry (cmp ...)), 1).
6229   if (Cond.getOpcode() == ISD::AND &&
6230       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6231     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6232     if (C && C->getAPIntValue() == 1) 
6233       Cond = Cond.getOperand(0);
6234   }
6235
6236   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6237   // setting operand in place of the X86ISD::SETCC.
6238   if (Cond.getOpcode() == X86ISD::SETCC ||
6239       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6240     CC = Cond.getOperand(0);
6241
6242     SDValue Cmp = Cond.getOperand(1);
6243     unsigned Opc = Cmp.getOpcode();
6244     EVT VT = Op.getValueType();
6245
6246     bool IllegalFPCMov = false;
6247     if (VT.isFloatingPoint() && !VT.isVector() &&
6248         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6249       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6250
6251     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6252         Opc == X86ISD::BT) { // FIXME
6253       Cond = Cmp;
6254       addTest = false;
6255     }
6256   }
6257
6258   if (addTest) {
6259     // Look pass the truncate.
6260     if (Cond.getOpcode() == ISD::TRUNCATE)
6261       Cond = Cond.getOperand(0);
6262
6263     // We know the result of AND is compared against zero. Try to match
6264     // it to BT.
6265     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6266       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6267       if (NewSetCC.getNode()) {
6268         CC = NewSetCC.getOperand(0);
6269         Cond = NewSetCC.getOperand(1);
6270         addTest = false;
6271       }
6272     }
6273   }
6274
6275   if (addTest) {
6276     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6277     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6278   }
6279
6280   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6281   // condition is true.
6282   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6283   SDValue Ops[] = { Op2, Op1, CC, Cond };
6284   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6285 }
6286
6287 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6288 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6289 // from the AND / OR.
6290 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6291   Opc = Op.getOpcode();
6292   if (Opc != ISD::OR && Opc != ISD::AND)
6293     return false;
6294   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6295           Op.getOperand(0).hasOneUse() &&
6296           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6297           Op.getOperand(1).hasOneUse());
6298 }
6299
6300 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6301 // 1 and that the SETCC node has a single use.
6302 static bool isXor1OfSetCC(SDValue Op) {
6303   if (Op.getOpcode() != ISD::XOR)
6304     return false;
6305   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6306   if (N1C && N1C->getAPIntValue() == 1) {
6307     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6308       Op.getOperand(0).hasOneUse();
6309   }
6310   return false;
6311 }
6312
6313 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6314   bool addTest = true;
6315   SDValue Chain = Op.getOperand(0);
6316   SDValue Cond  = Op.getOperand(1);
6317   SDValue Dest  = Op.getOperand(2);
6318   DebugLoc dl = Op.getDebugLoc();
6319   SDValue CC;
6320
6321   if (Cond.getOpcode() == ISD::SETCC) {
6322     SDValue NewCond = LowerSETCC(Cond, DAG);
6323     if (NewCond.getNode())
6324       Cond = NewCond;
6325   }
6326 #if 0
6327   // FIXME: LowerXALUO doesn't handle these!!
6328   else if (Cond.getOpcode() == X86ISD::ADD  ||
6329            Cond.getOpcode() == X86ISD::SUB  ||
6330            Cond.getOpcode() == X86ISD::SMUL ||
6331            Cond.getOpcode() == X86ISD::UMUL)
6332     Cond = LowerXALUO(Cond, DAG);
6333 #endif
6334
6335   // Look pass (and (setcc_carry (cmp ...)), 1).
6336   if (Cond.getOpcode() == ISD::AND &&
6337       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6338     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6339     if (C && C->getAPIntValue() == 1) 
6340       Cond = Cond.getOperand(0);
6341   }
6342
6343   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6344   // setting operand in place of the X86ISD::SETCC.
6345   if (Cond.getOpcode() == X86ISD::SETCC ||
6346       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6347     CC = Cond.getOperand(0);
6348
6349     SDValue Cmp = Cond.getOperand(1);
6350     unsigned Opc = Cmp.getOpcode();
6351     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6352     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6353       Cond = Cmp;
6354       addTest = false;
6355     } else {
6356       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6357       default: break;
6358       case X86::COND_O:
6359       case X86::COND_B:
6360         // These can only come from an arithmetic instruction with overflow,
6361         // e.g. SADDO, UADDO.
6362         Cond = Cond.getNode()->getOperand(1);
6363         addTest = false;
6364         break;
6365       }
6366     }
6367   } else {
6368     unsigned CondOpc;
6369     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6370       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6371       if (CondOpc == ISD::OR) {
6372         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6373         // two branches instead of an explicit OR instruction with a
6374         // separate test.
6375         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6376             isX86LogicalCmp(Cmp)) {
6377           CC = Cond.getOperand(0).getOperand(0);
6378           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6379                               Chain, Dest, CC, Cmp);
6380           CC = Cond.getOperand(1).getOperand(0);
6381           Cond = Cmp;
6382           addTest = false;
6383         }
6384       } else { // ISD::AND
6385         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6386         // two branches instead of an explicit AND instruction with a
6387         // separate test. However, we only do this if this block doesn't
6388         // have a fall-through edge, because this requires an explicit
6389         // jmp when the condition is false.
6390         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6391             isX86LogicalCmp(Cmp) &&
6392             Op.getNode()->hasOneUse()) {
6393           X86::CondCode CCode =
6394             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6395           CCode = X86::GetOppositeBranchCondition(CCode);
6396           CC = DAG.getConstant(CCode, MVT::i8);
6397           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6398           // Look for an unconditional branch following this conditional branch.
6399           // We need this because we need to reverse the successors in order
6400           // to implement FCMP_OEQ.
6401           if (User.getOpcode() == ISD::BR) {
6402             SDValue FalseBB = User.getOperand(1);
6403             SDValue NewBR =
6404               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6405             assert(NewBR == User);
6406             Dest = FalseBB;
6407
6408             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6409                                 Chain, Dest, CC, Cmp);
6410             X86::CondCode CCode =
6411               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6412             CCode = X86::GetOppositeBranchCondition(CCode);
6413             CC = DAG.getConstant(CCode, MVT::i8);
6414             Cond = Cmp;
6415             addTest = false;
6416           }
6417         }
6418       }
6419     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6420       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6421       // It should be transformed during dag combiner except when the condition
6422       // is set by a arithmetics with overflow node.
6423       X86::CondCode CCode =
6424         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6425       CCode = X86::GetOppositeBranchCondition(CCode);
6426       CC = DAG.getConstant(CCode, MVT::i8);
6427       Cond = Cond.getOperand(0).getOperand(1);
6428       addTest = false;
6429     }
6430   }
6431
6432   if (addTest) {
6433     // Look pass the truncate.
6434     if (Cond.getOpcode() == ISD::TRUNCATE)
6435       Cond = Cond.getOperand(0);
6436
6437     // We know the result of AND is compared against zero. Try to match
6438     // it to BT.
6439     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6440       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6441       if (NewSetCC.getNode()) {
6442         CC = NewSetCC.getOperand(0);
6443         Cond = NewSetCC.getOperand(1);
6444         addTest = false;
6445       }
6446     }
6447   }
6448
6449   if (addTest) {
6450     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6451     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6452   }
6453   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6454                      Chain, Dest, CC, Cond);
6455 }
6456
6457
6458 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6459 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6460 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6461 // that the guard pages used by the OS virtual memory manager are allocated in
6462 // correct sequence.
6463 SDValue
6464 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6465                                            SelectionDAG &DAG) {
6466   assert(Subtarget->isTargetCygMing() &&
6467          "This should be used only on Cygwin/Mingw targets");
6468   DebugLoc dl = Op.getDebugLoc();
6469
6470   // Get the inputs.
6471   SDValue Chain = Op.getOperand(0);
6472   SDValue Size  = Op.getOperand(1);
6473   // FIXME: Ensure alignment here
6474
6475   SDValue Flag;
6476
6477   EVT IntPtr = getPointerTy();
6478   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6479
6480   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6481   Flag = Chain.getValue(1);
6482
6483   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6484
6485   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6486   Flag = Chain.getValue(1);
6487
6488   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6489
6490   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6491   return DAG.getMergeValues(Ops1, 2, dl);
6492 }
6493
6494 SDValue
6495 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6496                                            SDValue Chain,
6497                                            SDValue Dst, SDValue Src,
6498                                            SDValue Size, unsigned Align,
6499                                            const Value *DstSV,
6500                                            uint64_t DstSVOff) {
6501   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6502
6503   // If not DWORD aligned or size is more than the threshold, call the library.
6504   // The libc version is likely to be faster for these cases. It can use the
6505   // address value and run time information about the CPU.
6506   if ((Align & 3) != 0 ||
6507       !ConstantSize ||
6508       ConstantSize->getZExtValue() >
6509         getSubtarget()->getMaxInlineSizeThreshold()) {
6510     SDValue InFlag(0, 0);
6511
6512     // Check to see if there is a specialized entry-point for memory zeroing.
6513     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6514
6515     if (const char *bzeroEntry =  V &&
6516         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6517       EVT IntPtr = getPointerTy();
6518       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6519       TargetLowering::ArgListTy Args;
6520       TargetLowering::ArgListEntry Entry;
6521       Entry.Node = Dst;
6522       Entry.Ty = IntPtrTy;
6523       Args.push_back(Entry);
6524       Entry.Node = Size;
6525       Args.push_back(Entry);
6526       std::pair<SDValue,SDValue> CallResult =
6527         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6528                     false, false, false, false,
6529                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6530                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6531       return CallResult.second;
6532     }
6533
6534     // Otherwise have the target-independent code call memset.
6535     return SDValue();
6536   }
6537
6538   uint64_t SizeVal = ConstantSize->getZExtValue();
6539   SDValue InFlag(0, 0);
6540   EVT AVT;
6541   SDValue Count;
6542   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6543   unsigned BytesLeft = 0;
6544   bool TwoRepStos = false;
6545   if (ValC) {
6546     unsigned ValReg;
6547     uint64_t Val = ValC->getZExtValue() & 255;
6548
6549     // If the value is a constant, then we can potentially use larger sets.
6550     switch (Align & 3) {
6551     case 2:   // WORD aligned
6552       AVT = MVT::i16;
6553       ValReg = X86::AX;
6554       Val = (Val << 8) | Val;
6555       break;
6556     case 0:  // DWORD aligned
6557       AVT = MVT::i32;
6558       ValReg = X86::EAX;
6559       Val = (Val << 8)  | Val;
6560       Val = (Val << 16) | Val;
6561       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6562         AVT = MVT::i64;
6563         ValReg = X86::RAX;
6564         Val = (Val << 32) | Val;
6565       }
6566       break;
6567     default:  // Byte aligned
6568       AVT = MVT::i8;
6569       ValReg = X86::AL;
6570       Count = DAG.getIntPtrConstant(SizeVal);
6571       break;
6572     }
6573
6574     if (AVT.bitsGT(MVT::i8)) {
6575       unsigned UBytes = AVT.getSizeInBits() / 8;
6576       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6577       BytesLeft = SizeVal % UBytes;
6578     }
6579
6580     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6581                               InFlag);
6582     InFlag = Chain.getValue(1);
6583   } else {
6584     AVT = MVT::i8;
6585     Count  = DAG.getIntPtrConstant(SizeVal);
6586     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6587     InFlag = Chain.getValue(1);
6588   }
6589
6590   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6591                                                               X86::ECX,
6592                             Count, InFlag);
6593   InFlag = Chain.getValue(1);
6594   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6595                                                               X86::EDI,
6596                             Dst, InFlag);
6597   InFlag = Chain.getValue(1);
6598
6599   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6600   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6601   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6602
6603   if (TwoRepStos) {
6604     InFlag = Chain.getValue(1);
6605     Count  = Size;
6606     EVT CVT = Count.getValueType();
6607     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6608                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6609     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6610                                                              X86::ECX,
6611                               Left, InFlag);
6612     InFlag = Chain.getValue(1);
6613     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6614     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6615     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6616   } else if (BytesLeft) {
6617     // Handle the last 1 - 7 bytes.
6618     unsigned Offset = SizeVal - BytesLeft;
6619     EVT AddrVT = Dst.getValueType();
6620     EVT SizeVT = Size.getValueType();
6621
6622     Chain = DAG.getMemset(Chain, dl,
6623                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6624                                       DAG.getConstant(Offset, AddrVT)),
6625                           Src,
6626                           DAG.getConstant(BytesLeft, SizeVT),
6627                           Align, DstSV, DstSVOff + Offset);
6628   }
6629
6630   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6631   return Chain;
6632 }
6633
6634 SDValue
6635 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6636                                       SDValue Chain, SDValue Dst, SDValue Src,
6637                                       SDValue Size, unsigned Align,
6638                                       bool AlwaysInline,
6639                                       const Value *DstSV, uint64_t DstSVOff,
6640                                       const Value *SrcSV, uint64_t SrcSVOff) {
6641   // This requires the copy size to be a constant, preferrably
6642   // within a subtarget-specific limit.
6643   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6644   if (!ConstantSize)
6645     return SDValue();
6646   uint64_t SizeVal = ConstantSize->getZExtValue();
6647   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6648     return SDValue();
6649
6650   /// If not DWORD aligned, call the library.
6651   if ((Align & 3) != 0)
6652     return SDValue();
6653
6654   // DWORD aligned
6655   EVT AVT = MVT::i32;
6656   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6657     AVT = MVT::i64;
6658
6659   unsigned UBytes = AVT.getSizeInBits() / 8;
6660   unsigned CountVal = SizeVal / UBytes;
6661   SDValue Count = DAG.getIntPtrConstant(CountVal);
6662   unsigned BytesLeft = SizeVal % UBytes;
6663
6664   SDValue InFlag(0, 0);
6665   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6666                                                               X86::ECX,
6667                             Count, InFlag);
6668   InFlag = Chain.getValue(1);
6669   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6670                                                              X86::EDI,
6671                             Dst, InFlag);
6672   InFlag = Chain.getValue(1);
6673   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6674                                                               X86::ESI,
6675                             Src, InFlag);
6676   InFlag = Chain.getValue(1);
6677
6678   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6679   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6680   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6681                                 array_lengthof(Ops));
6682
6683   SmallVector<SDValue, 4> Results;
6684   Results.push_back(RepMovs);
6685   if (BytesLeft) {
6686     // Handle the last 1 - 7 bytes.
6687     unsigned Offset = SizeVal - BytesLeft;
6688     EVT DstVT = Dst.getValueType();
6689     EVT SrcVT = Src.getValueType();
6690     EVT SizeVT = Size.getValueType();
6691     Results.push_back(DAG.getMemcpy(Chain, dl,
6692                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6693                                                 DAG.getConstant(Offset, DstVT)),
6694                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6695                                                 DAG.getConstant(Offset, SrcVT)),
6696                                     DAG.getConstant(BytesLeft, SizeVT),
6697                                     Align, AlwaysInline,
6698                                     DstSV, DstSVOff + Offset,
6699                                     SrcSV, SrcSVOff + Offset));
6700   }
6701
6702   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6703                      &Results[0], Results.size());
6704 }
6705
6706 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6707   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6708   DebugLoc dl = Op.getDebugLoc();
6709
6710   if (!Subtarget->is64Bit()) {
6711     // vastart just stores the address of the VarArgsFrameIndex slot into the
6712     // memory location argument.
6713     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6714     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6715                         false, false, 0);
6716   }
6717
6718   // __va_list_tag:
6719   //   gp_offset         (0 - 6 * 8)
6720   //   fp_offset         (48 - 48 + 8 * 16)
6721   //   overflow_arg_area (point to parameters coming in memory).
6722   //   reg_save_area
6723   SmallVector<SDValue, 8> MemOps;
6724   SDValue FIN = Op.getOperand(1);
6725   // Store gp_offset
6726   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6727                                DAG.getConstant(VarArgsGPOffset, MVT::i32),
6728                                FIN, SV, 0, false, false, 0);
6729   MemOps.push_back(Store);
6730
6731   // Store fp_offset
6732   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6733                     FIN, DAG.getIntPtrConstant(4));
6734   Store = DAG.getStore(Op.getOperand(0), dl,
6735                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6736                        FIN, SV, 0, false, false, 0);
6737   MemOps.push_back(Store);
6738
6739   // Store ptr to overflow_arg_area
6740   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6741                     FIN, DAG.getIntPtrConstant(4));
6742   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6743   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6744                        false, false, 0);
6745   MemOps.push_back(Store);
6746
6747   // Store ptr to reg_save_area.
6748   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6749                     FIN, DAG.getIntPtrConstant(8));
6750   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6751   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6752                        false, false, 0);
6753   MemOps.push_back(Store);
6754   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6755                      &MemOps[0], MemOps.size());
6756 }
6757
6758 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6759   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6760   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6761   SDValue Chain = Op.getOperand(0);
6762   SDValue SrcPtr = Op.getOperand(1);
6763   SDValue SrcSV = Op.getOperand(2);
6764
6765   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6766   return SDValue();
6767 }
6768
6769 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6770   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6771   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6772   SDValue Chain = Op.getOperand(0);
6773   SDValue DstPtr = Op.getOperand(1);
6774   SDValue SrcPtr = Op.getOperand(2);
6775   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6776   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6777   DebugLoc dl = Op.getDebugLoc();
6778
6779   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6780                        DAG.getIntPtrConstant(24), 8, false,
6781                        DstSV, 0, SrcSV, 0);
6782 }
6783
6784 SDValue
6785 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6786   DebugLoc dl = Op.getDebugLoc();
6787   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6788   switch (IntNo) {
6789   default: return SDValue();    // Don't custom lower most intrinsics.
6790   // Comparison intrinsics.
6791   case Intrinsic::x86_sse_comieq_ss:
6792   case Intrinsic::x86_sse_comilt_ss:
6793   case Intrinsic::x86_sse_comile_ss:
6794   case Intrinsic::x86_sse_comigt_ss:
6795   case Intrinsic::x86_sse_comige_ss:
6796   case Intrinsic::x86_sse_comineq_ss:
6797   case Intrinsic::x86_sse_ucomieq_ss:
6798   case Intrinsic::x86_sse_ucomilt_ss:
6799   case Intrinsic::x86_sse_ucomile_ss:
6800   case Intrinsic::x86_sse_ucomigt_ss:
6801   case Intrinsic::x86_sse_ucomige_ss:
6802   case Intrinsic::x86_sse_ucomineq_ss:
6803   case Intrinsic::x86_sse2_comieq_sd:
6804   case Intrinsic::x86_sse2_comilt_sd:
6805   case Intrinsic::x86_sse2_comile_sd:
6806   case Intrinsic::x86_sse2_comigt_sd:
6807   case Intrinsic::x86_sse2_comige_sd:
6808   case Intrinsic::x86_sse2_comineq_sd:
6809   case Intrinsic::x86_sse2_ucomieq_sd:
6810   case Intrinsic::x86_sse2_ucomilt_sd:
6811   case Intrinsic::x86_sse2_ucomile_sd:
6812   case Intrinsic::x86_sse2_ucomigt_sd:
6813   case Intrinsic::x86_sse2_ucomige_sd:
6814   case Intrinsic::x86_sse2_ucomineq_sd: {
6815     unsigned Opc = 0;
6816     ISD::CondCode CC = ISD::SETCC_INVALID;
6817     switch (IntNo) {
6818     default: break;
6819     case Intrinsic::x86_sse_comieq_ss:
6820     case Intrinsic::x86_sse2_comieq_sd:
6821       Opc = X86ISD::COMI;
6822       CC = ISD::SETEQ;
6823       break;
6824     case Intrinsic::x86_sse_comilt_ss:
6825     case Intrinsic::x86_sse2_comilt_sd:
6826       Opc = X86ISD::COMI;
6827       CC = ISD::SETLT;
6828       break;
6829     case Intrinsic::x86_sse_comile_ss:
6830     case Intrinsic::x86_sse2_comile_sd:
6831       Opc = X86ISD::COMI;
6832       CC = ISD::SETLE;
6833       break;
6834     case Intrinsic::x86_sse_comigt_ss:
6835     case Intrinsic::x86_sse2_comigt_sd:
6836       Opc = X86ISD::COMI;
6837       CC = ISD::SETGT;
6838       break;
6839     case Intrinsic::x86_sse_comige_ss:
6840     case Intrinsic::x86_sse2_comige_sd:
6841       Opc = X86ISD::COMI;
6842       CC = ISD::SETGE;
6843       break;
6844     case Intrinsic::x86_sse_comineq_ss:
6845     case Intrinsic::x86_sse2_comineq_sd:
6846       Opc = X86ISD::COMI;
6847       CC = ISD::SETNE;
6848       break;
6849     case Intrinsic::x86_sse_ucomieq_ss:
6850     case Intrinsic::x86_sse2_ucomieq_sd:
6851       Opc = X86ISD::UCOMI;
6852       CC = ISD::SETEQ;
6853       break;
6854     case Intrinsic::x86_sse_ucomilt_ss:
6855     case Intrinsic::x86_sse2_ucomilt_sd:
6856       Opc = X86ISD::UCOMI;
6857       CC = ISD::SETLT;
6858       break;
6859     case Intrinsic::x86_sse_ucomile_ss:
6860     case Intrinsic::x86_sse2_ucomile_sd:
6861       Opc = X86ISD::UCOMI;
6862       CC = ISD::SETLE;
6863       break;
6864     case Intrinsic::x86_sse_ucomigt_ss:
6865     case Intrinsic::x86_sse2_ucomigt_sd:
6866       Opc = X86ISD::UCOMI;
6867       CC = ISD::SETGT;
6868       break;
6869     case Intrinsic::x86_sse_ucomige_ss:
6870     case Intrinsic::x86_sse2_ucomige_sd:
6871       Opc = X86ISD::UCOMI;
6872       CC = ISD::SETGE;
6873       break;
6874     case Intrinsic::x86_sse_ucomineq_ss:
6875     case Intrinsic::x86_sse2_ucomineq_sd:
6876       Opc = X86ISD::UCOMI;
6877       CC = ISD::SETNE;
6878       break;
6879     }
6880
6881     SDValue LHS = Op.getOperand(1);
6882     SDValue RHS = Op.getOperand(2);
6883     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6884     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6885     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6886     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6887                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6888     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6889   }
6890   // ptest intrinsics. The intrinsic these come from are designed to return
6891   // an integer value, not just an instruction so lower it to the ptest
6892   // pattern and a setcc for the result.
6893   case Intrinsic::x86_sse41_ptestz:
6894   case Intrinsic::x86_sse41_ptestc:
6895   case Intrinsic::x86_sse41_ptestnzc:{
6896     unsigned X86CC = 0;
6897     switch (IntNo) {
6898     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6899     case Intrinsic::x86_sse41_ptestz:
6900       // ZF = 1
6901       X86CC = X86::COND_E;
6902       break;
6903     case Intrinsic::x86_sse41_ptestc:
6904       // CF = 1
6905       X86CC = X86::COND_B;
6906       break;
6907     case Intrinsic::x86_sse41_ptestnzc:
6908       // ZF and CF = 0
6909       X86CC = X86::COND_A;
6910       break;
6911     }
6912
6913     SDValue LHS = Op.getOperand(1);
6914     SDValue RHS = Op.getOperand(2);
6915     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6916     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6917     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6918     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6919   }
6920
6921   // Fix vector shift instructions where the last operand is a non-immediate
6922   // i32 value.
6923   case Intrinsic::x86_sse2_pslli_w:
6924   case Intrinsic::x86_sse2_pslli_d:
6925   case Intrinsic::x86_sse2_pslli_q:
6926   case Intrinsic::x86_sse2_psrli_w:
6927   case Intrinsic::x86_sse2_psrli_d:
6928   case Intrinsic::x86_sse2_psrli_q:
6929   case Intrinsic::x86_sse2_psrai_w:
6930   case Intrinsic::x86_sse2_psrai_d:
6931   case Intrinsic::x86_mmx_pslli_w:
6932   case Intrinsic::x86_mmx_pslli_d:
6933   case Intrinsic::x86_mmx_pslli_q:
6934   case Intrinsic::x86_mmx_psrli_w:
6935   case Intrinsic::x86_mmx_psrli_d:
6936   case Intrinsic::x86_mmx_psrli_q:
6937   case Intrinsic::x86_mmx_psrai_w:
6938   case Intrinsic::x86_mmx_psrai_d: {
6939     SDValue ShAmt = Op.getOperand(2);
6940     if (isa<ConstantSDNode>(ShAmt))
6941       return SDValue();
6942
6943     unsigned NewIntNo = 0;
6944     EVT ShAmtVT = MVT::v4i32;
6945     switch (IntNo) {
6946     case Intrinsic::x86_sse2_pslli_w:
6947       NewIntNo = Intrinsic::x86_sse2_psll_w;
6948       break;
6949     case Intrinsic::x86_sse2_pslli_d:
6950       NewIntNo = Intrinsic::x86_sse2_psll_d;
6951       break;
6952     case Intrinsic::x86_sse2_pslli_q:
6953       NewIntNo = Intrinsic::x86_sse2_psll_q;
6954       break;
6955     case Intrinsic::x86_sse2_psrli_w:
6956       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6957       break;
6958     case Intrinsic::x86_sse2_psrli_d:
6959       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6960       break;
6961     case Intrinsic::x86_sse2_psrli_q:
6962       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6963       break;
6964     case Intrinsic::x86_sse2_psrai_w:
6965       NewIntNo = Intrinsic::x86_sse2_psra_w;
6966       break;
6967     case Intrinsic::x86_sse2_psrai_d:
6968       NewIntNo = Intrinsic::x86_sse2_psra_d;
6969       break;
6970     default: {
6971       ShAmtVT = MVT::v2i32;
6972       switch (IntNo) {
6973       case Intrinsic::x86_mmx_pslli_w:
6974         NewIntNo = Intrinsic::x86_mmx_psll_w;
6975         break;
6976       case Intrinsic::x86_mmx_pslli_d:
6977         NewIntNo = Intrinsic::x86_mmx_psll_d;
6978         break;
6979       case Intrinsic::x86_mmx_pslli_q:
6980         NewIntNo = Intrinsic::x86_mmx_psll_q;
6981         break;
6982       case Intrinsic::x86_mmx_psrli_w:
6983         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6984         break;
6985       case Intrinsic::x86_mmx_psrli_d:
6986         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6987         break;
6988       case Intrinsic::x86_mmx_psrli_q:
6989         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6990         break;
6991       case Intrinsic::x86_mmx_psrai_w:
6992         NewIntNo = Intrinsic::x86_mmx_psra_w;
6993         break;
6994       case Intrinsic::x86_mmx_psrai_d:
6995         NewIntNo = Intrinsic::x86_mmx_psra_d;
6996         break;
6997       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6998       }
6999       break;
7000     }
7001     }
7002
7003     // The vector shift intrinsics with scalars uses 32b shift amounts but
7004     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7005     // to be zero.
7006     SDValue ShOps[4];
7007     ShOps[0] = ShAmt;
7008     ShOps[1] = DAG.getConstant(0, MVT::i32);
7009     if (ShAmtVT == MVT::v4i32) {
7010       ShOps[2] = DAG.getUNDEF(MVT::i32);
7011       ShOps[3] = DAG.getUNDEF(MVT::i32);
7012       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7013     } else {
7014       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7015     }
7016
7017     EVT VT = Op.getValueType();
7018     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7019     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7020                        DAG.getConstant(NewIntNo, MVT::i32),
7021                        Op.getOperand(1), ShAmt);
7022   }
7023   }
7024 }
7025
7026 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7027   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7028   DebugLoc dl = Op.getDebugLoc();
7029
7030   if (Depth > 0) {
7031     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7032     SDValue Offset =
7033       DAG.getConstant(TD->getPointerSize(),
7034                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7035     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7036                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7037                                    FrameAddr, Offset),
7038                        NULL, 0, false, false, 0);
7039   }
7040
7041   // Just load the return address.
7042   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7043   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7044                      RetAddrFI, NULL, 0, false, false, 0);
7045 }
7046
7047 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7048   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7049   MFI->setFrameAddressIsTaken(true);
7050   EVT VT = Op.getValueType();
7051   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7052   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7053   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7054   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7055   while (Depth--)
7056     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7057                             false, false, 0);
7058   return FrameAddr;
7059 }
7060
7061 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7062                                                      SelectionDAG &DAG) {
7063   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7064 }
7065
7066 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7067 {
7068   MachineFunction &MF = DAG.getMachineFunction();
7069   SDValue Chain     = Op.getOperand(0);
7070   SDValue Offset    = Op.getOperand(1);
7071   SDValue Handler   = Op.getOperand(2);
7072   DebugLoc dl       = Op.getDebugLoc();
7073
7074   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7075                                   getPointerTy());
7076   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7077
7078   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7079                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7080   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7081   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7082   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7083   MF.getRegInfo().addLiveOut(StoreAddrReg);
7084
7085   return DAG.getNode(X86ISD::EH_RETURN, dl,
7086                      MVT::Other,
7087                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7088 }
7089
7090 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7091                                              SelectionDAG &DAG) {
7092   SDValue Root = Op.getOperand(0);
7093   SDValue Trmp = Op.getOperand(1); // trampoline
7094   SDValue FPtr = Op.getOperand(2); // nested function
7095   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7096   DebugLoc dl  = Op.getDebugLoc();
7097
7098   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7099
7100   if (Subtarget->is64Bit()) {
7101     SDValue OutChains[6];
7102
7103     // Large code-model.
7104     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7105     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7106
7107     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7108     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7109
7110     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7111
7112     // Load the pointer to the nested function into R11.
7113     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7114     SDValue Addr = Trmp;
7115     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7116                                 Addr, TrmpAddr, 0, false, false, 0);
7117
7118     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7119                        DAG.getConstant(2, MVT::i64));
7120     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7121                                 false, false, 2);
7122
7123     // Load the 'nest' parameter value into R10.
7124     // R10 is specified in X86CallingConv.td
7125     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7126     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7127                        DAG.getConstant(10, MVT::i64));
7128     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7129                                 Addr, TrmpAddr, 10, false, false, 0);
7130
7131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7132                        DAG.getConstant(12, MVT::i64));
7133     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7134                                 false, false, 2);
7135
7136     // Jump to the nested function.
7137     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7138     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7139                        DAG.getConstant(20, MVT::i64));
7140     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7141                                 Addr, TrmpAddr, 20, false, false, 0);
7142
7143     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7144     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7145                        DAG.getConstant(22, MVT::i64));
7146     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7147                                 TrmpAddr, 22, false, false, 0);
7148
7149     SDValue Ops[] =
7150       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7151     return DAG.getMergeValues(Ops, 2, dl);
7152   } else {
7153     const Function *Func =
7154       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7155     CallingConv::ID CC = Func->getCallingConv();
7156     unsigned NestReg;
7157
7158     switch (CC) {
7159     default:
7160       llvm_unreachable("Unsupported calling convention");
7161     case CallingConv::C:
7162     case CallingConv::X86_StdCall: {
7163       // Pass 'nest' parameter in ECX.
7164       // Must be kept in sync with X86CallingConv.td
7165       NestReg = X86::ECX;
7166
7167       // Check that ECX wasn't needed by an 'inreg' parameter.
7168       const FunctionType *FTy = Func->getFunctionType();
7169       const AttrListPtr &Attrs = Func->getAttributes();
7170
7171       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7172         unsigned InRegCount = 0;
7173         unsigned Idx = 1;
7174
7175         for (FunctionType::param_iterator I = FTy->param_begin(),
7176              E = FTy->param_end(); I != E; ++I, ++Idx)
7177           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7178             // FIXME: should only count parameters that are lowered to integers.
7179             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7180
7181         if (InRegCount > 2) {
7182           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7183         }
7184       }
7185       break;
7186     }
7187     case CallingConv::X86_FastCall:
7188     case CallingConv::Fast:
7189       // Pass 'nest' parameter in EAX.
7190       // Must be kept in sync with X86CallingConv.td
7191       NestReg = X86::EAX;
7192       break;
7193     }
7194
7195     SDValue OutChains[4];
7196     SDValue Addr, Disp;
7197
7198     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7199                        DAG.getConstant(10, MVT::i32));
7200     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7201
7202     // This is storing the opcode for MOV32ri.
7203     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7204     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7205     OutChains[0] = DAG.getStore(Root, dl,
7206                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7207                                 Trmp, TrmpAddr, 0, false, false, 0);
7208
7209     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7210                        DAG.getConstant(1, MVT::i32));
7211     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7212                                 false, false, 1);
7213
7214     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7215     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7216                        DAG.getConstant(5, MVT::i32));
7217     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7218                                 TrmpAddr, 5, false, false, 1);
7219
7220     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7221                        DAG.getConstant(6, MVT::i32));
7222     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7223                                 false, false, 1);
7224
7225     SDValue Ops[] =
7226       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7227     return DAG.getMergeValues(Ops, 2, dl);
7228   }
7229 }
7230
7231 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7232   /*
7233    The rounding mode is in bits 11:10 of FPSR, and has the following
7234    settings:
7235      00 Round to nearest
7236      01 Round to -inf
7237      10 Round to +inf
7238      11 Round to 0
7239
7240   FLT_ROUNDS, on the other hand, expects the following:
7241     -1 Undefined
7242      0 Round to 0
7243      1 Round to nearest
7244      2 Round to +inf
7245      3 Round to -inf
7246
7247   To perform the conversion, we do:
7248     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7249   */
7250
7251   MachineFunction &MF = DAG.getMachineFunction();
7252   const TargetMachine &TM = MF.getTarget();
7253   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7254   unsigned StackAlignment = TFI.getStackAlignment();
7255   EVT VT = Op.getValueType();
7256   DebugLoc dl = Op.getDebugLoc();
7257
7258   // Save FP Control Word to stack slot
7259   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7260   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7261
7262   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7263                               DAG.getEntryNode(), StackSlot);
7264
7265   // Load FP Control Word from stack slot
7266   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7267                             false, false, 0);
7268
7269   // Transform as necessary
7270   SDValue CWD1 =
7271     DAG.getNode(ISD::SRL, dl, MVT::i16,
7272                 DAG.getNode(ISD::AND, dl, MVT::i16,
7273                             CWD, DAG.getConstant(0x800, MVT::i16)),
7274                 DAG.getConstant(11, MVT::i8));
7275   SDValue CWD2 =
7276     DAG.getNode(ISD::SRL, dl, MVT::i16,
7277                 DAG.getNode(ISD::AND, dl, MVT::i16,
7278                             CWD, DAG.getConstant(0x400, MVT::i16)),
7279                 DAG.getConstant(9, MVT::i8));
7280
7281   SDValue RetVal =
7282     DAG.getNode(ISD::AND, dl, MVT::i16,
7283                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7284                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7285                             DAG.getConstant(1, MVT::i16)),
7286                 DAG.getConstant(3, MVT::i16));
7287
7288
7289   return DAG.getNode((VT.getSizeInBits() < 16 ?
7290                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7291 }
7292
7293 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7294   EVT VT = Op.getValueType();
7295   EVT OpVT = VT;
7296   unsigned NumBits = VT.getSizeInBits();
7297   DebugLoc dl = Op.getDebugLoc();
7298
7299   Op = Op.getOperand(0);
7300   if (VT == MVT::i8) {
7301     // Zero extend to i32 since there is not an i8 bsr.
7302     OpVT = MVT::i32;
7303     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7304   }
7305
7306   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7307   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7308   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7309
7310   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7311   SDValue Ops[] = {
7312     Op,
7313     DAG.getConstant(NumBits+NumBits-1, OpVT),
7314     DAG.getConstant(X86::COND_E, MVT::i8),
7315     Op.getValue(1)
7316   };
7317   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7318
7319   // Finally xor with NumBits-1.
7320   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7321
7322   if (VT == MVT::i8)
7323     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7324   return Op;
7325 }
7326
7327 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7328   EVT VT = Op.getValueType();
7329   EVT OpVT = VT;
7330   unsigned NumBits = VT.getSizeInBits();
7331   DebugLoc dl = Op.getDebugLoc();
7332
7333   Op = Op.getOperand(0);
7334   if (VT == MVT::i8) {
7335     OpVT = MVT::i32;
7336     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7337   }
7338
7339   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7340   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7341   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7342
7343   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7344   SDValue Ops[] = {
7345     Op,
7346     DAG.getConstant(NumBits, OpVT),
7347     DAG.getConstant(X86::COND_E, MVT::i8),
7348     Op.getValue(1)
7349   };
7350   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7351
7352   if (VT == MVT::i8)
7353     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7354   return Op;
7355 }
7356
7357 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7358   EVT VT = Op.getValueType();
7359   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7360   DebugLoc dl = Op.getDebugLoc();
7361
7362   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7363   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7364   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7365   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7366   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7367   //
7368   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7369   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7370   //  return AloBlo + AloBhi + AhiBlo;
7371
7372   SDValue A = Op.getOperand(0);
7373   SDValue B = Op.getOperand(1);
7374
7375   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7376                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7377                        A, DAG.getConstant(32, MVT::i32));
7378   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7379                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7380                        B, DAG.getConstant(32, MVT::i32));
7381   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7382                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7383                        A, B);
7384   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7385                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7386                        A, Bhi);
7387   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7388                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7389                        Ahi, B);
7390   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7391                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7392                        AloBhi, DAG.getConstant(32, MVT::i32));
7393   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7394                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7395                        AhiBlo, DAG.getConstant(32, MVT::i32));
7396   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7397   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7398   return Res;
7399 }
7400
7401
7402 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7403   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7404   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7405   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7406   // has only one use.
7407   SDNode *N = Op.getNode();
7408   SDValue LHS = N->getOperand(0);
7409   SDValue RHS = N->getOperand(1);
7410   unsigned BaseOp = 0;
7411   unsigned Cond = 0;
7412   DebugLoc dl = Op.getDebugLoc();
7413
7414   switch (Op.getOpcode()) {
7415   default: llvm_unreachable("Unknown ovf instruction!");
7416   case ISD::SADDO:
7417     // A subtract of one will be selected as a INC. Note that INC doesn't
7418     // set CF, so we can't do this for UADDO.
7419     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7420       if (C->getAPIntValue() == 1) {
7421         BaseOp = X86ISD::INC;
7422         Cond = X86::COND_O;
7423         break;
7424       }
7425     BaseOp = X86ISD::ADD;
7426     Cond = X86::COND_O;
7427     break;
7428   case ISD::UADDO:
7429     BaseOp = X86ISD::ADD;
7430     Cond = X86::COND_B;
7431     break;
7432   case ISD::SSUBO:
7433     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7434     // set CF, so we can't do this for USUBO.
7435     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7436       if (C->getAPIntValue() == 1) {
7437         BaseOp = X86ISD::DEC;
7438         Cond = X86::COND_O;
7439         break;
7440       }
7441     BaseOp = X86ISD::SUB;
7442     Cond = X86::COND_O;
7443     break;
7444   case ISD::USUBO:
7445     BaseOp = X86ISD::SUB;
7446     Cond = X86::COND_B;
7447     break;
7448   case ISD::SMULO:
7449     BaseOp = X86ISD::SMUL;
7450     Cond = X86::COND_O;
7451     break;
7452   case ISD::UMULO:
7453     BaseOp = X86ISD::UMUL;
7454     Cond = X86::COND_B;
7455     break;
7456   }
7457
7458   // Also sets EFLAGS.
7459   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7460   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7461
7462   SDValue SetCC =
7463     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7464                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7465
7466   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7467   return Sum;
7468 }
7469
7470 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7471   EVT T = Op.getValueType();
7472   DebugLoc dl = Op.getDebugLoc();
7473   unsigned Reg = 0;
7474   unsigned size = 0;
7475   switch(T.getSimpleVT().SimpleTy) {
7476   default:
7477     assert(false && "Invalid value type!");
7478   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7479   case MVT::i16: Reg = X86::AX;  size = 2; break;
7480   case MVT::i32: Reg = X86::EAX; size = 4; break;
7481   case MVT::i64:
7482     assert(Subtarget->is64Bit() && "Node not type legal!");
7483     Reg = X86::RAX; size = 8;
7484     break;
7485   }
7486   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7487                                     Op.getOperand(2), SDValue());
7488   SDValue Ops[] = { cpIn.getValue(0),
7489                     Op.getOperand(1),
7490                     Op.getOperand(3),
7491                     DAG.getTargetConstant(size, MVT::i8),
7492                     cpIn.getValue(1) };
7493   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7494   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7495   SDValue cpOut =
7496     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7497   return cpOut;
7498 }
7499
7500 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7501                                                  SelectionDAG &DAG) {
7502   assert(Subtarget->is64Bit() && "Result not type legalized?");
7503   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7504   SDValue TheChain = Op.getOperand(0);
7505   DebugLoc dl = Op.getDebugLoc();
7506   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7507   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7508   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7509                                    rax.getValue(2));
7510   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7511                             DAG.getConstant(32, MVT::i8));
7512   SDValue Ops[] = {
7513     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7514     rdx.getValue(1)
7515   };
7516   return DAG.getMergeValues(Ops, 2, dl);
7517 }
7518
7519 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7520   SDNode *Node = Op.getNode();
7521   DebugLoc dl = Node->getDebugLoc();
7522   EVT T = Node->getValueType(0);
7523   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7524                               DAG.getConstant(0, T), Node->getOperand(2));
7525   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7526                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7527                        Node->getOperand(0),
7528                        Node->getOperand(1), negOp,
7529                        cast<AtomicSDNode>(Node)->getSrcValue(),
7530                        cast<AtomicSDNode>(Node)->getAlignment());
7531 }
7532
7533 /// LowerOperation - Provide custom lowering hooks for some operations.
7534 ///
7535 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7536   switch (Op.getOpcode()) {
7537   default: llvm_unreachable("Should not custom lower this!");
7538   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7539   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7540   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7541   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7542   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7543   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7544   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7545   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7546   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7547   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7548   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7549   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7550   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7551   case ISD::SHL_PARTS:
7552   case ISD::SRA_PARTS:
7553   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7554   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7555   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7556   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7557   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7558   case ISD::FABS:               return LowerFABS(Op, DAG);
7559   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7560   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7561   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7562   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7563   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7564   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7565   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7566   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7567   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7568   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7569   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7570   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7571   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7572   case ISD::FRAME_TO_ARGS_OFFSET:
7573                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7574   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7575   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7576   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7577   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7578   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7579   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7580   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7581   case ISD::SADDO:
7582   case ISD::UADDO:
7583   case ISD::SSUBO:
7584   case ISD::USUBO:
7585   case ISD::SMULO:
7586   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7587   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7588   }
7589 }
7590
7591 void X86TargetLowering::
7592 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7593                         SelectionDAG &DAG, unsigned NewOp) {
7594   EVT T = Node->getValueType(0);
7595   DebugLoc dl = Node->getDebugLoc();
7596   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7597
7598   SDValue Chain = Node->getOperand(0);
7599   SDValue In1 = Node->getOperand(1);
7600   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7601                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7602   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7603                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7604   SDValue Ops[] = { Chain, In1, In2L, In2H };
7605   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7606   SDValue Result =
7607     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7608                             cast<MemSDNode>(Node)->getMemOperand());
7609   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7610   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7611   Results.push_back(Result.getValue(2));
7612 }
7613
7614 /// ReplaceNodeResults - Replace a node with an illegal result type
7615 /// with a new node built out of custom code.
7616 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7617                                            SmallVectorImpl<SDValue>&Results,
7618                                            SelectionDAG &DAG) {
7619   DebugLoc dl = N->getDebugLoc();
7620   switch (N->getOpcode()) {
7621   default:
7622     assert(false && "Do not know how to custom type legalize this operation!");
7623     return;
7624   case ISD::FP_TO_SINT: {
7625     std::pair<SDValue,SDValue> Vals =
7626         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7627     SDValue FIST = Vals.first, StackSlot = Vals.second;
7628     if (FIST.getNode() != 0) {
7629       EVT VT = N->getValueType(0);
7630       // Return a load from the stack slot.
7631       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7632                                     false, false, 0));
7633     }
7634     return;
7635   }
7636   case ISD::READCYCLECOUNTER: {
7637     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7638     SDValue TheChain = N->getOperand(0);
7639     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7640     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7641                                      rd.getValue(1));
7642     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7643                                      eax.getValue(2));
7644     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7645     SDValue Ops[] = { eax, edx };
7646     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7647     Results.push_back(edx.getValue(1));
7648     return;
7649   }
7650   case ISD::ATOMIC_CMP_SWAP: {
7651     EVT T = N->getValueType(0);
7652     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7653     SDValue cpInL, cpInH;
7654     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7655                         DAG.getConstant(0, MVT::i32));
7656     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7657                         DAG.getConstant(1, MVT::i32));
7658     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7659     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7660                              cpInL.getValue(1));
7661     SDValue swapInL, swapInH;
7662     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7663                           DAG.getConstant(0, MVT::i32));
7664     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7665                           DAG.getConstant(1, MVT::i32));
7666     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7667                                cpInH.getValue(1));
7668     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7669                                swapInL.getValue(1));
7670     SDValue Ops[] = { swapInH.getValue(0),
7671                       N->getOperand(1),
7672                       swapInH.getValue(1) };
7673     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7674     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7675     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7676                                         MVT::i32, Result.getValue(1));
7677     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7678                                         MVT::i32, cpOutL.getValue(2));
7679     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7680     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7681     Results.push_back(cpOutH.getValue(1));
7682     return;
7683   }
7684   case ISD::ATOMIC_LOAD_ADD:
7685     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7686     return;
7687   case ISD::ATOMIC_LOAD_AND:
7688     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7689     return;
7690   case ISD::ATOMIC_LOAD_NAND:
7691     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7692     return;
7693   case ISD::ATOMIC_LOAD_OR:
7694     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7695     return;
7696   case ISD::ATOMIC_LOAD_SUB:
7697     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7698     return;
7699   case ISD::ATOMIC_LOAD_XOR:
7700     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7701     return;
7702   case ISD::ATOMIC_SWAP:
7703     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7704     return;
7705   }
7706 }
7707
7708 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7709   switch (Opcode) {
7710   default: return NULL;
7711   case X86ISD::BSF:                return "X86ISD::BSF";
7712   case X86ISD::BSR:                return "X86ISD::BSR";
7713   case X86ISD::SHLD:               return "X86ISD::SHLD";
7714   case X86ISD::SHRD:               return "X86ISD::SHRD";
7715   case X86ISD::FAND:               return "X86ISD::FAND";
7716   case X86ISD::FOR:                return "X86ISD::FOR";
7717   case X86ISD::FXOR:               return "X86ISD::FXOR";
7718   case X86ISD::FSRL:               return "X86ISD::FSRL";
7719   case X86ISD::FILD:               return "X86ISD::FILD";
7720   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7721   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7722   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7723   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7724   case X86ISD::FLD:                return "X86ISD::FLD";
7725   case X86ISD::FST:                return "X86ISD::FST";
7726   case X86ISD::CALL:               return "X86ISD::CALL";
7727   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7728   case X86ISD::BT:                 return "X86ISD::BT";
7729   case X86ISD::CMP:                return "X86ISD::CMP";
7730   case X86ISD::COMI:               return "X86ISD::COMI";
7731   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7732   case X86ISD::SETCC:              return "X86ISD::SETCC";
7733   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7734   case X86ISD::CMOV:               return "X86ISD::CMOV";
7735   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7736   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7737   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7738   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7739   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7740   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7741   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7742   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7743   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7744   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7745   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7746   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7747   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7748   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7749   case X86ISD::FMAX:               return "X86ISD::FMAX";
7750   case X86ISD::FMIN:               return "X86ISD::FMIN";
7751   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7752   case X86ISD::FRCP:               return "X86ISD::FRCP";
7753   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7754   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7755   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7756   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7757   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7758   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7759   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7760   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7761   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7762   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7763   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7764   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7765   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7766   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7767   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7768   case X86ISD::VSHL:               return "X86ISD::VSHL";
7769   case X86ISD::VSRL:               return "X86ISD::VSRL";
7770   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7771   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7772   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7773   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7774   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7775   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7776   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7777   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7778   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7779   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7780   case X86ISD::ADD:                return "X86ISD::ADD";
7781   case X86ISD::SUB:                return "X86ISD::SUB";
7782   case X86ISD::SMUL:               return "X86ISD::SMUL";
7783   case X86ISD::UMUL:               return "X86ISD::UMUL";
7784   case X86ISD::INC:                return "X86ISD::INC";
7785   case X86ISD::DEC:                return "X86ISD::DEC";
7786   case X86ISD::OR:                 return "X86ISD::OR";
7787   case X86ISD::XOR:                return "X86ISD::XOR";
7788   case X86ISD::AND:                return "X86ISD::AND";
7789   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7790   case X86ISD::PTEST:              return "X86ISD::PTEST";
7791   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7792   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7793   }
7794 }
7795
7796 // isLegalAddressingMode - Return true if the addressing mode represented
7797 // by AM is legal for this target, for a load/store of the specified type.
7798 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7799                                               const Type *Ty) const {
7800   // X86 supports extremely general addressing modes.
7801   CodeModel::Model M = getTargetMachine().getCodeModel();
7802
7803   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7804   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7805     return false;
7806
7807   if (AM.BaseGV) {
7808     unsigned GVFlags =
7809       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7810
7811     // If a reference to this global requires an extra load, we can't fold it.
7812     if (isGlobalStubReference(GVFlags))
7813       return false;
7814
7815     // If BaseGV requires a register for the PIC base, we cannot also have a
7816     // BaseReg specified.
7817     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7818       return false;
7819
7820     // If lower 4G is not available, then we must use rip-relative addressing.
7821     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7822       return false;
7823   }
7824
7825   switch (AM.Scale) {
7826   case 0:
7827   case 1:
7828   case 2:
7829   case 4:
7830   case 8:
7831     // These scales always work.
7832     break;
7833   case 3:
7834   case 5:
7835   case 9:
7836     // These scales are formed with basereg+scalereg.  Only accept if there is
7837     // no basereg yet.
7838     if (AM.HasBaseReg)
7839       return false;
7840     break;
7841   default:  // Other stuff never works.
7842     return false;
7843   }
7844
7845   return true;
7846 }
7847
7848
7849 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7850   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7851     return false;
7852   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7853   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7854   if (NumBits1 <= NumBits2)
7855     return false;
7856   return true;
7857 }
7858
7859 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7860   if (!VT1.isInteger() || !VT2.isInteger())
7861     return false;
7862   unsigned NumBits1 = VT1.getSizeInBits();
7863   unsigned NumBits2 = VT2.getSizeInBits();
7864   if (NumBits1 <= NumBits2)
7865     return false;
7866   return true;
7867 }
7868
7869 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7870   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7871   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7872 }
7873
7874 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7875   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7876   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7877 }
7878
7879 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7880   // i16 instructions are longer (0x66 prefix) and potentially slower.
7881   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7882 }
7883
7884 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7885 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7886 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7887 /// are assumed to be legal.
7888 bool
7889 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7890                                       EVT VT) const {
7891   // Only do shuffles on 128-bit vector types for now.
7892   if (VT.getSizeInBits() == 64)
7893     return false;
7894
7895   // FIXME: pshufb, blends, shifts.
7896   return (VT.getVectorNumElements() == 2 ||
7897           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7898           isMOVLMask(M, VT) ||
7899           isSHUFPMask(M, VT) ||
7900           isPSHUFDMask(M, VT) ||
7901           isPSHUFHWMask(M, VT) ||
7902           isPSHUFLWMask(M, VT) ||
7903           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7904           isUNPCKLMask(M, VT) ||
7905           isUNPCKHMask(M, VT) ||
7906           isUNPCKL_v_undef_Mask(M, VT) ||
7907           isUNPCKH_v_undef_Mask(M, VT));
7908 }
7909
7910 bool
7911 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7912                                           EVT VT) const {
7913   unsigned NumElts = VT.getVectorNumElements();
7914   // FIXME: This collection of masks seems suspect.
7915   if (NumElts == 2)
7916     return true;
7917   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7918     return (isMOVLMask(Mask, VT)  ||
7919             isCommutedMOVLMask(Mask, VT, true) ||
7920             isSHUFPMask(Mask, VT) ||
7921             isCommutedSHUFPMask(Mask, VT));
7922   }
7923   return false;
7924 }
7925
7926 //===----------------------------------------------------------------------===//
7927 //                           X86 Scheduler Hooks
7928 //===----------------------------------------------------------------------===//
7929
7930 // private utility function
7931 MachineBasicBlock *
7932 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7933                                                        MachineBasicBlock *MBB,
7934                                                        unsigned regOpc,
7935                                                        unsigned immOpc,
7936                                                        unsigned LoadOpc,
7937                                                        unsigned CXchgOpc,
7938                                                        unsigned copyOpc,
7939                                                        unsigned notOpc,
7940                                                        unsigned EAXreg,
7941                                                        TargetRegisterClass *RC,
7942                                                        bool invSrc) const {
7943   // For the atomic bitwise operator, we generate
7944   //   thisMBB:
7945   //   newMBB:
7946   //     ld  t1 = [bitinstr.addr]
7947   //     op  t2 = t1, [bitinstr.val]
7948   //     mov EAX = t1
7949   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7950   //     bz  newMBB
7951   //     fallthrough -->nextMBB
7952   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7953   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7954   MachineFunction::iterator MBBIter = MBB;
7955   ++MBBIter;
7956
7957   /// First build the CFG
7958   MachineFunction *F = MBB->getParent();
7959   MachineBasicBlock *thisMBB = MBB;
7960   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7961   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7962   F->insert(MBBIter, newMBB);
7963   F->insert(MBBIter, nextMBB);
7964
7965   // Move all successors to thisMBB to nextMBB
7966   nextMBB->transferSuccessors(thisMBB);
7967
7968   // Update thisMBB to fall through to newMBB
7969   thisMBB->addSuccessor(newMBB);
7970
7971   // newMBB jumps to itself and fall through to nextMBB
7972   newMBB->addSuccessor(nextMBB);
7973   newMBB->addSuccessor(newMBB);
7974
7975   // Insert instructions into newMBB based on incoming instruction
7976   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7977          "unexpected number of operands");
7978   DebugLoc dl = bInstr->getDebugLoc();
7979   MachineOperand& destOper = bInstr->getOperand(0);
7980   MachineOperand* argOpers[2 + X86AddrNumOperands];
7981   int numArgs = bInstr->getNumOperands() - 1;
7982   for (int i=0; i < numArgs; ++i)
7983     argOpers[i] = &bInstr->getOperand(i+1);
7984
7985   // x86 address has 4 operands: base, index, scale, and displacement
7986   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7987   int valArgIndx = lastAddrIndx + 1;
7988
7989   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7990   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7991   for (int i=0; i <= lastAddrIndx; ++i)
7992     (*MIB).addOperand(*argOpers[i]);
7993
7994   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7995   if (invSrc) {
7996     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7997   }
7998   else
7999     tt = t1;
8000
8001   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8002   assert((argOpers[valArgIndx]->isReg() ||
8003           argOpers[valArgIndx]->isImm()) &&
8004          "invalid operand");
8005   if (argOpers[valArgIndx]->isReg())
8006     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8007   else
8008     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8009   MIB.addReg(tt);
8010   (*MIB).addOperand(*argOpers[valArgIndx]);
8011
8012   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8013   MIB.addReg(t1);
8014
8015   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8016   for (int i=0; i <= lastAddrIndx; ++i)
8017     (*MIB).addOperand(*argOpers[i]);
8018   MIB.addReg(t2);
8019   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8020   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8021                     bInstr->memoperands_end());
8022
8023   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8024   MIB.addReg(EAXreg);
8025
8026   // insert branch
8027   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8028
8029   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8030   return nextMBB;
8031 }
8032
8033 // private utility function:  64 bit atomics on 32 bit host.
8034 MachineBasicBlock *
8035 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8036                                                        MachineBasicBlock *MBB,
8037                                                        unsigned regOpcL,
8038                                                        unsigned regOpcH,
8039                                                        unsigned immOpcL,
8040                                                        unsigned immOpcH,
8041                                                        bool invSrc) const {
8042   // For the atomic bitwise operator, we generate
8043   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8044   //     ld t1,t2 = [bitinstr.addr]
8045   //   newMBB:
8046   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8047   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8048   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8049   //     mov ECX, EBX <- t5, t6
8050   //     mov EAX, EDX <- t1, t2
8051   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8052   //     mov t3, t4 <- EAX, EDX
8053   //     bz  newMBB
8054   //     result in out1, out2
8055   //     fallthrough -->nextMBB
8056
8057   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8058   const unsigned LoadOpc = X86::MOV32rm;
8059   const unsigned copyOpc = X86::MOV32rr;
8060   const unsigned NotOpc = X86::NOT32r;
8061   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8062   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8063   MachineFunction::iterator MBBIter = MBB;
8064   ++MBBIter;
8065
8066   /// First build the CFG
8067   MachineFunction *F = MBB->getParent();
8068   MachineBasicBlock *thisMBB = MBB;
8069   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8070   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8071   F->insert(MBBIter, newMBB);
8072   F->insert(MBBIter, nextMBB);
8073
8074   // Move all successors to thisMBB to nextMBB
8075   nextMBB->transferSuccessors(thisMBB);
8076
8077   // Update thisMBB to fall through to newMBB
8078   thisMBB->addSuccessor(newMBB);
8079
8080   // newMBB jumps to itself and fall through to nextMBB
8081   newMBB->addSuccessor(nextMBB);
8082   newMBB->addSuccessor(newMBB);
8083
8084   DebugLoc dl = bInstr->getDebugLoc();
8085   // Insert instructions into newMBB based on incoming instruction
8086   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8087   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8088          "unexpected number of operands");
8089   MachineOperand& dest1Oper = bInstr->getOperand(0);
8090   MachineOperand& dest2Oper = bInstr->getOperand(1);
8091   MachineOperand* argOpers[2 + X86AddrNumOperands];
8092   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8093     argOpers[i] = &bInstr->getOperand(i+2);
8094
8095   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8096   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8097
8098   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8099   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8100   for (int i=0; i <= lastAddrIndx; ++i)
8101     (*MIB).addOperand(*argOpers[i]);
8102   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8103   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8104   // add 4 to displacement.
8105   for (int i=0; i <= lastAddrIndx-2; ++i)
8106     (*MIB).addOperand(*argOpers[i]);
8107   MachineOperand newOp3 = *(argOpers[3]);
8108   if (newOp3.isImm())
8109     newOp3.setImm(newOp3.getImm()+4);
8110   else
8111     newOp3.setOffset(newOp3.getOffset()+4);
8112   (*MIB).addOperand(newOp3);
8113   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8114
8115   // t3/4 are defined later, at the bottom of the loop
8116   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8117   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8118   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8119     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8120   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8121     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8122
8123   // The subsequent operations should be using the destination registers of
8124   //the PHI instructions.
8125   if (invSrc) {
8126     t1 = F->getRegInfo().createVirtualRegister(RC);
8127     t2 = F->getRegInfo().createVirtualRegister(RC);
8128     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8129     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8130   } else {
8131     t1 = dest1Oper.getReg();
8132     t2 = dest2Oper.getReg();
8133   }
8134
8135   int valArgIndx = lastAddrIndx + 1;
8136   assert((argOpers[valArgIndx]->isReg() ||
8137           argOpers[valArgIndx]->isImm()) &&
8138          "invalid operand");
8139   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8140   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8141   if (argOpers[valArgIndx]->isReg())
8142     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8143   else
8144     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8145   if (regOpcL != X86::MOV32rr)
8146     MIB.addReg(t1);
8147   (*MIB).addOperand(*argOpers[valArgIndx]);
8148   assert(argOpers[valArgIndx + 1]->isReg() ==
8149          argOpers[valArgIndx]->isReg());
8150   assert(argOpers[valArgIndx + 1]->isImm() ==
8151          argOpers[valArgIndx]->isImm());
8152   if (argOpers[valArgIndx + 1]->isReg())
8153     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8154   else
8155     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8156   if (regOpcH != X86::MOV32rr)
8157     MIB.addReg(t2);
8158   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8159
8160   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8161   MIB.addReg(t1);
8162   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8163   MIB.addReg(t2);
8164
8165   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8166   MIB.addReg(t5);
8167   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8168   MIB.addReg(t6);
8169
8170   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8171   for (int i=0; i <= lastAddrIndx; ++i)
8172     (*MIB).addOperand(*argOpers[i]);
8173
8174   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8175   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8176                     bInstr->memoperands_end());
8177
8178   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8179   MIB.addReg(X86::EAX);
8180   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8181   MIB.addReg(X86::EDX);
8182
8183   // insert branch
8184   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8185
8186   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8187   return nextMBB;
8188 }
8189
8190 // private utility function
8191 MachineBasicBlock *
8192 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8193                                                       MachineBasicBlock *MBB,
8194                                                       unsigned cmovOpc) const {
8195   // For the atomic min/max operator, we generate
8196   //   thisMBB:
8197   //   newMBB:
8198   //     ld t1 = [min/max.addr]
8199   //     mov t2 = [min/max.val]
8200   //     cmp  t1, t2
8201   //     cmov[cond] t2 = t1
8202   //     mov EAX = t1
8203   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8204   //     bz   newMBB
8205   //     fallthrough -->nextMBB
8206   //
8207   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8208   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8209   MachineFunction::iterator MBBIter = MBB;
8210   ++MBBIter;
8211
8212   /// First build the CFG
8213   MachineFunction *F = MBB->getParent();
8214   MachineBasicBlock *thisMBB = MBB;
8215   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8216   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8217   F->insert(MBBIter, newMBB);
8218   F->insert(MBBIter, nextMBB);
8219
8220   // Move all successors of thisMBB to nextMBB
8221   nextMBB->transferSuccessors(thisMBB);
8222
8223   // Update thisMBB to fall through to newMBB
8224   thisMBB->addSuccessor(newMBB);
8225
8226   // newMBB jumps to newMBB and fall through to nextMBB
8227   newMBB->addSuccessor(nextMBB);
8228   newMBB->addSuccessor(newMBB);
8229
8230   DebugLoc dl = mInstr->getDebugLoc();
8231   // Insert instructions into newMBB based on incoming instruction
8232   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8233          "unexpected number of operands");
8234   MachineOperand& destOper = mInstr->getOperand(0);
8235   MachineOperand* argOpers[2 + X86AddrNumOperands];
8236   int numArgs = mInstr->getNumOperands() - 1;
8237   for (int i=0; i < numArgs; ++i)
8238     argOpers[i] = &mInstr->getOperand(i+1);
8239
8240   // x86 address has 4 operands: base, index, scale, and displacement
8241   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8242   int valArgIndx = lastAddrIndx + 1;
8243
8244   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8245   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8246   for (int i=0; i <= lastAddrIndx; ++i)
8247     (*MIB).addOperand(*argOpers[i]);
8248
8249   // We only support register and immediate values
8250   assert((argOpers[valArgIndx]->isReg() ||
8251           argOpers[valArgIndx]->isImm()) &&
8252          "invalid operand");
8253
8254   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8255   if (argOpers[valArgIndx]->isReg())
8256     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8257   else
8258     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8259   (*MIB).addOperand(*argOpers[valArgIndx]);
8260
8261   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8262   MIB.addReg(t1);
8263
8264   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8265   MIB.addReg(t1);
8266   MIB.addReg(t2);
8267
8268   // Generate movc
8269   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8270   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8271   MIB.addReg(t2);
8272   MIB.addReg(t1);
8273
8274   // Cmp and exchange if none has modified the memory location
8275   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8276   for (int i=0; i <= lastAddrIndx; ++i)
8277     (*MIB).addOperand(*argOpers[i]);
8278   MIB.addReg(t3);
8279   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8280   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8281                     mInstr->memoperands_end());
8282
8283   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8284   MIB.addReg(X86::EAX);
8285
8286   // insert branch
8287   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8288
8289   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8290   return nextMBB;
8291 }
8292
8293 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8294 // all of this code can be replaced with that in the .td file.
8295 MachineBasicBlock *
8296 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8297                             unsigned numArgs, bool memArg) const {
8298
8299   MachineFunction *F = BB->getParent();
8300   DebugLoc dl = MI->getDebugLoc();
8301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8302
8303   unsigned Opc;
8304   if (memArg)
8305     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8306   else
8307     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8308
8309   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8310
8311   for (unsigned i = 0; i < numArgs; ++i) {
8312     MachineOperand &Op = MI->getOperand(i+1);
8313
8314     if (!(Op.isReg() && Op.isImplicit()))
8315       MIB.addOperand(Op);
8316   }
8317
8318   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8319     .addReg(X86::XMM0);
8320
8321   F->DeleteMachineInstr(MI);
8322
8323   return BB;
8324 }
8325
8326 MachineBasicBlock *
8327 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8328                                                  MachineInstr *MI,
8329                                                  MachineBasicBlock *MBB) const {
8330   // Emit code to save XMM registers to the stack. The ABI says that the
8331   // number of registers to save is given in %al, so it's theoretically
8332   // possible to do an indirect jump trick to avoid saving all of them,
8333   // however this code takes a simpler approach and just executes all
8334   // of the stores if %al is non-zero. It's less code, and it's probably
8335   // easier on the hardware branch predictor, and stores aren't all that
8336   // expensive anyway.
8337
8338   // Create the new basic blocks. One block contains all the XMM stores,
8339   // and one block is the final destination regardless of whether any
8340   // stores were performed.
8341   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8342   MachineFunction *F = MBB->getParent();
8343   MachineFunction::iterator MBBIter = MBB;
8344   ++MBBIter;
8345   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8346   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8347   F->insert(MBBIter, XMMSaveMBB);
8348   F->insert(MBBIter, EndMBB);
8349
8350   // Set up the CFG.
8351   // Move any original successors of MBB to the end block.
8352   EndMBB->transferSuccessors(MBB);
8353   // The original block will now fall through to the XMM save block.
8354   MBB->addSuccessor(XMMSaveMBB);
8355   // The XMMSaveMBB will fall through to the end block.
8356   XMMSaveMBB->addSuccessor(EndMBB);
8357
8358   // Now add the instructions.
8359   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8360   DebugLoc DL = MI->getDebugLoc();
8361
8362   unsigned CountReg = MI->getOperand(0).getReg();
8363   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8364   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8365
8366   if (!Subtarget->isTargetWin64()) {
8367     // If %al is 0, branch around the XMM save block.
8368     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8369     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8370     MBB->addSuccessor(EndMBB);
8371   }
8372
8373   // In the XMM save block, save all the XMM argument registers.
8374   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8375     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8376     MachineMemOperand *MMO =
8377       F->getMachineMemOperand(
8378         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8379         MachineMemOperand::MOStore, Offset,
8380         /*Size=*/16, /*Align=*/16);
8381     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8382       .addFrameIndex(RegSaveFrameIndex)
8383       .addImm(/*Scale=*/1)
8384       .addReg(/*IndexReg=*/0)
8385       .addImm(/*Disp=*/Offset)
8386       .addReg(/*Segment=*/0)
8387       .addReg(MI->getOperand(i).getReg())
8388       .addMemOperand(MMO);
8389   }
8390
8391   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8392
8393   return EndMBB;
8394 }
8395
8396 MachineBasicBlock *
8397 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8398                                      MachineBasicBlock *BB,
8399                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8400   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8401   DebugLoc DL = MI->getDebugLoc();
8402
8403   // To "insert" a SELECT_CC instruction, we actually have to insert the
8404   // diamond control-flow pattern.  The incoming instruction knows the
8405   // destination vreg to set, the condition code register to branch on, the
8406   // true/false values to select between, and a branch opcode to use.
8407   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8408   MachineFunction::iterator It = BB;
8409   ++It;
8410
8411   //  thisMBB:
8412   //  ...
8413   //   TrueVal = ...
8414   //   cmpTY ccX, r1, r2
8415   //   bCC copy1MBB
8416   //   fallthrough --> copy0MBB
8417   MachineBasicBlock *thisMBB = BB;
8418   MachineFunction *F = BB->getParent();
8419   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8420   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8421   unsigned Opc =
8422     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8423   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8424   F->insert(It, copy0MBB);
8425   F->insert(It, sinkMBB);
8426   // Update machine-CFG edges by first adding all successors of the current
8427   // block to the new block which will contain the Phi node for the select.
8428   // Also inform sdisel of the edge changes.
8429   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8430          E = BB->succ_end(); I != E; ++I) {
8431     EM->insert(std::make_pair(*I, sinkMBB));
8432     sinkMBB->addSuccessor(*I);
8433   }
8434   // Next, remove all successors of the current block, and add the true
8435   // and fallthrough blocks as its successors.
8436   while (!BB->succ_empty())
8437     BB->removeSuccessor(BB->succ_begin());
8438   // Add the true and fallthrough blocks as its successors.
8439   BB->addSuccessor(copy0MBB);
8440   BB->addSuccessor(sinkMBB);
8441
8442   //  copy0MBB:
8443   //   %FalseValue = ...
8444   //   # fallthrough to sinkMBB
8445   BB = copy0MBB;
8446
8447   // Update machine-CFG edges
8448   BB->addSuccessor(sinkMBB);
8449
8450   //  sinkMBB:
8451   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8452   //  ...
8453   BB = sinkMBB;
8454   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8455     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8456     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8457
8458   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8459   return BB;
8460 }
8461
8462 MachineBasicBlock *
8463 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8464                                           MachineBasicBlock *BB,
8465                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8466   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8467   DebugLoc DL = MI->getDebugLoc();
8468   MachineFunction *F = BB->getParent();
8469
8470   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8471   // non-trivial part is impdef of ESP.
8472   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8473   // mingw-w64.
8474
8475   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8476     .addExternalSymbol("_alloca")
8477     .addReg(X86::EAX, RegState::Implicit)
8478     .addReg(X86::ESP, RegState::Implicit)
8479     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8480     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8481
8482   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8483   return BB;
8484 }
8485
8486 MachineBasicBlock *
8487 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8488                                                MachineBasicBlock *BB,
8489                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8490   switch (MI->getOpcode()) {
8491   default: assert(false && "Unexpected instr type to insert");
8492   case X86::MINGW_ALLOCA:
8493     return EmitLoweredMingwAlloca(MI, BB, EM);
8494   case X86::CMOV_GR8:
8495   case X86::CMOV_V1I64:
8496   case X86::CMOV_FR32:
8497   case X86::CMOV_FR64:
8498   case X86::CMOV_V4F32:
8499   case X86::CMOV_V2F64:
8500   case X86::CMOV_V2I64:
8501     return EmitLoweredSelect(MI, BB, EM);
8502
8503   case X86::FP32_TO_INT16_IN_MEM:
8504   case X86::FP32_TO_INT32_IN_MEM:
8505   case X86::FP32_TO_INT64_IN_MEM:
8506   case X86::FP64_TO_INT16_IN_MEM:
8507   case X86::FP64_TO_INT32_IN_MEM:
8508   case X86::FP64_TO_INT64_IN_MEM:
8509   case X86::FP80_TO_INT16_IN_MEM:
8510   case X86::FP80_TO_INT32_IN_MEM:
8511   case X86::FP80_TO_INT64_IN_MEM: {
8512     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8513     DebugLoc DL = MI->getDebugLoc();
8514
8515     // Change the floating point control register to use "round towards zero"
8516     // mode when truncating to an integer value.
8517     MachineFunction *F = BB->getParent();
8518     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8519     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8520
8521     // Load the old value of the high byte of the control word...
8522     unsigned OldCW =
8523       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8524     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8525                       CWFrameIdx);
8526
8527     // Set the high part to be round to zero...
8528     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8529       .addImm(0xC7F);
8530
8531     // Reload the modified control word now...
8532     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8533
8534     // Restore the memory image of control word to original value
8535     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8536       .addReg(OldCW);
8537
8538     // Get the X86 opcode to use.
8539     unsigned Opc;
8540     switch (MI->getOpcode()) {
8541     default: llvm_unreachable("illegal opcode!");
8542     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8543     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8544     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8545     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8546     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8547     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8548     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8549     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8550     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8551     }
8552
8553     X86AddressMode AM;
8554     MachineOperand &Op = MI->getOperand(0);
8555     if (Op.isReg()) {
8556       AM.BaseType = X86AddressMode::RegBase;
8557       AM.Base.Reg = Op.getReg();
8558     } else {
8559       AM.BaseType = X86AddressMode::FrameIndexBase;
8560       AM.Base.FrameIndex = Op.getIndex();
8561     }
8562     Op = MI->getOperand(1);
8563     if (Op.isImm())
8564       AM.Scale = Op.getImm();
8565     Op = MI->getOperand(2);
8566     if (Op.isImm())
8567       AM.IndexReg = Op.getImm();
8568     Op = MI->getOperand(3);
8569     if (Op.isGlobal()) {
8570       AM.GV = Op.getGlobal();
8571     } else {
8572       AM.Disp = Op.getImm();
8573     }
8574     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8575                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8576
8577     // Reload the original control word now.
8578     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8579
8580     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8581     return BB;
8582   }
8583     // DBG_VALUE.  Only the frame index case is done here.
8584   case X86::DBG_VALUE: {
8585     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8586     DebugLoc DL = MI->getDebugLoc();
8587     X86AddressMode AM;
8588     MachineFunction *F = BB->getParent();
8589     AM.BaseType = X86AddressMode::FrameIndexBase;
8590     AM.Base.FrameIndex = MI->getOperand(0).getImm();
8591     addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8592       addImm(MI->getOperand(1).getImm()).
8593       addMetadata(MI->getOperand(2).getMetadata());
8594     F->DeleteMachineInstr(MI);      // Remove pseudo.
8595     return BB;
8596   }
8597
8598     // String/text processing lowering.
8599   case X86::PCMPISTRM128REG:
8600     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8601   case X86::PCMPISTRM128MEM:
8602     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8603   case X86::PCMPESTRM128REG:
8604     return EmitPCMP(MI, BB, 5, false /* in mem */);
8605   case X86::PCMPESTRM128MEM:
8606     return EmitPCMP(MI, BB, 5, true /* in mem */);
8607
8608     // Atomic Lowering.
8609   case X86::ATOMAND32:
8610     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8611                                                X86::AND32ri, X86::MOV32rm,
8612                                                X86::LCMPXCHG32, X86::MOV32rr,
8613                                                X86::NOT32r, X86::EAX,
8614                                                X86::GR32RegisterClass);
8615   case X86::ATOMOR32:
8616     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8617                                                X86::OR32ri, X86::MOV32rm,
8618                                                X86::LCMPXCHG32, X86::MOV32rr,
8619                                                X86::NOT32r, X86::EAX,
8620                                                X86::GR32RegisterClass);
8621   case X86::ATOMXOR32:
8622     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8623                                                X86::XOR32ri, X86::MOV32rm,
8624                                                X86::LCMPXCHG32, X86::MOV32rr,
8625                                                X86::NOT32r, X86::EAX,
8626                                                X86::GR32RegisterClass);
8627   case X86::ATOMNAND32:
8628     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8629                                                X86::AND32ri, X86::MOV32rm,
8630                                                X86::LCMPXCHG32, X86::MOV32rr,
8631                                                X86::NOT32r, X86::EAX,
8632                                                X86::GR32RegisterClass, true);
8633   case X86::ATOMMIN32:
8634     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8635   case X86::ATOMMAX32:
8636     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8637   case X86::ATOMUMIN32:
8638     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8639   case X86::ATOMUMAX32:
8640     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8641
8642   case X86::ATOMAND16:
8643     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8644                                                X86::AND16ri, X86::MOV16rm,
8645                                                X86::LCMPXCHG16, X86::MOV16rr,
8646                                                X86::NOT16r, X86::AX,
8647                                                X86::GR16RegisterClass);
8648   case X86::ATOMOR16:
8649     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8650                                                X86::OR16ri, X86::MOV16rm,
8651                                                X86::LCMPXCHG16, X86::MOV16rr,
8652                                                X86::NOT16r, X86::AX,
8653                                                X86::GR16RegisterClass);
8654   case X86::ATOMXOR16:
8655     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8656                                                X86::XOR16ri, X86::MOV16rm,
8657                                                X86::LCMPXCHG16, X86::MOV16rr,
8658                                                X86::NOT16r, X86::AX,
8659                                                X86::GR16RegisterClass);
8660   case X86::ATOMNAND16:
8661     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8662                                                X86::AND16ri, X86::MOV16rm,
8663                                                X86::LCMPXCHG16, X86::MOV16rr,
8664                                                X86::NOT16r, X86::AX,
8665                                                X86::GR16RegisterClass, true);
8666   case X86::ATOMMIN16:
8667     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8668   case X86::ATOMMAX16:
8669     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8670   case X86::ATOMUMIN16:
8671     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8672   case X86::ATOMUMAX16:
8673     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8674
8675   case X86::ATOMAND8:
8676     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8677                                                X86::AND8ri, X86::MOV8rm,
8678                                                X86::LCMPXCHG8, X86::MOV8rr,
8679                                                X86::NOT8r, X86::AL,
8680                                                X86::GR8RegisterClass);
8681   case X86::ATOMOR8:
8682     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8683                                                X86::OR8ri, X86::MOV8rm,
8684                                                X86::LCMPXCHG8, X86::MOV8rr,
8685                                                X86::NOT8r, X86::AL,
8686                                                X86::GR8RegisterClass);
8687   case X86::ATOMXOR8:
8688     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8689                                                X86::XOR8ri, X86::MOV8rm,
8690                                                X86::LCMPXCHG8, X86::MOV8rr,
8691                                                X86::NOT8r, X86::AL,
8692                                                X86::GR8RegisterClass);
8693   case X86::ATOMNAND8:
8694     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8695                                                X86::AND8ri, X86::MOV8rm,
8696                                                X86::LCMPXCHG8, X86::MOV8rr,
8697                                                X86::NOT8r, X86::AL,
8698                                                X86::GR8RegisterClass, true);
8699   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8700   // This group is for 64-bit host.
8701   case X86::ATOMAND64:
8702     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8703                                                X86::AND64ri32, X86::MOV64rm,
8704                                                X86::LCMPXCHG64, X86::MOV64rr,
8705                                                X86::NOT64r, X86::RAX,
8706                                                X86::GR64RegisterClass);
8707   case X86::ATOMOR64:
8708     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8709                                                X86::OR64ri32, X86::MOV64rm,
8710                                                X86::LCMPXCHG64, X86::MOV64rr,
8711                                                X86::NOT64r, X86::RAX,
8712                                                X86::GR64RegisterClass);
8713   case X86::ATOMXOR64:
8714     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8715                                                X86::XOR64ri32, X86::MOV64rm,
8716                                                X86::LCMPXCHG64, X86::MOV64rr,
8717                                                X86::NOT64r, X86::RAX,
8718                                                X86::GR64RegisterClass);
8719   case X86::ATOMNAND64:
8720     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8721                                                X86::AND64ri32, X86::MOV64rm,
8722                                                X86::LCMPXCHG64, X86::MOV64rr,
8723                                                X86::NOT64r, X86::RAX,
8724                                                X86::GR64RegisterClass, true);
8725   case X86::ATOMMIN64:
8726     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8727   case X86::ATOMMAX64:
8728     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8729   case X86::ATOMUMIN64:
8730     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8731   case X86::ATOMUMAX64:
8732     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8733
8734   // This group does 64-bit operations on a 32-bit host.
8735   case X86::ATOMAND6432:
8736     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8737                                                X86::AND32rr, X86::AND32rr,
8738                                                X86::AND32ri, X86::AND32ri,
8739                                                false);
8740   case X86::ATOMOR6432:
8741     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8742                                                X86::OR32rr, X86::OR32rr,
8743                                                X86::OR32ri, X86::OR32ri,
8744                                                false);
8745   case X86::ATOMXOR6432:
8746     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8747                                                X86::XOR32rr, X86::XOR32rr,
8748                                                X86::XOR32ri, X86::XOR32ri,
8749                                                false);
8750   case X86::ATOMNAND6432:
8751     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8752                                                X86::AND32rr, X86::AND32rr,
8753                                                X86::AND32ri, X86::AND32ri,
8754                                                true);
8755   case X86::ATOMADD6432:
8756     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8757                                                X86::ADD32rr, X86::ADC32rr,
8758                                                X86::ADD32ri, X86::ADC32ri,
8759                                                false);
8760   case X86::ATOMSUB6432:
8761     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8762                                                X86::SUB32rr, X86::SBB32rr,
8763                                                X86::SUB32ri, X86::SBB32ri,
8764                                                false);
8765   case X86::ATOMSWAP6432:
8766     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8767                                                X86::MOV32rr, X86::MOV32rr,
8768                                                X86::MOV32ri, X86::MOV32ri,
8769                                                false);
8770   case X86::VASTART_SAVE_XMM_REGS:
8771     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8772   }
8773 }
8774
8775 //===----------------------------------------------------------------------===//
8776 //                           X86 Optimization Hooks
8777 //===----------------------------------------------------------------------===//
8778
8779 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8780                                                        const APInt &Mask,
8781                                                        APInt &KnownZero,
8782                                                        APInt &KnownOne,
8783                                                        const SelectionDAG &DAG,
8784                                                        unsigned Depth) const {
8785   unsigned Opc = Op.getOpcode();
8786   assert((Opc >= ISD::BUILTIN_OP_END ||
8787           Opc == ISD::INTRINSIC_WO_CHAIN ||
8788           Opc == ISD::INTRINSIC_W_CHAIN ||
8789           Opc == ISD::INTRINSIC_VOID) &&
8790          "Should use MaskedValueIsZero if you don't know whether Op"
8791          " is a target node!");
8792
8793   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8794   switch (Opc) {
8795   default: break;
8796   case X86ISD::ADD:
8797   case X86ISD::SUB:
8798   case X86ISD::SMUL:
8799   case X86ISD::UMUL:
8800   case X86ISD::INC:
8801   case X86ISD::DEC:
8802   case X86ISD::OR:
8803   case X86ISD::XOR:
8804   case X86ISD::AND:
8805     // These nodes' second result is a boolean.
8806     if (Op.getResNo() == 0)
8807       break;
8808     // Fallthrough
8809   case X86ISD::SETCC:
8810     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8811                                        Mask.getBitWidth() - 1);
8812     break;
8813   }
8814 }
8815
8816 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8817 /// node is a GlobalAddress + offset.
8818 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8819                                        GlobalValue* &GA, int64_t &Offset) const{
8820   if (N->getOpcode() == X86ISD::Wrapper) {
8821     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8822       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8823       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8824       return true;
8825     }
8826   }
8827   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8828 }
8829
8830 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8831                                      EVT EltVT, LoadSDNode *&LDBase,
8832                                      unsigned &LastLoadedElt,
8833                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8834                                      const TargetLowering &TLI) {
8835   LDBase = NULL;
8836   LastLoadedElt = -1U;
8837   for (unsigned i = 0; i < NumElems; ++i) {
8838     if (N->getMaskElt(i) < 0) {
8839       if (!LDBase)
8840         return false;
8841       continue;
8842     }
8843
8844     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8845     if (!Elt.getNode() ||
8846         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8847       return false;
8848     if (!LDBase) {
8849       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8850         return false;
8851       LDBase = cast<LoadSDNode>(Elt.getNode());
8852       LastLoadedElt = i;
8853       continue;
8854     }
8855     if (Elt.getOpcode() == ISD::UNDEF)
8856       continue;
8857
8858     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8859     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8860       return false;
8861     LastLoadedElt = i;
8862   }
8863   return true;
8864 }
8865
8866 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8867 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8868 /// if the load addresses are consecutive, non-overlapping, and in the right
8869 /// order.  In the case of v2i64, it will see if it can rewrite the
8870 /// shuffle to be an appropriate build vector so it can take advantage of
8871 // performBuildVectorCombine.
8872 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8873                                      const TargetLowering &TLI) {
8874   DebugLoc dl = N->getDebugLoc();
8875   EVT VT = N->getValueType(0);
8876   EVT EltVT = VT.getVectorElementType();
8877   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8878   unsigned NumElems = VT.getVectorNumElements();
8879
8880   if (VT.getSizeInBits() != 128)
8881     return SDValue();
8882
8883   // Try to combine a vector_shuffle into a 128-bit load.
8884   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8885   LoadSDNode *LD = NULL;
8886   unsigned LastLoadedElt;
8887   if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8888                                 MFI, TLI))
8889     return SDValue();
8890
8891   if (LastLoadedElt == NumElems - 1) {
8892     if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8893       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8894                          LD->getSrcValue(), LD->getSrcValueOffset(),
8895                          LD->isVolatile(), LD->isNonTemporal(), 0);
8896     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8897                        LD->getSrcValue(), LD->getSrcValueOffset(),
8898                        LD->isVolatile(), LD->isNonTemporal(),
8899                        LD->getAlignment());
8900   } else if (NumElems == 4 && LastLoadedElt == 1) {
8901     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8902     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8903     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8904     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8905   }
8906   return SDValue();
8907 }
8908
8909 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8910 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8911                                     const X86Subtarget *Subtarget) {
8912   DebugLoc DL = N->getDebugLoc();
8913   SDValue Cond = N->getOperand(0);
8914   // Get the LHS/RHS of the select.
8915   SDValue LHS = N->getOperand(1);
8916   SDValue RHS = N->getOperand(2);
8917
8918   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8919   // instructions match the semantics of the common C idiom x<y?x:y but not
8920   // x<=y?x:y, because of how they handle negative zero (which can be
8921   // ignored in unsafe-math mode).
8922   if (Subtarget->hasSSE2() &&
8923       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8924       Cond.getOpcode() == ISD::SETCC) {
8925     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8926
8927     unsigned Opcode = 0;
8928     // Check for x CC y ? x : y.
8929     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8930         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8931       switch (CC) {
8932       default: break;
8933       case ISD::SETULT:
8934         // Converting this to a min would handle NaNs incorrectly, and swapping
8935         // the operands would cause it to handle comparisons between positive
8936         // and negative zero incorrectly.
8937         if (!FiniteOnlyFPMath() &&
8938             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8939           if (!UnsafeFPMath &&
8940               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8941             break;
8942           std::swap(LHS, RHS);
8943         }
8944         Opcode = X86ISD::FMIN;
8945         break;
8946       case ISD::SETOLE:
8947         // Converting this to a min would handle comparisons between positive
8948         // and negative zero incorrectly.
8949         if (!UnsafeFPMath &&
8950             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8951           break;
8952         Opcode = X86ISD::FMIN;
8953         break;
8954       case ISD::SETULE:
8955         // Converting this to a min would handle both negative zeros and NaNs
8956         // incorrectly, but we can swap the operands to fix both.
8957         std::swap(LHS, RHS);
8958       case ISD::SETOLT:
8959       case ISD::SETLT:
8960       case ISD::SETLE:
8961         Opcode = X86ISD::FMIN;
8962         break;
8963
8964       case ISD::SETOGE:
8965         // Converting this to a max would handle comparisons between positive
8966         // and negative zero incorrectly.
8967         if (!UnsafeFPMath &&
8968             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8969           break;
8970         Opcode = X86ISD::FMAX;
8971         break;
8972       case ISD::SETUGT:
8973         // Converting this to a max would handle NaNs incorrectly, and swapping
8974         // the operands would cause it to handle comparisons between positive
8975         // and negative zero incorrectly.
8976         if (!FiniteOnlyFPMath() &&
8977             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8978           if (!UnsafeFPMath &&
8979               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8980             break;
8981           std::swap(LHS, RHS);
8982         }
8983         Opcode = X86ISD::FMAX;
8984         break;
8985       case ISD::SETUGE:
8986         // Converting this to a max would handle both negative zeros and NaNs
8987         // incorrectly, but we can swap the operands to fix both.
8988         std::swap(LHS, RHS);
8989       case ISD::SETOGT:
8990       case ISD::SETGT:
8991       case ISD::SETGE:
8992         Opcode = X86ISD::FMAX;
8993         break;
8994       }
8995     // Check for x CC y ? y : x -- a min/max with reversed arms.
8996     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8997                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8998       switch (CC) {
8999       default: break;
9000       case ISD::SETOGE:
9001         // Converting this to a min would handle comparisons between positive
9002         // and negative zero incorrectly, and swapping the operands would
9003         // cause it to handle NaNs incorrectly.
9004         if (!UnsafeFPMath &&
9005             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9006           if (!FiniteOnlyFPMath() &&
9007               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9008             break;
9009           std::swap(LHS, RHS);
9010         }
9011         Opcode = X86ISD::FMIN;
9012         break;
9013       case ISD::SETUGT:
9014         // Converting this to a min would handle NaNs incorrectly.
9015         if (!UnsafeFPMath &&
9016             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9017           break;
9018         Opcode = X86ISD::FMIN;
9019         break;
9020       case ISD::SETUGE:
9021         // Converting this to a min would handle both negative zeros and NaNs
9022         // incorrectly, but we can swap the operands to fix both.
9023         std::swap(LHS, RHS);
9024       case ISD::SETOGT:
9025       case ISD::SETGT:
9026       case ISD::SETGE:
9027         Opcode = X86ISD::FMIN;
9028         break;
9029
9030       case ISD::SETULT:
9031         // Converting this to a max would handle NaNs incorrectly.
9032         if (!FiniteOnlyFPMath() &&
9033             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9034           break;
9035         Opcode = X86ISD::FMAX;
9036         break;
9037       case ISD::SETOLE:
9038         // Converting this to a max would handle comparisons between positive
9039         // and negative zero incorrectly, and swapping the operands would
9040         // cause it to handle NaNs incorrectly.
9041         if (!UnsafeFPMath &&
9042             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9043           if (!FiniteOnlyFPMath() &&
9044               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9045             break;
9046           std::swap(LHS, RHS);
9047         }
9048         Opcode = X86ISD::FMAX;
9049         break;
9050       case ISD::SETULE:
9051         // Converting this to a max would handle both negative zeros and NaNs
9052         // incorrectly, but we can swap the operands to fix both.
9053         std::swap(LHS, RHS);
9054       case ISD::SETOLT:
9055       case ISD::SETLT:
9056       case ISD::SETLE:
9057         Opcode = X86ISD::FMAX;
9058         break;
9059       }
9060     }
9061
9062     if (Opcode)
9063       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9064   }
9065
9066   // If this is a select between two integer constants, try to do some
9067   // optimizations.
9068   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9069     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9070       // Don't do this for crazy integer types.
9071       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9072         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9073         // so that TrueC (the true value) is larger than FalseC.
9074         bool NeedsCondInvert = false;
9075
9076         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9077             // Efficiently invertible.
9078             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9079              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9080               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9081           NeedsCondInvert = true;
9082           std::swap(TrueC, FalseC);
9083         }
9084
9085         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9086         if (FalseC->getAPIntValue() == 0 &&
9087             TrueC->getAPIntValue().isPowerOf2()) {
9088           if (NeedsCondInvert) // Invert the condition if needed.
9089             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9090                                DAG.getConstant(1, Cond.getValueType()));
9091
9092           // Zero extend the condition if needed.
9093           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9094
9095           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9096           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9097                              DAG.getConstant(ShAmt, MVT::i8));
9098         }
9099
9100         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9101         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9102           if (NeedsCondInvert) // Invert the condition if needed.
9103             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9104                                DAG.getConstant(1, Cond.getValueType()));
9105
9106           // Zero extend the condition if needed.
9107           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9108                              FalseC->getValueType(0), Cond);
9109           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9110                              SDValue(FalseC, 0));
9111         }
9112
9113         // Optimize cases that will turn into an LEA instruction.  This requires
9114         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9115         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9116           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9117           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9118
9119           bool isFastMultiplier = false;
9120           if (Diff < 10) {
9121             switch ((unsigned char)Diff) {
9122               default: break;
9123               case 1:  // result = add base, cond
9124               case 2:  // result = lea base(    , cond*2)
9125               case 3:  // result = lea base(cond, cond*2)
9126               case 4:  // result = lea base(    , cond*4)
9127               case 5:  // result = lea base(cond, cond*4)
9128               case 8:  // result = lea base(    , cond*8)
9129               case 9:  // result = lea base(cond, cond*8)
9130                 isFastMultiplier = true;
9131                 break;
9132             }
9133           }
9134
9135           if (isFastMultiplier) {
9136             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9137             if (NeedsCondInvert) // Invert the condition if needed.
9138               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9139                                  DAG.getConstant(1, Cond.getValueType()));
9140
9141             // Zero extend the condition if needed.
9142             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9143                                Cond);
9144             // Scale the condition by the difference.
9145             if (Diff != 1)
9146               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9147                                  DAG.getConstant(Diff, Cond.getValueType()));
9148
9149             // Add the base if non-zero.
9150             if (FalseC->getAPIntValue() != 0)
9151               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9152                                  SDValue(FalseC, 0));
9153             return Cond;
9154           }
9155         }
9156       }
9157   }
9158
9159   return SDValue();
9160 }
9161
9162 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9163 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9164                                   TargetLowering::DAGCombinerInfo &DCI) {
9165   DebugLoc DL = N->getDebugLoc();
9166
9167   // If the flag operand isn't dead, don't touch this CMOV.
9168   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9169     return SDValue();
9170
9171   // If this is a select between two integer constants, try to do some
9172   // optimizations.  Note that the operands are ordered the opposite of SELECT
9173   // operands.
9174   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9175     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9176       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9177       // larger than FalseC (the false value).
9178       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9179
9180       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9181         CC = X86::GetOppositeBranchCondition(CC);
9182         std::swap(TrueC, FalseC);
9183       }
9184
9185       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9186       // This is efficient for any integer data type (including i8/i16) and
9187       // shift amount.
9188       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9189         SDValue Cond = N->getOperand(3);
9190         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9191                            DAG.getConstant(CC, MVT::i8), Cond);
9192
9193         // Zero extend the condition if needed.
9194         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9195
9196         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9197         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9198                            DAG.getConstant(ShAmt, MVT::i8));
9199         if (N->getNumValues() == 2)  // Dead flag value?
9200           return DCI.CombineTo(N, Cond, SDValue());
9201         return Cond;
9202       }
9203
9204       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9205       // for any integer data type, including i8/i16.
9206       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9207         SDValue Cond = N->getOperand(3);
9208         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9209                            DAG.getConstant(CC, MVT::i8), Cond);
9210
9211         // Zero extend the condition if needed.
9212         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9213                            FalseC->getValueType(0), Cond);
9214         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9215                            SDValue(FalseC, 0));
9216
9217         if (N->getNumValues() == 2)  // Dead flag value?
9218           return DCI.CombineTo(N, Cond, SDValue());
9219         return Cond;
9220       }
9221
9222       // Optimize cases that will turn into an LEA instruction.  This requires
9223       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9224       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9225         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9226         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9227
9228         bool isFastMultiplier = false;
9229         if (Diff < 10) {
9230           switch ((unsigned char)Diff) {
9231           default: break;
9232           case 1:  // result = add base, cond
9233           case 2:  // result = lea base(    , cond*2)
9234           case 3:  // result = lea base(cond, cond*2)
9235           case 4:  // result = lea base(    , cond*4)
9236           case 5:  // result = lea base(cond, cond*4)
9237           case 8:  // result = lea base(    , cond*8)
9238           case 9:  // result = lea base(cond, cond*8)
9239             isFastMultiplier = true;
9240             break;
9241           }
9242         }
9243
9244         if (isFastMultiplier) {
9245           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9246           SDValue Cond = N->getOperand(3);
9247           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9248                              DAG.getConstant(CC, MVT::i8), Cond);
9249           // Zero extend the condition if needed.
9250           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9251                              Cond);
9252           // Scale the condition by the difference.
9253           if (Diff != 1)
9254             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9255                                DAG.getConstant(Diff, Cond.getValueType()));
9256
9257           // Add the base if non-zero.
9258           if (FalseC->getAPIntValue() != 0)
9259             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9260                                SDValue(FalseC, 0));
9261           if (N->getNumValues() == 2)  // Dead flag value?
9262             return DCI.CombineTo(N, Cond, SDValue());
9263           return Cond;
9264         }
9265       }
9266     }
9267   }
9268   return SDValue();
9269 }
9270
9271
9272 /// PerformMulCombine - Optimize a single multiply with constant into two
9273 /// in order to implement it with two cheaper instructions, e.g.
9274 /// LEA + SHL, LEA + LEA.
9275 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9276                                  TargetLowering::DAGCombinerInfo &DCI) {
9277   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9278     return SDValue();
9279
9280   EVT VT = N->getValueType(0);
9281   if (VT != MVT::i64)
9282     return SDValue();
9283
9284   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9285   if (!C)
9286     return SDValue();
9287   uint64_t MulAmt = C->getZExtValue();
9288   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9289     return SDValue();
9290
9291   uint64_t MulAmt1 = 0;
9292   uint64_t MulAmt2 = 0;
9293   if ((MulAmt % 9) == 0) {
9294     MulAmt1 = 9;
9295     MulAmt2 = MulAmt / 9;
9296   } else if ((MulAmt % 5) == 0) {
9297     MulAmt1 = 5;
9298     MulAmt2 = MulAmt / 5;
9299   } else if ((MulAmt % 3) == 0) {
9300     MulAmt1 = 3;
9301     MulAmt2 = MulAmt / 3;
9302   }
9303   if (MulAmt2 &&
9304       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9305     DebugLoc DL = N->getDebugLoc();
9306
9307     if (isPowerOf2_64(MulAmt2) &&
9308         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9309       // If second multiplifer is pow2, issue it first. We want the multiply by
9310       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9311       // is an add.
9312       std::swap(MulAmt1, MulAmt2);
9313
9314     SDValue NewMul;
9315     if (isPowerOf2_64(MulAmt1))
9316       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9317                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9318     else
9319       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9320                            DAG.getConstant(MulAmt1, VT));
9321
9322     if (isPowerOf2_64(MulAmt2))
9323       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9324                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9325     else
9326       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9327                            DAG.getConstant(MulAmt2, VT));
9328
9329     // Do not add new nodes to DAG combiner worklist.
9330     DCI.CombineTo(N, NewMul, false);
9331   }
9332   return SDValue();
9333 }
9334
9335 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9336   SDValue N0 = N->getOperand(0);
9337   SDValue N1 = N->getOperand(1);
9338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9339   EVT VT = N0.getValueType();
9340
9341   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9342   // since the result of setcc_c is all zero's or all ones.
9343   if (N1C && N0.getOpcode() == ISD::AND &&
9344       N0.getOperand(1).getOpcode() == ISD::Constant) {
9345     SDValue N00 = N0.getOperand(0);
9346     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9347         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9348           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9349          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9350       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9351       APInt ShAmt = N1C->getAPIntValue();
9352       Mask = Mask.shl(ShAmt);
9353       if (Mask != 0)
9354         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9355                            N00, DAG.getConstant(Mask, VT));
9356     }
9357   }
9358
9359   return SDValue();
9360 }
9361
9362 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9363 ///                       when possible.
9364 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9365                                    const X86Subtarget *Subtarget) {
9366   EVT VT = N->getValueType(0);
9367   if (!VT.isVector() && VT.isInteger() &&
9368       N->getOpcode() == ISD::SHL)
9369     return PerformSHLCombine(N, DAG);
9370
9371   // On X86 with SSE2 support, we can transform this to a vector shift if
9372   // all elements are shifted by the same amount.  We can't do this in legalize
9373   // because the a constant vector is typically transformed to a constant pool
9374   // so we have no knowledge of the shift amount.
9375   if (!Subtarget->hasSSE2())
9376     return SDValue();
9377
9378   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9379     return SDValue();
9380
9381   SDValue ShAmtOp = N->getOperand(1);
9382   EVT EltVT = VT.getVectorElementType();
9383   DebugLoc DL = N->getDebugLoc();
9384   SDValue BaseShAmt = SDValue();
9385   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9386     unsigned NumElts = VT.getVectorNumElements();
9387     unsigned i = 0;
9388     for (; i != NumElts; ++i) {
9389       SDValue Arg = ShAmtOp.getOperand(i);
9390       if (Arg.getOpcode() == ISD::UNDEF) continue;
9391       BaseShAmt = Arg;
9392       break;
9393     }
9394     for (; i != NumElts; ++i) {
9395       SDValue Arg = ShAmtOp.getOperand(i);
9396       if (Arg.getOpcode() == ISD::UNDEF) continue;
9397       if (Arg != BaseShAmt) {
9398         return SDValue();
9399       }
9400     }
9401   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9402              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9403     SDValue InVec = ShAmtOp.getOperand(0);
9404     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9405       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9406       unsigned i = 0;
9407       for (; i != NumElts; ++i) {
9408         SDValue Arg = InVec.getOperand(i);
9409         if (Arg.getOpcode() == ISD::UNDEF) continue;
9410         BaseShAmt = Arg;
9411         break;
9412       }
9413     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9414        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9415          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9416          if (C->getZExtValue() == SplatIdx)
9417            BaseShAmt = InVec.getOperand(1);
9418        }
9419     }
9420     if (BaseShAmt.getNode() == 0)
9421       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9422                               DAG.getIntPtrConstant(0));
9423   } else
9424     return SDValue();
9425
9426   // The shift amount is an i32.
9427   if (EltVT.bitsGT(MVT::i32))
9428     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9429   else if (EltVT.bitsLT(MVT::i32))
9430     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9431
9432   // The shift amount is identical so we can do a vector shift.
9433   SDValue  ValOp = N->getOperand(0);
9434   switch (N->getOpcode()) {
9435   default:
9436     llvm_unreachable("Unknown shift opcode!");
9437     break;
9438   case ISD::SHL:
9439     if (VT == MVT::v2i64)
9440       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9441                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9442                          ValOp, BaseShAmt);
9443     if (VT == MVT::v4i32)
9444       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9445                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9446                          ValOp, BaseShAmt);
9447     if (VT == MVT::v8i16)
9448       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9449                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9450                          ValOp, BaseShAmt);
9451     break;
9452   case ISD::SRA:
9453     if (VT == MVT::v4i32)
9454       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9455                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9456                          ValOp, BaseShAmt);
9457     if (VT == MVT::v8i16)
9458       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9459                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9460                          ValOp, BaseShAmt);
9461     break;
9462   case ISD::SRL:
9463     if (VT == MVT::v2i64)
9464       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9465                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9466                          ValOp, BaseShAmt);
9467     if (VT == MVT::v4i32)
9468       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9469                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9470                          ValOp, BaseShAmt);
9471     if (VT ==  MVT::v8i16)
9472       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9473                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9474                          ValOp, BaseShAmt);
9475     break;
9476   }
9477   return SDValue();
9478 }
9479
9480 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9481                                 const X86Subtarget *Subtarget) {
9482   EVT VT = N->getValueType(0);
9483   if (VT != MVT::i64 || !Subtarget->is64Bit())
9484     return SDValue();
9485
9486   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9487   SDValue N0 = N->getOperand(0);
9488   SDValue N1 = N->getOperand(1);
9489   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9490     std::swap(N0, N1);
9491   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9492     return SDValue();
9493
9494   SDValue ShAmt0 = N0.getOperand(1);
9495   if (ShAmt0.getValueType() != MVT::i8)
9496     return SDValue();
9497   SDValue ShAmt1 = N1.getOperand(1);
9498   if (ShAmt1.getValueType() != MVT::i8)
9499     return SDValue();
9500   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9501     ShAmt0 = ShAmt0.getOperand(0);
9502   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9503     ShAmt1 = ShAmt1.getOperand(0);
9504
9505   DebugLoc DL = N->getDebugLoc();
9506   unsigned Opc = X86ISD::SHLD;
9507   SDValue Op0 = N0.getOperand(0);
9508   SDValue Op1 = N1.getOperand(0);
9509   if (ShAmt0.getOpcode() == ISD::SUB) {
9510     Opc = X86ISD::SHRD;
9511     std::swap(Op0, Op1);
9512     std::swap(ShAmt0, ShAmt1);
9513   }
9514
9515   if (ShAmt1.getOpcode() == ISD::SUB) {
9516     SDValue Sum = ShAmt1.getOperand(0);
9517     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9518       if (SumC->getSExtValue() == 64 &&
9519           ShAmt1.getOperand(1) == ShAmt0)
9520         return DAG.getNode(Opc, DL, VT,
9521                            Op0, Op1,
9522                            DAG.getNode(ISD::TRUNCATE, DL,
9523                                        MVT::i8, ShAmt0));
9524     }
9525   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9526     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9527     if (ShAmt0C &&
9528         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9529       return DAG.getNode(Opc, DL, VT,
9530                          N0.getOperand(0), N1.getOperand(0),
9531                          DAG.getNode(ISD::TRUNCATE, DL,
9532                                        MVT::i8, ShAmt0));
9533   }
9534
9535   return SDValue();
9536 }
9537
9538 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9539 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9540                                    const X86Subtarget *Subtarget) {
9541   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9542   // the FP state in cases where an emms may be missing.
9543   // A preferable solution to the general problem is to figure out the right
9544   // places to insert EMMS.  This qualifies as a quick hack.
9545
9546   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9547   StoreSDNode *St = cast<StoreSDNode>(N);
9548   EVT VT = St->getValue().getValueType();
9549   if (VT.getSizeInBits() != 64)
9550     return SDValue();
9551
9552   const Function *F = DAG.getMachineFunction().getFunction();
9553   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9554   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9555     && Subtarget->hasSSE2();
9556   if ((VT.isVector() ||
9557        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9558       isa<LoadSDNode>(St->getValue()) &&
9559       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9560       St->getChain().hasOneUse() && !St->isVolatile()) {
9561     SDNode* LdVal = St->getValue().getNode();
9562     LoadSDNode *Ld = 0;
9563     int TokenFactorIndex = -1;
9564     SmallVector<SDValue, 8> Ops;
9565     SDNode* ChainVal = St->getChain().getNode();
9566     // Must be a store of a load.  We currently handle two cases:  the load
9567     // is a direct child, and it's under an intervening TokenFactor.  It is
9568     // possible to dig deeper under nested TokenFactors.
9569     if (ChainVal == LdVal)
9570       Ld = cast<LoadSDNode>(St->getChain());
9571     else if (St->getValue().hasOneUse() &&
9572              ChainVal->getOpcode() == ISD::TokenFactor) {
9573       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9574         if (ChainVal->getOperand(i).getNode() == LdVal) {
9575           TokenFactorIndex = i;
9576           Ld = cast<LoadSDNode>(St->getValue());
9577         } else
9578           Ops.push_back(ChainVal->getOperand(i));
9579       }
9580     }
9581
9582     if (!Ld || !ISD::isNormalLoad(Ld))
9583       return SDValue();
9584
9585     // If this is not the MMX case, i.e. we are just turning i64 load/store
9586     // into f64 load/store, avoid the transformation if there are multiple
9587     // uses of the loaded value.
9588     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9589       return SDValue();
9590
9591     DebugLoc LdDL = Ld->getDebugLoc();
9592     DebugLoc StDL = N->getDebugLoc();
9593     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9594     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9595     // pair instead.
9596     if (Subtarget->is64Bit() || F64IsLegal) {
9597       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9598       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9599                                   Ld->getBasePtr(), Ld->getSrcValue(),
9600                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9601                                   Ld->isNonTemporal(), Ld->getAlignment());
9602       SDValue NewChain = NewLd.getValue(1);
9603       if (TokenFactorIndex != -1) {
9604         Ops.push_back(NewChain);
9605         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9606                                Ops.size());
9607       }
9608       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9609                           St->getSrcValue(), St->getSrcValueOffset(),
9610                           St->isVolatile(), St->isNonTemporal(),
9611                           St->getAlignment());
9612     }
9613
9614     // Otherwise, lower to two pairs of 32-bit loads / stores.
9615     SDValue LoAddr = Ld->getBasePtr();
9616     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9617                                  DAG.getConstant(4, MVT::i32));
9618
9619     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9620                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9621                                Ld->isVolatile(), Ld->isNonTemporal(),
9622                                Ld->getAlignment());
9623     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9624                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9625                                Ld->isVolatile(), Ld->isNonTemporal(),
9626                                MinAlign(Ld->getAlignment(), 4));
9627
9628     SDValue NewChain = LoLd.getValue(1);
9629     if (TokenFactorIndex != -1) {
9630       Ops.push_back(LoLd);
9631       Ops.push_back(HiLd);
9632       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9633                              Ops.size());
9634     }
9635
9636     LoAddr = St->getBasePtr();
9637     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9638                          DAG.getConstant(4, MVT::i32));
9639
9640     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9641                                 St->getSrcValue(), St->getSrcValueOffset(),
9642                                 St->isVolatile(), St->isNonTemporal(),
9643                                 St->getAlignment());
9644     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9645                                 St->getSrcValue(),
9646                                 St->getSrcValueOffset() + 4,
9647                                 St->isVolatile(),
9648                                 St->isNonTemporal(),
9649                                 MinAlign(St->getAlignment(), 4));
9650     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9651   }
9652   return SDValue();
9653 }
9654
9655 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9656 /// X86ISD::FXOR nodes.
9657 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9658   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9659   // F[X]OR(0.0, x) -> x
9660   // F[X]OR(x, 0.0) -> x
9661   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9662     if (C->getValueAPF().isPosZero())
9663       return N->getOperand(1);
9664   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9665     if (C->getValueAPF().isPosZero())
9666       return N->getOperand(0);
9667   return SDValue();
9668 }
9669
9670 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9671 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9672   // FAND(0.0, x) -> 0.0
9673   // FAND(x, 0.0) -> 0.0
9674   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9675     if (C->getValueAPF().isPosZero())
9676       return N->getOperand(0);
9677   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9678     if (C->getValueAPF().isPosZero())
9679       return N->getOperand(1);
9680   return SDValue();
9681 }
9682
9683 static SDValue PerformBTCombine(SDNode *N,
9684                                 SelectionDAG &DAG,
9685                                 TargetLowering::DAGCombinerInfo &DCI) {
9686   // BT ignores high bits in the bit index operand.
9687   SDValue Op1 = N->getOperand(1);
9688   if (Op1.hasOneUse()) {
9689     unsigned BitWidth = Op1.getValueSizeInBits();
9690     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9691     APInt KnownZero, KnownOne;
9692     TargetLowering::TargetLoweringOpt TLO(DAG);
9693     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9694     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9695         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9696       DCI.CommitTargetLoweringOpt(TLO);
9697   }
9698   return SDValue();
9699 }
9700
9701 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9702   SDValue Op = N->getOperand(0);
9703   if (Op.getOpcode() == ISD::BIT_CONVERT)
9704     Op = Op.getOperand(0);
9705   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9706   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9707       VT.getVectorElementType().getSizeInBits() ==
9708       OpVT.getVectorElementType().getSizeInBits()) {
9709     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9710   }
9711   return SDValue();
9712 }
9713
9714 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9715 // Locked instructions, in turn, have implicit fence semantics (all memory
9716 // operations are flushed before issuing the locked instruction, and the
9717 // are not buffered), so we can fold away the common pattern of
9718 // fence-atomic-fence.
9719 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9720   SDValue atomic = N->getOperand(0);
9721   switch (atomic.getOpcode()) {
9722     case ISD::ATOMIC_CMP_SWAP:
9723     case ISD::ATOMIC_SWAP:
9724     case ISD::ATOMIC_LOAD_ADD:
9725     case ISD::ATOMIC_LOAD_SUB:
9726     case ISD::ATOMIC_LOAD_AND:
9727     case ISD::ATOMIC_LOAD_OR:
9728     case ISD::ATOMIC_LOAD_XOR:
9729     case ISD::ATOMIC_LOAD_NAND:
9730     case ISD::ATOMIC_LOAD_MIN:
9731     case ISD::ATOMIC_LOAD_MAX:
9732     case ISD::ATOMIC_LOAD_UMIN:
9733     case ISD::ATOMIC_LOAD_UMAX:
9734       break;
9735     default:
9736       return SDValue();
9737   }
9738
9739   SDValue fence = atomic.getOperand(0);
9740   if (fence.getOpcode() != ISD::MEMBARRIER)
9741     return SDValue();
9742
9743   switch (atomic.getOpcode()) {
9744     case ISD::ATOMIC_CMP_SWAP:
9745       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9746                                     atomic.getOperand(1), atomic.getOperand(2),
9747                                     atomic.getOperand(3));
9748     case ISD::ATOMIC_SWAP:
9749     case ISD::ATOMIC_LOAD_ADD:
9750     case ISD::ATOMIC_LOAD_SUB:
9751     case ISD::ATOMIC_LOAD_AND:
9752     case ISD::ATOMIC_LOAD_OR:
9753     case ISD::ATOMIC_LOAD_XOR:
9754     case ISD::ATOMIC_LOAD_NAND:
9755     case ISD::ATOMIC_LOAD_MIN:
9756     case ISD::ATOMIC_LOAD_MAX:
9757     case ISD::ATOMIC_LOAD_UMIN:
9758     case ISD::ATOMIC_LOAD_UMAX:
9759       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9760                                     atomic.getOperand(1), atomic.getOperand(2));
9761     default:
9762       return SDValue();
9763   }
9764 }
9765
9766 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9767   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9768   //           (and (i32 x86isd::setcc_carry), 1)
9769   // This eliminates the zext. This transformation is necessary because
9770   // ISD::SETCC is always legalized to i8.
9771   DebugLoc dl = N->getDebugLoc();
9772   SDValue N0 = N->getOperand(0);
9773   EVT VT = N->getValueType(0);
9774   if (N0.getOpcode() == ISD::AND &&
9775       N0.hasOneUse() &&
9776       N0.getOperand(0).hasOneUse()) {
9777     SDValue N00 = N0.getOperand(0);
9778     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9779       return SDValue();
9780     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9781     if (!C || C->getZExtValue() != 1)
9782       return SDValue();
9783     return DAG.getNode(ISD::AND, dl, VT,
9784                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9785                                    N00.getOperand(0), N00.getOperand(1)),
9786                        DAG.getConstant(1, VT));
9787   }
9788
9789   return SDValue();
9790 }
9791
9792 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9793                                              DAGCombinerInfo &DCI) const {
9794   SelectionDAG &DAG = DCI.DAG;
9795   switch (N->getOpcode()) {
9796   default: break;
9797   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9798   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9799   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9800   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9801   case ISD::SHL:
9802   case ISD::SRA:
9803   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9804   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9805   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9806   case X86ISD::FXOR:
9807   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9808   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9809   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9810   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9811   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9812   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9813   }
9814
9815   return SDValue();
9816 }
9817
9818 //===----------------------------------------------------------------------===//
9819 //                           X86 Inline Assembly Support
9820 //===----------------------------------------------------------------------===//
9821
9822 static bool LowerToBSwap(CallInst *CI) {
9823   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9824   // we will turn this bswap into something that will be lowered to logical ops
9825   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9826   // so don't worry about this.
9827
9828   // Verify this is a simple bswap.
9829   if (CI->getNumOperands() != 2 ||
9830       CI->getType() != CI->getOperand(1)->getType() ||
9831       !CI->getType()->isIntegerTy())
9832     return false;
9833
9834   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9835   if (!Ty || Ty->getBitWidth() % 16 != 0)
9836     return false;
9837
9838   // Okay, we can do this xform, do so now.
9839   const Type *Tys[] = { Ty };
9840   Module *M = CI->getParent()->getParent()->getParent();
9841   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9842
9843   Value *Op = CI->getOperand(1);
9844   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9845
9846   CI->replaceAllUsesWith(Op);
9847   CI->eraseFromParent();
9848   return true;
9849 }
9850
9851 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9852   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9853   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9854
9855   std::string AsmStr = IA->getAsmString();
9856
9857   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9858   SmallVector<StringRef, 4> AsmPieces;
9859   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9860
9861   switch (AsmPieces.size()) {
9862   default: return false;
9863   case 1:
9864     AsmStr = AsmPieces[0];
9865     AsmPieces.clear();
9866     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9867
9868     // bswap $0
9869     if (AsmPieces.size() == 2 &&
9870         (AsmPieces[0] == "bswap" ||
9871          AsmPieces[0] == "bswapq" ||
9872          AsmPieces[0] == "bswapl") &&
9873         (AsmPieces[1] == "$0" ||
9874          AsmPieces[1] == "${0:q}")) {
9875       // No need to check constraints, nothing other than the equivalent of
9876       // "=r,0" would be valid here.
9877       return LowerToBSwap(CI);
9878     }
9879     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9880     if (CI->getType()->isIntegerTy(16) &&
9881         AsmPieces.size() == 3 &&
9882         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9883         AsmPieces[1] == "$$8," &&
9884         AsmPieces[2] == "${0:w}" &&
9885         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9886       AsmPieces.clear();
9887       const std::string &Constraints = IA->getConstraintString();
9888       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9889       std::sort(AsmPieces.begin(), AsmPieces.end());
9890       if (AsmPieces.size() == 4 &&
9891           AsmPieces[0] == "~{cc}" &&
9892           AsmPieces[1] == "~{dirflag}" &&
9893           AsmPieces[2] == "~{flags}" &&
9894           AsmPieces[3] == "~{fpsr}") {
9895         return LowerToBSwap(CI);
9896       }
9897     }
9898     break;
9899   case 3:
9900     if (CI->getType()->isIntegerTy(64) &&
9901         Constraints.size() >= 2 &&
9902         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9903         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9904       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9905       SmallVector<StringRef, 4> Words;
9906       SplitString(AsmPieces[0], Words, " \t");
9907       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9908         Words.clear();
9909         SplitString(AsmPieces[1], Words, " \t");
9910         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9911           Words.clear();
9912           SplitString(AsmPieces[2], Words, " \t,");
9913           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9914               Words[2] == "%edx") {
9915             return LowerToBSwap(CI);
9916           }
9917         }
9918       }
9919     }
9920     break;
9921   }
9922   return false;
9923 }
9924
9925
9926
9927 /// getConstraintType - Given a constraint letter, return the type of
9928 /// constraint it is for this target.
9929 X86TargetLowering::ConstraintType
9930 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9931   if (Constraint.size() == 1) {
9932     switch (Constraint[0]) {
9933     case 'A':
9934       return C_Register;
9935     case 'f':
9936     case 'r':
9937     case 'R':
9938     case 'l':
9939     case 'q':
9940     case 'Q':
9941     case 'x':
9942     case 'y':
9943     case 'Y':
9944       return C_RegisterClass;
9945     case 'e':
9946     case 'Z':
9947       return C_Other;
9948     default:
9949       break;
9950     }
9951   }
9952   return TargetLowering::getConstraintType(Constraint);
9953 }
9954
9955 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9956 /// with another that has more specific requirements based on the type of the
9957 /// corresponding operand.
9958 const char *X86TargetLowering::
9959 LowerXConstraint(EVT ConstraintVT) const {
9960   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9961   // 'f' like normal targets.
9962   if (ConstraintVT.isFloatingPoint()) {
9963     if (Subtarget->hasSSE2())
9964       return "Y";
9965     if (Subtarget->hasSSE1())
9966       return "x";
9967   }
9968
9969   return TargetLowering::LowerXConstraint(ConstraintVT);
9970 }
9971
9972 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9973 /// vector.  If it is invalid, don't add anything to Ops.
9974 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9975                                                      char Constraint,
9976                                                      bool hasMemory,
9977                                                      std::vector<SDValue>&Ops,
9978                                                      SelectionDAG &DAG) const {
9979   SDValue Result(0, 0);
9980
9981   switch (Constraint) {
9982   default: break;
9983   case 'I':
9984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9985       if (C->getZExtValue() <= 31) {
9986         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9987         break;
9988       }
9989     }
9990     return;
9991   case 'J':
9992     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9993       if (C->getZExtValue() <= 63) {
9994         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9995         break;
9996       }
9997     }
9998     return;
9999   case 'K':
10000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10001       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10002         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10003         break;
10004       }
10005     }
10006     return;
10007   case 'N':
10008     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10009       if (C->getZExtValue() <= 255) {
10010         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10011         break;
10012       }
10013     }
10014     return;
10015   case 'e': {
10016     // 32-bit signed value
10017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10018       const ConstantInt *CI = C->getConstantIntValue();
10019       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10020                                   C->getSExtValue())) {
10021         // Widen to 64 bits here to get it sign extended.
10022         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10023         break;
10024       }
10025     // FIXME gcc accepts some relocatable values here too, but only in certain
10026     // memory models; it's complicated.
10027     }
10028     return;
10029   }
10030   case 'Z': {
10031     // 32-bit unsigned value
10032     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10033       const ConstantInt *CI = C->getConstantIntValue();
10034       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10035                                   C->getZExtValue())) {
10036         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10037         break;
10038       }
10039     }
10040     // FIXME gcc accepts some relocatable values here too, but only in certain
10041     // memory models; it's complicated.
10042     return;
10043   }
10044   case 'i': {
10045     // Literal immediates are always ok.
10046     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10047       // Widen to 64 bits here to get it sign extended.
10048       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10049       break;
10050     }
10051
10052     // If we are in non-pic codegen mode, we allow the address of a global (with
10053     // an optional displacement) to be used with 'i'.
10054     GlobalAddressSDNode *GA = 0;
10055     int64_t Offset = 0;
10056
10057     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10058     while (1) {
10059       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10060         Offset += GA->getOffset();
10061         break;
10062       } else if (Op.getOpcode() == ISD::ADD) {
10063         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10064           Offset += C->getZExtValue();
10065           Op = Op.getOperand(0);
10066           continue;
10067         }
10068       } else if (Op.getOpcode() == ISD::SUB) {
10069         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10070           Offset += -C->getZExtValue();
10071           Op = Op.getOperand(0);
10072           continue;
10073         }
10074       }
10075
10076       // Otherwise, this isn't something we can handle, reject it.
10077       return;
10078     }
10079
10080     GlobalValue *GV = GA->getGlobal();
10081     // If we require an extra load to get this address, as in PIC mode, we
10082     // can't accept it.
10083     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10084                                                         getTargetMachine())))
10085       return;
10086
10087     if (hasMemory)
10088       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10089     else
10090       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10091     Result = Op;
10092     break;
10093   }
10094   }
10095
10096   if (Result.getNode()) {
10097     Ops.push_back(Result);
10098     return;
10099   }
10100   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10101                                                       Ops, DAG);
10102 }
10103
10104 std::vector<unsigned> X86TargetLowering::
10105 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10106                                   EVT VT) const {
10107   if (Constraint.size() == 1) {
10108     // FIXME: not handling fp-stack yet!
10109     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10110     default: break;  // Unknown constraint letter
10111     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10112       if (Subtarget->is64Bit()) {
10113         if (VT == MVT::i32)
10114           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10115                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10116                                        X86::R10D,X86::R11D,X86::R12D,
10117                                        X86::R13D,X86::R14D,X86::R15D,
10118                                        X86::EBP, X86::ESP, 0);
10119         else if (VT == MVT::i16)
10120           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10121                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10122                                        X86::R10W,X86::R11W,X86::R12W,
10123                                        X86::R13W,X86::R14W,X86::R15W,
10124                                        X86::BP,  X86::SP, 0);
10125         else if (VT == MVT::i8)
10126           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10127                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10128                                        X86::R10B,X86::R11B,X86::R12B,
10129                                        X86::R13B,X86::R14B,X86::R15B,
10130                                        X86::BPL, X86::SPL, 0);
10131
10132         else if (VT == MVT::i64)
10133           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10134                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10135                                        X86::R10, X86::R11, X86::R12,
10136                                        X86::R13, X86::R14, X86::R15,
10137                                        X86::RBP, X86::RSP, 0);
10138
10139         break;
10140       }
10141       // 32-bit fallthrough
10142     case 'Q':   // Q_REGS
10143       if (VT == MVT::i32)
10144         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10145       else if (VT == MVT::i16)
10146         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10147       else if (VT == MVT::i8)
10148         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10149       else if (VT == MVT::i64)
10150         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10151       break;
10152     }
10153   }
10154
10155   return std::vector<unsigned>();
10156 }
10157
10158 std::pair<unsigned, const TargetRegisterClass*>
10159 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10160                                                 EVT VT) const {
10161   // First, see if this is a constraint that directly corresponds to an LLVM
10162   // register class.
10163   if (Constraint.size() == 1) {
10164     // GCC Constraint Letters
10165     switch (Constraint[0]) {
10166     default: break;
10167     case 'r':   // GENERAL_REGS
10168     case 'l':   // INDEX_REGS
10169       if (VT == MVT::i8)
10170         return std::make_pair(0U, X86::GR8RegisterClass);
10171       if (VT == MVT::i16)
10172         return std::make_pair(0U, X86::GR16RegisterClass);
10173       if (VT == MVT::i32 || !Subtarget->is64Bit())
10174         return std::make_pair(0U, X86::GR32RegisterClass);
10175       return std::make_pair(0U, X86::GR64RegisterClass);
10176     case 'R':   // LEGACY_REGS
10177       if (VT == MVT::i8)
10178         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10179       if (VT == MVT::i16)
10180         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10181       if (VT == MVT::i32 || !Subtarget->is64Bit())
10182         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10183       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10184     case 'f':  // FP Stack registers.
10185       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10186       // value to the correct fpstack register class.
10187       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10188         return std::make_pair(0U, X86::RFP32RegisterClass);
10189       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10190         return std::make_pair(0U, X86::RFP64RegisterClass);
10191       return std::make_pair(0U, X86::RFP80RegisterClass);
10192     case 'y':   // MMX_REGS if MMX allowed.
10193       if (!Subtarget->hasMMX()) break;
10194       return std::make_pair(0U, X86::VR64RegisterClass);
10195     case 'Y':   // SSE_REGS if SSE2 allowed
10196       if (!Subtarget->hasSSE2()) break;
10197       // FALL THROUGH.
10198     case 'x':   // SSE_REGS if SSE1 allowed
10199       if (!Subtarget->hasSSE1()) break;
10200
10201       switch (VT.getSimpleVT().SimpleTy) {
10202       default: break;
10203       // Scalar SSE types.
10204       case MVT::f32:
10205       case MVT::i32:
10206         return std::make_pair(0U, X86::FR32RegisterClass);
10207       case MVT::f64:
10208       case MVT::i64:
10209         return std::make_pair(0U, X86::FR64RegisterClass);
10210       // Vector types.
10211       case MVT::v16i8:
10212       case MVT::v8i16:
10213       case MVT::v4i32:
10214       case MVT::v2i64:
10215       case MVT::v4f32:
10216       case MVT::v2f64:
10217         return std::make_pair(0U, X86::VR128RegisterClass);
10218       }
10219       break;
10220     }
10221   }
10222
10223   // Use the default implementation in TargetLowering to convert the register
10224   // constraint into a member of a register class.
10225   std::pair<unsigned, const TargetRegisterClass*> Res;
10226   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10227
10228   // Not found as a standard register?
10229   if (Res.second == 0) {
10230     // Map st(0) -> st(7) -> ST0
10231     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10232         tolower(Constraint[1]) == 's' &&
10233         tolower(Constraint[2]) == 't' &&
10234         Constraint[3] == '(' &&
10235         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10236         Constraint[5] == ')' &&
10237         Constraint[6] == '}') {
10238
10239       Res.first = X86::ST0+Constraint[4]-'0';
10240       Res.second = X86::RFP80RegisterClass;
10241       return Res;
10242     }
10243
10244     // GCC allows "st(0)" to be called just plain "st".
10245     if (StringRef("{st}").equals_lower(Constraint)) {
10246       Res.first = X86::ST0;
10247       Res.second = X86::RFP80RegisterClass;
10248       return Res;
10249     }
10250
10251     // flags -> EFLAGS
10252     if (StringRef("{flags}").equals_lower(Constraint)) {
10253       Res.first = X86::EFLAGS;
10254       Res.second = X86::CCRRegisterClass;
10255       return Res;
10256     }
10257
10258     // 'A' means EAX + EDX.
10259     if (Constraint == "A") {
10260       Res.first = X86::EAX;
10261       Res.second = X86::GR32_ADRegisterClass;
10262       return Res;
10263     }
10264     return Res;
10265   }
10266
10267   // Otherwise, check to see if this is a register class of the wrong value
10268   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10269   // turn into {ax},{dx}.
10270   if (Res.second->hasType(VT))
10271     return Res;   // Correct type already, nothing to do.
10272
10273   // All of the single-register GCC register classes map their values onto
10274   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10275   // really want an 8-bit or 32-bit register, map to the appropriate register
10276   // class and return the appropriate register.
10277   if (Res.second == X86::GR16RegisterClass) {
10278     if (VT == MVT::i8) {
10279       unsigned DestReg = 0;
10280       switch (Res.first) {
10281       default: break;
10282       case X86::AX: DestReg = X86::AL; break;
10283       case X86::DX: DestReg = X86::DL; break;
10284       case X86::CX: DestReg = X86::CL; break;
10285       case X86::BX: DestReg = X86::BL; break;
10286       }
10287       if (DestReg) {
10288         Res.first = DestReg;
10289         Res.second = X86::GR8RegisterClass;
10290       }
10291     } else if (VT == MVT::i32) {
10292       unsigned DestReg = 0;
10293       switch (Res.first) {
10294       default: break;
10295       case X86::AX: DestReg = X86::EAX; break;
10296       case X86::DX: DestReg = X86::EDX; break;
10297       case X86::CX: DestReg = X86::ECX; break;
10298       case X86::BX: DestReg = X86::EBX; break;
10299       case X86::SI: DestReg = X86::ESI; break;
10300       case X86::DI: DestReg = X86::EDI; break;
10301       case X86::BP: DestReg = X86::EBP; break;
10302       case X86::SP: DestReg = X86::ESP; break;
10303       }
10304       if (DestReg) {
10305         Res.first = DestReg;
10306         Res.second = X86::GR32RegisterClass;
10307       }
10308     } else if (VT == MVT::i64) {
10309       unsigned DestReg = 0;
10310       switch (Res.first) {
10311       default: break;
10312       case X86::AX: DestReg = X86::RAX; break;
10313       case X86::DX: DestReg = X86::RDX; break;
10314       case X86::CX: DestReg = X86::RCX; break;
10315       case X86::BX: DestReg = X86::RBX; break;
10316       case X86::SI: DestReg = X86::RSI; break;
10317       case X86::DI: DestReg = X86::RDI; break;
10318       case X86::BP: DestReg = X86::RBP; break;
10319       case X86::SP: DestReg = X86::RSP; break;
10320       }
10321       if (DestReg) {
10322         Res.first = DestReg;
10323         Res.second = X86::GR64RegisterClass;
10324       }
10325     }
10326   } else if (Res.second == X86::FR32RegisterClass ||
10327              Res.second == X86::FR64RegisterClass ||
10328              Res.second == X86::VR128RegisterClass) {
10329     // Handle references to XMM physical registers that got mapped into the
10330     // wrong class.  This can happen with constraints like {xmm0} where the
10331     // target independent register mapper will just pick the first match it can
10332     // find, ignoring the required type.
10333     if (VT == MVT::f32)
10334       Res.second = X86::FR32RegisterClass;
10335     else if (VT == MVT::f64)
10336       Res.second = X86::FR64RegisterClass;
10337     else if (X86::VR128RegisterClass->hasType(VT))
10338       Res.second = X86::VR128RegisterClass;
10339   }
10340
10341   return Res;
10342 }