llvm-mc/X86: Encode constant MCValue's correctly.
[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 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalAlias.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/VectorExtras.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/raw_ostream.h"
45 using namespace llvm;
46
47 static cl::opt<bool>
48 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
49
50 // Forward declarations.
51 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
52                        SDValue V2);
53
54 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
55   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
56   default: llvm_unreachable("unknown subtarget type");
57   case X86Subtarget::isDarwin:
58     return new TargetLoweringObjectFileMachO();
59   case X86Subtarget::isELF:
60     return new TargetLoweringObjectFileELF();
61   case X86Subtarget::isMingw:
62   case X86Subtarget::isCygwin:
63   case X86Subtarget::isWindows:
64     return new TargetLoweringObjectFileCOFF();
65   }
66
67 }
68
69 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
70   : TargetLowering(TM, createTLOF(TM)) {
71   Subtarget = &TM.getSubtarget<X86Subtarget>();
72   X86ScalarSSEf64 = Subtarget->hasSSE2();
73   X86ScalarSSEf32 = Subtarget->hasSSE1();
74   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
75
76   RegInfo = TM.getRegisterInfo();
77   TD = getTargetData();
78
79   // Set up the TargetLowering object.
80
81   // X86 is weird, it always uses i8 for shift amounts and setcc results.
82   setShiftAmountType(MVT::i8);
83   setBooleanContents(ZeroOrOneBooleanContent);
84   setSchedulingPreference(SchedulingForRegPressure);
85   setStackPointerRegisterToSaveRestore(X86StackPtr);
86
87   if (Subtarget->isTargetDarwin()) {
88     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
89     setUseUnderscoreSetJmp(false);
90     setUseUnderscoreLongJmp(false);
91   } else if (Subtarget->isTargetMingw()) {
92     // MS runtime is weird: it exports _setjmp, but longjmp!
93     setUseUnderscoreSetJmp(true);
94     setUseUnderscoreLongJmp(false);
95   } else {
96     setUseUnderscoreSetJmp(true);
97     setUseUnderscoreLongJmp(true);
98   }
99
100   // Set up the register classes.
101   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
102   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
103   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
104   if (Subtarget->is64Bit())
105     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
106
107   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
108
109   // We don't accept any truncstore of integer registers.
110   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
111   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
112   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
113   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
114   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
115   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
116
117   // SETOEQ and SETUNE require checking two conditions.
118   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
119   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
120   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
121   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
122   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
123   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
124
125   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
126   // operation.
127   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
128   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
129   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
130
131   if (Subtarget->is64Bit()) {
132     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
133     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
134   } else if (!UseSoftFloat) {
135     if (X86ScalarSSEf64) {
136       // We have an impenetrably clever algorithm for ui64->double only.
137       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
138     }
139     // We have an algorithm for SSE2, and we turn this into a 64-bit
140     // FILD for other targets.
141     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
142   }
143
144   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
145   // this operation.
146   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
147   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
148
149   if (!UseSoftFloat) {
150     // SSE has no i16 to fp conversion, only i32
151     if (X86ScalarSSEf32) {
152       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
153       // f32 and f64 cases are Legal, f80 case is not
154       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
155     } else {
156       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
157       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
158     }
159   } else {
160     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
161     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
162   }
163
164   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
165   // are Legal, f80 is custom lowered.
166   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
167   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
168
169   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
170   // this operation.
171   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
172   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
173
174   if (X86ScalarSSEf32) {
175     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
176     // f32 and f64 cases are Legal, f80 case is not
177     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
178   } else {
179     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
180     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
181   }
182
183   // Handle FP_TO_UINT by promoting the destination to a larger signed
184   // conversion.
185   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
186   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
187   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
188
189   if (Subtarget->is64Bit()) {
190     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
191     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
192   } else if (!UseSoftFloat) {
193     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
194       // Expand FP_TO_UINT into a select.
195       // FIXME: We would like to use a Custom expander here eventually to do
196       // the optimal thing for SSE vs. the default expansion in the legalizer.
197       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
198     else
199       // With SSE3 we can use fisttpll to convert to a signed i64; without
200       // SSE, we're stuck with a fistpll.
201       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
202   }
203
204   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
205   if (!X86ScalarSSEf64) {
206     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
207     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
208   }
209
210   // Scalar integer divide and remainder are lowered to use operations that
211   // produce two results, to match the available instructions. This exposes
212   // the two-result form to trivial CSE, which is able to combine x/y and x%y
213   // into a single instruction.
214   //
215   // Scalar integer multiply-high is also lowered to use two-result
216   // operations, to match the available instructions. However, plain multiply
217   // (low) operations are left as Legal, as there are single-result
218   // instructions for this in x86. Using the two-result multiply instructions
219   // when both high and low results are needed must be arranged by dagcombine.
220   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
221   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
222   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
223   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
224   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
225   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
226   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
227   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
228   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
229   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
230   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
231   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
232   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
233   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
234   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
235   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
236   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
237   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
238   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
239   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
240   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
241   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
242   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
243   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
244
245   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
246   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
248   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
249   if (Subtarget->is64Bit())
250     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
251   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
252   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
253   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
254   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
255   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
256   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
257   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
258   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
259
260   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
261   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
262   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
263   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
264   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
265   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
266   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
267   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
268   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
269   if (Subtarget->is64Bit()) {
270     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
271     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
272     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
273   }
274
275   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
276   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
277
278   // These should be promoted to a larger select which is supported.
279   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
280   // X86 wants to expand cmov itself.
281   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
282   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
283   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
284   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
285   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
286   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
287   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
288   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
289   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
290   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
291   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
292   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
293   if (Subtarget->is64Bit()) {
294     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
295     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
296   }
297   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
298
299   // Darwin ABI issue.
300   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
301   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
302   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
303   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
304   if (Subtarget->is64Bit())
305     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
306   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
307   if (Subtarget->is64Bit()) {
308     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
309     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
310     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
311     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
312   }
313   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
314   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
315   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
316   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
317   if (Subtarget->is64Bit()) {
318     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
319     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
320     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
321   }
322
323   if (Subtarget->hasSSE1())
324     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
325
326   if (!Subtarget->hasSSE2())
327     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
328
329   // Expand certain atomics
330   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
331   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
332   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
333   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
334
335   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
336   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
337   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
338   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
339
340   if (!Subtarget->is64Bit()) {
341     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
342     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
343     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
344     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
345     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
346     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
347     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
348   }
349
350   // Use the default ISD::DBG_STOPPOINT.
351   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
352   // FIXME - use subtarget debug flags
353   if (!Subtarget->isTargetDarwin() &&
354       !Subtarget->isTargetELF() &&
355       !Subtarget->isTargetCygMing()) {
356     setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
357     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
358   }
359
360   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
361   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
362   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
363   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
364   if (Subtarget->is64Bit()) {
365     setExceptionPointerRegister(X86::RAX);
366     setExceptionSelectorRegister(X86::RDX);
367   } else {
368     setExceptionPointerRegister(X86::EAX);
369     setExceptionSelectorRegister(X86::EDX);
370   }
371   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
372   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
373
374   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
375
376   setOperationAction(ISD::TRAP, MVT::Other, Legal);
377
378   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
379   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
380   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
381   if (Subtarget->is64Bit()) {
382     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
383     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
384   } else {
385     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
386     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
387   }
388
389   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
390   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
391   if (Subtarget->is64Bit())
392     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
393   if (Subtarget->isTargetCygMing())
394     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
395   else
396     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
397
398   if (!UseSoftFloat && X86ScalarSSEf64) {
399     // f32 and f64 use SSE.
400     // Set up the FP register classes.
401     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
402     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
403
404     // Use ANDPD to simulate FABS.
405     setOperationAction(ISD::FABS , MVT::f64, Custom);
406     setOperationAction(ISD::FABS , MVT::f32, Custom);
407
408     // Use XORP to simulate FNEG.
409     setOperationAction(ISD::FNEG , MVT::f64, Custom);
410     setOperationAction(ISD::FNEG , MVT::f32, Custom);
411
412     // Use ANDPD and ORPD to simulate FCOPYSIGN.
413     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
414     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
415
416     // We don't support sin/cos/fmod
417     setOperationAction(ISD::FSIN , MVT::f64, Expand);
418     setOperationAction(ISD::FCOS , MVT::f64, Expand);
419     setOperationAction(ISD::FSIN , MVT::f32, Expand);
420     setOperationAction(ISD::FCOS , MVT::f32, Expand);
421
422     // Expand FP immediates into loads from the stack, except for the special
423     // cases we handle.
424     addLegalFPImmediate(APFloat(+0.0)); // xorpd
425     addLegalFPImmediate(APFloat(+0.0f)); // xorps
426   } else if (!UseSoftFloat && X86ScalarSSEf32) {
427     // Use SSE for f32, x87 for f64.
428     // Set up the FP register classes.
429     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
430     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
431
432     // Use ANDPS to simulate FABS.
433     setOperationAction(ISD::FABS , MVT::f32, Custom);
434
435     // Use XORP to simulate FNEG.
436     setOperationAction(ISD::FNEG , MVT::f32, Custom);
437
438     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
439
440     // Use ANDPS and ORPS to simulate FCOPYSIGN.
441     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
442     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
443
444     // We don't support sin/cos/fmod
445     setOperationAction(ISD::FSIN , MVT::f32, Expand);
446     setOperationAction(ISD::FCOS , MVT::f32, Expand);
447
448     // Special cases we handle for FP constants.
449     addLegalFPImmediate(APFloat(+0.0f)); // xorps
450     addLegalFPImmediate(APFloat(+0.0)); // FLD0
451     addLegalFPImmediate(APFloat(+1.0)); // FLD1
452     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
453     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
454
455     if (!UnsafeFPMath) {
456       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
457       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
458     }
459   } else if (!UseSoftFloat) {
460     // f32 and f64 in x87.
461     // Set up the FP register classes.
462     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
463     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
464
465     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
466     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
467     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
468     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
469
470     if (!UnsafeFPMath) {
471       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
472       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
473     }
474     addLegalFPImmediate(APFloat(+0.0)); // FLD0
475     addLegalFPImmediate(APFloat(+1.0)); // FLD1
476     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
478     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
479     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
480     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
481     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
482   }
483
484   // Long double always uses X87.
485   if (!UseSoftFloat) {
486     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
487     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
488     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
489     {
490       bool ignored;
491       APFloat TmpFlt(+0.0);
492       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
493                      &ignored);
494       addLegalFPImmediate(TmpFlt);  // FLD0
495       TmpFlt.changeSign();
496       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
497       APFloat TmpFlt2(+1.0);
498       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
499                       &ignored);
500       addLegalFPImmediate(TmpFlt2);  // FLD1
501       TmpFlt2.changeSign();
502       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
503     }
504
505     if (!UnsafeFPMath) {
506       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
507       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
508     }
509   }
510
511   // Always use a library call for pow.
512   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
513   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
514   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
515
516   setOperationAction(ISD::FLOG, MVT::f80, Expand);
517   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
518   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
519   setOperationAction(ISD::FEXP, MVT::f80, Expand);
520   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
521
522   // First set operation action for all vector types to either promote
523   // (for widening) or expand (for scalarization). Then we will selectively
524   // turn on ones that can be effectively codegen'd.
525   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
526        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
527     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
528     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
529     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
530     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
531     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
532     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
533     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
534     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
535     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
536     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
537     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
538     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
539     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
542     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
543     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
575   }
576
577   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
578   // with -msoft-float, disable use of MMX as well.
579   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
580     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
581     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
582     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
583     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
584     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
585
586     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
587     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
588     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
589     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
590
591     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
592     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
593     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
594     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
595
596     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
597     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
598
599     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
600     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
601     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
602     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
603     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
604     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
605     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
606
607     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
608     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
609     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
610     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
611     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
612     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
613     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
614
615     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
616     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
617     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
618     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
619     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
620     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
621     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
622
623     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
624     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
625     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
626     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
627     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
628     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
629     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
630     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
631     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
632
633     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
634     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
635     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
636     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
637     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
638
639     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
640     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
641     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
642     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
643
644     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
645     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
646     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
647     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
648
649     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
650
651     setTruncStoreAction(MVT::v8i16,             MVT::v8i8, Expand);
652     setOperationAction(ISD::TRUNCATE,           MVT::v8i8, Expand);
653     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
654     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
655     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
656     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
657     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
658     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
659     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
660   }
661
662   if (!UseSoftFloat && Subtarget->hasSSE1()) {
663     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
664
665     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
666     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
667     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
668     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
669     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
670     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
671     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
674     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
675     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
676     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
677   }
678
679   if (!UseSoftFloat && Subtarget->hasSSE2()) {
680     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
681
682     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
683     // registers cannot be used even for integer operations.
684     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
685     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
686     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
687     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
688
689     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
690     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
691     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
692     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
693     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
694     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
695     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
696     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
697     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
698     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
699     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
700     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
701     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
702     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
703     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
704     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
705
706     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
707     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
708     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
709     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
710
711     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
712     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
713     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
714     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
715     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
716
717     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
718     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
719       EVT VT = (MVT::SimpleValueType)i;
720       // Do not attempt to custom lower non-power-of-2 vectors
721       if (!isPowerOf2_32(VT.getVectorNumElements()))
722         continue;
723       // Do not attempt to custom lower non-128-bit vectors
724       if (!VT.is128BitVector())
725         continue;
726       setOperationAction(ISD::BUILD_VECTOR,
727                          VT.getSimpleVT().SimpleTy, Custom);
728       setOperationAction(ISD::VECTOR_SHUFFLE,
729                          VT.getSimpleVT().SimpleTy, Custom);
730       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
731                          VT.getSimpleVT().SimpleTy, Custom);
732     }
733
734     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
735     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
736     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
737     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
738     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
739     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
740
741     if (Subtarget->is64Bit()) {
742       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
743       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
744     }
745
746     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
747     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
748       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
749       EVT VT = SVT;
750
751       // Do not attempt to promote non-128-bit vectors
752       if (!VT.is128BitVector()) {
753         continue;
754       }
755       setOperationAction(ISD::AND,    SVT, Promote);
756       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
757       setOperationAction(ISD::OR,     SVT, Promote);
758       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
759       setOperationAction(ISD::XOR,    SVT, Promote);
760       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
761       setOperationAction(ISD::LOAD,   SVT, Promote);
762       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
763       setOperationAction(ISD::SELECT, SVT, Promote);
764       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
765     }
766
767     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
768
769     // Custom lower v2i64 and v2f64 selects.
770     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
771     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
772     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
773     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
774
775     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
776     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
777     if (!DisableMMX && Subtarget->hasMMX()) {
778       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
779       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
780     }
781   }
782
783   if (Subtarget->hasSSE41()) {
784     // FIXME: Do we need to handle scalar-to-vector here?
785     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
786
787     // i8 and i16 vectors are custom , because the source register and source
788     // source memory operand types are not the same width.  f32 vectors are
789     // custom since the immediate controlling the insert encodes additional
790     // information.
791     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
792     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
793     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
794     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
795
796     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
797     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
798     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
799     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
800
801     if (Subtarget->is64Bit()) {
802       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
803       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
804     }
805   }
806
807   if (Subtarget->hasSSE42()) {
808     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
809   }
810
811   if (!UseSoftFloat && Subtarget->hasAVX()) {
812     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
813     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
814     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
815     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
816
817     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
818     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
819     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
820     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
821     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
827     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
828     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
829     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
830     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
831     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
832
833     // Operations to consider commented out -v16i16 v32i8
834     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
835     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
836     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
837     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
838     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
839     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
840     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
841     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
842     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
843     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
844     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
845     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
846     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
847     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
848
849     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
850     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
851     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
852     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
853
854     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
855     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
856     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
857     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
858     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
859
860     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
861     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
862     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
863     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
865     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
866
867 #if 0
868     // Not sure we want to do this since there are no 256-bit integer
869     // operations in AVX
870
871     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
872     // This includes 256-bit vectors
873     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
874       EVT VT = (MVT::SimpleValueType)i;
875
876       // Do not attempt to custom lower non-power-of-2 vectors
877       if (!isPowerOf2_32(VT.getVectorNumElements()))
878         continue;
879
880       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
881       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
882       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
883     }
884
885     if (Subtarget->is64Bit()) {
886       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
888     }
889 #endif
890
891 #if 0
892     // Not sure we want to do this since there are no 256-bit integer
893     // operations in AVX
894
895     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
896     // Including 256-bit vectors
897     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
898       EVT VT = (MVT::SimpleValueType)i;
899
900       if (!VT.is256BitVector()) {
901         continue;
902       }
903       setOperationAction(ISD::AND,    VT, Promote);
904       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
905       setOperationAction(ISD::OR,     VT, Promote);
906       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
907       setOperationAction(ISD::XOR,    VT, Promote);
908       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
909       setOperationAction(ISD::LOAD,   VT, Promote);
910       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
911       setOperationAction(ISD::SELECT, VT, Promote);
912       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
913     }
914
915     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
916 #endif
917   }
918
919   // We want to custom lower some of our intrinsics.
920   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
921
922   // Add/Sub/Mul with overflow operations are custom lowered.
923   setOperationAction(ISD::SADDO, MVT::i32, Custom);
924   setOperationAction(ISD::SADDO, MVT::i64, Custom);
925   setOperationAction(ISD::UADDO, MVT::i32, Custom);
926   setOperationAction(ISD::UADDO, MVT::i64, Custom);
927   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
928   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
929   setOperationAction(ISD::USUBO, MVT::i32, Custom);
930   setOperationAction(ISD::USUBO, MVT::i64, Custom);
931   setOperationAction(ISD::SMULO, MVT::i32, Custom);
932   setOperationAction(ISD::SMULO, MVT::i64, Custom);
933
934   if (!Subtarget->is64Bit()) {
935     // These libcalls are not available in 32-bit.
936     setLibcallName(RTLIB::SHL_I128, 0);
937     setLibcallName(RTLIB::SRL_I128, 0);
938     setLibcallName(RTLIB::SRA_I128, 0);
939   }
940
941   // We have target-specific dag combine patterns for the following nodes:
942   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
943   setTargetDAGCombine(ISD::BUILD_VECTOR);
944   setTargetDAGCombine(ISD::SELECT);
945   setTargetDAGCombine(ISD::SHL);
946   setTargetDAGCombine(ISD::SRA);
947   setTargetDAGCombine(ISD::SRL);
948   setTargetDAGCombine(ISD::STORE);
949   setTargetDAGCombine(ISD::MEMBARRIER);
950   if (Subtarget->is64Bit())
951     setTargetDAGCombine(ISD::MUL);
952
953   computeRegisterProperties();
954
955   // FIXME: These should be based on subtarget info. Plus, the values should
956   // be smaller when we are in optimizing for size mode.
957   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
958   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
959   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
960   setPrefLoopAlignment(16);
961   benefitFromCodePlacementOpt = true;
962 }
963
964
965 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
966   return MVT::i8;
967 }
968
969
970 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
971 /// the desired ByVal argument alignment.
972 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
973   if (MaxAlign == 16)
974     return;
975   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
976     if (VTy->getBitWidth() == 128)
977       MaxAlign = 16;
978   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
979     unsigned EltAlign = 0;
980     getMaxByValAlign(ATy->getElementType(), EltAlign);
981     if (EltAlign > MaxAlign)
982       MaxAlign = EltAlign;
983   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
984     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
985       unsigned EltAlign = 0;
986       getMaxByValAlign(STy->getElementType(i), EltAlign);
987       if (EltAlign > MaxAlign)
988         MaxAlign = EltAlign;
989       if (MaxAlign == 16)
990         break;
991     }
992   }
993   return;
994 }
995
996 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
997 /// function arguments in the caller parameter area. For X86, aggregates
998 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
999 /// are at 4-byte boundaries.
1000 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1001   if (Subtarget->is64Bit()) {
1002     // Max of 8 and alignment of type.
1003     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1004     if (TyAlign > 8)
1005       return TyAlign;
1006     return 8;
1007   }
1008
1009   unsigned Align = 4;
1010   if (Subtarget->hasSSE1())
1011     getMaxByValAlign(Ty, Align);
1012   return Align;
1013 }
1014
1015 /// getOptimalMemOpType - Returns the target specific optimal type for load
1016 /// and store operations as a result of memset, memcpy, and memmove
1017 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1018 /// determining it.
1019 EVT
1020 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1021                                        bool isSrcConst, bool isSrcStr,
1022                                        SelectionDAG &DAG) const {
1023   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1024   // linux.  This is because the stack realignment code can't handle certain
1025   // cases like PR2962.  This should be removed when PR2962 is fixed.
1026   const Function *F = DAG.getMachineFunction().getFunction();
1027   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1028   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1029     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1030       return MVT::v4i32;
1031     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1032       return MVT::v4f32;
1033   }
1034   if (Subtarget->is64Bit() && Size >= 8)
1035     return MVT::i64;
1036   return MVT::i32;
1037 }
1038
1039 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1040 /// jumptable.
1041 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1042                                                       SelectionDAG &DAG) const {
1043   if (usesGlobalOffsetTable())
1044     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1045   if (!Subtarget->is64Bit())
1046     // This doesn't have DebugLoc associated with it, but is not really the
1047     // same as a Register.
1048     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1049                        getPointerTy());
1050   return Table;
1051 }
1052
1053 /// getFunctionAlignment - Return the Log2 alignment of this function.
1054 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1055   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1056 }
1057
1058 /// getPreferredLSDADataFormat - Return the preferred exception handling data
1059 /// format for the LSDA.
1060 unsigned X86TargetLowering::getPreferredLSDADataFormat() const {
1061   if (Subtarget->isTargetDarwin())
1062     return dwarf::DW_EH_PE_pcrel;
1063
1064   CodeModel::Model M = getTargetMachine().getCodeModel();
1065
1066   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1067     if (!Subtarget->is64Bit() || M == CodeModel::Small)
1068       return dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1069
1070     return dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
1071   }
1072
1073   if (M == CodeModel::Small)
1074     return dwarf::DW_EH_PE_sdata4;
1075
1076   return dwarf::DW_EH_PE_absptr;
1077 }
1078
1079 /// getPreferredFDEDataFormat - Return the preferred exception handling data
1080 /// format for the FDE.
1081 unsigned X86TargetLowering::getPreferredFDEDataFormat() const {
1082   if (Subtarget->isTargetDarwin())
1083     return dwarf::DW_EH_PE_pcrel;
1084
1085   CodeModel::Model M = getTargetMachine().getCodeModel();
1086
1087   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1088     if (!Subtarget->is64Bit() ||
1089         M == CodeModel::Small || M == CodeModel::Medium)
1090       return dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1091
1092     return dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
1093   }
1094
1095   if (M == CodeModel::Small || M == CodeModel::Medium)
1096     return dwarf::DW_EH_PE_sdata4;
1097
1098   return dwarf::DW_EH_PE_absptr;
1099 }
1100
1101 //===----------------------------------------------------------------------===//
1102 //               Return Value Calling Convention Implementation
1103 //===----------------------------------------------------------------------===//
1104
1105 #include "X86GenCallingConv.inc"
1106
1107 SDValue
1108 X86TargetLowering::LowerReturn(SDValue Chain,
1109                                unsigned CallConv, bool isVarArg,
1110                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1111                                DebugLoc dl, SelectionDAG &DAG) {
1112
1113   SmallVector<CCValAssign, 16> RVLocs;
1114   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1115                  RVLocs, *DAG.getContext());
1116   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1117
1118   // If this is the first return lowered for this function, add the regs to the
1119   // liveout set for the function.
1120   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1121     for (unsigned i = 0; i != RVLocs.size(); ++i)
1122       if (RVLocs[i].isRegLoc())
1123         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1124   }
1125
1126   SDValue Flag;
1127
1128   SmallVector<SDValue, 6> RetOps;
1129   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1130   // Operand #1 = Bytes To Pop
1131   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1132
1133   // Copy the result values into the output registers.
1134   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1135     CCValAssign &VA = RVLocs[i];
1136     assert(VA.isRegLoc() && "Can only return in registers!");
1137     SDValue ValToCopy = Outs[i].Val;
1138
1139     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1140     // the RET instruction and handled by the FP Stackifier.
1141     if (VA.getLocReg() == X86::ST0 ||
1142         VA.getLocReg() == X86::ST1) {
1143       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1144       // change the value to the FP stack register class.
1145       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1146         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1147       RetOps.push_back(ValToCopy);
1148       // Don't emit a copytoreg.
1149       continue;
1150     }
1151
1152     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1153     // which is returned in RAX / RDX.
1154     if (Subtarget->is64Bit()) {
1155       EVT ValVT = ValToCopy.getValueType();
1156       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1157         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1158         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1159           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1160       }
1161     }
1162
1163     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1164     Flag = Chain.getValue(1);
1165   }
1166
1167   // The x86-64 ABI for returning structs by value requires that we copy
1168   // the sret argument into %rax for the return. We saved the argument into
1169   // a virtual register in the entry block, so now we copy the value out
1170   // and into %rax.
1171   if (Subtarget->is64Bit() &&
1172       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1173     MachineFunction &MF = DAG.getMachineFunction();
1174     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1175     unsigned Reg = FuncInfo->getSRetReturnReg();
1176     if (!Reg) {
1177       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1178       FuncInfo->setSRetReturnReg(Reg);
1179     }
1180     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1181
1182     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1183     Flag = Chain.getValue(1);
1184   }
1185
1186   RetOps[0] = Chain;  // Update chain.
1187
1188   // Add the flag if we have it.
1189   if (Flag.getNode())
1190     RetOps.push_back(Flag);
1191
1192   return DAG.getNode(X86ISD::RET_FLAG, dl,
1193                      MVT::Other, &RetOps[0], RetOps.size());
1194 }
1195
1196 /// LowerCallResult - Lower the result values of a call into the
1197 /// appropriate copies out of appropriate physical registers.
1198 ///
1199 SDValue
1200 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1201                                    unsigned CallConv, bool isVarArg,
1202                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1203                                    DebugLoc dl, SelectionDAG &DAG,
1204                                    SmallVectorImpl<SDValue> &InVals) {
1205
1206   // Assign locations to each value returned by this call.
1207   SmallVector<CCValAssign, 16> RVLocs;
1208   bool Is64Bit = Subtarget->is64Bit();
1209   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1210                  RVLocs, *DAG.getContext());
1211   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1212
1213   // Copy all of the result registers out of their specified physreg.
1214   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1215     CCValAssign &VA = RVLocs[i];
1216     EVT CopyVT = VA.getValVT();
1217
1218     // If this is x86-64, and we disabled SSE, we can't return FP values
1219     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1220         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1221       llvm_report_error("SSE register return with SSE disabled");
1222     }
1223
1224     // If this is a call to a function that returns an fp value on the floating
1225     // point stack, but where we prefer to use the value in xmm registers, copy
1226     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1227     if ((VA.getLocReg() == X86::ST0 ||
1228          VA.getLocReg() == X86::ST1) &&
1229         isScalarFPTypeInSSEReg(VA.getValVT())) {
1230       CopyVT = MVT::f80;
1231     }
1232
1233     SDValue Val;
1234     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1235       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1236       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1237         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1238                                    MVT::v2i64, InFlag).getValue(1);
1239         Val = Chain.getValue(0);
1240         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1241                           Val, DAG.getConstant(0, MVT::i64));
1242       } else {
1243         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1244                                    MVT::i64, InFlag).getValue(1);
1245         Val = Chain.getValue(0);
1246       }
1247       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1248     } else {
1249       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1250                                  CopyVT, InFlag).getValue(1);
1251       Val = Chain.getValue(0);
1252     }
1253     InFlag = Chain.getValue(2);
1254
1255     if (CopyVT != VA.getValVT()) {
1256       // Round the F80 the right size, which also moves to the appropriate xmm
1257       // register.
1258       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1259                         // This truncation won't change the value.
1260                         DAG.getIntPtrConstant(1));
1261     }
1262
1263     InVals.push_back(Val);
1264   }
1265
1266   return Chain;
1267 }
1268
1269
1270 //===----------------------------------------------------------------------===//
1271 //                C & StdCall & Fast Calling Convention implementation
1272 //===----------------------------------------------------------------------===//
1273 //  StdCall calling convention seems to be standard for many Windows' API
1274 //  routines and around. It differs from C calling convention just a little:
1275 //  callee should clean up the stack, not caller. Symbols should be also
1276 //  decorated in some fancy way :) It doesn't support any vector arguments.
1277 //  For info on fast calling convention see Fast Calling Convention (tail call)
1278 //  implementation LowerX86_32FastCCCallTo.
1279
1280 /// CallIsStructReturn - Determines whether a call uses struct return
1281 /// semantics.
1282 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1283   if (Outs.empty())
1284     return false;
1285
1286   return Outs[0].Flags.isSRet();
1287 }
1288
1289 /// ArgsAreStructReturn - Determines whether a function uses struct
1290 /// return semantics.
1291 static bool
1292 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1293   if (Ins.empty())
1294     return false;
1295
1296   return Ins[0].Flags.isSRet();
1297 }
1298
1299 /// IsCalleePop - Determines whether the callee is required to pop its
1300 /// own arguments. Callee pop is necessary to support tail calls.
1301 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1302   if (IsVarArg)
1303     return false;
1304
1305   switch (CallingConv) {
1306   default:
1307     return false;
1308   case CallingConv::X86_StdCall:
1309     return !Subtarget->is64Bit();
1310   case CallingConv::X86_FastCall:
1311     return !Subtarget->is64Bit();
1312   case CallingConv::Fast:
1313     return PerformTailCallOpt;
1314   }
1315 }
1316
1317 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1318 /// given CallingConvention value.
1319 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1320   if (Subtarget->is64Bit()) {
1321     if (Subtarget->isTargetWin64())
1322       return CC_X86_Win64_C;
1323     else
1324       return CC_X86_64_C;
1325   }
1326
1327   if (CC == CallingConv::X86_FastCall)
1328     return CC_X86_32_FastCall;
1329   else if (CC == CallingConv::Fast)
1330     return CC_X86_32_FastCC;
1331   else
1332     return CC_X86_32_C;
1333 }
1334
1335 /// NameDecorationForCallConv - Selects the appropriate decoration to
1336 /// apply to a MachineFunction containing a given calling convention.
1337 NameDecorationStyle
1338 X86TargetLowering::NameDecorationForCallConv(unsigned CallConv) {
1339   if (CallConv == CallingConv::X86_FastCall)
1340     return FastCall;
1341   else if (CallConv == CallingConv::X86_StdCall)
1342     return StdCall;
1343   return None;
1344 }
1345
1346
1347 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1348 /// by "Src" to address "Dst" with size and alignment information specified by
1349 /// the specific parameter attribute. The copy will be passed as a byval
1350 /// function parameter.
1351 static SDValue
1352 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1353                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1354                           DebugLoc dl) {
1355   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1356   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1357                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1358 }
1359
1360 SDValue
1361 X86TargetLowering::LowerMemArgument(SDValue Chain,
1362                                     unsigned CallConv,
1363                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1364                                     DebugLoc dl, SelectionDAG &DAG,
1365                                     const CCValAssign &VA,
1366                                     MachineFrameInfo *MFI,
1367                                     unsigned i) {
1368
1369   // Create the nodes corresponding to a load from this parameter slot.
1370   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1371   bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1372   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1373   EVT ValVT;
1374
1375   // If value is passed by pointer we have address passed instead of the value
1376   // itself.
1377   if (VA.getLocInfo() == CCValAssign::Indirect)
1378     ValVT = VA.getLocVT();
1379   else
1380     ValVT = VA.getValVT();
1381
1382   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1383   // changed with more analysis.
1384   // In case of tail call optimization mark all arguments mutable. Since they
1385   // could be overwritten by lowering of arguments in case of a tail call.
1386   int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1387                                   VA.getLocMemOffset(), isImmutable);
1388   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1389   if (Flags.isByVal())
1390     return FIN;
1391   return DAG.getLoad(ValVT, dl, Chain, FIN,
1392                      PseudoSourceValue::getFixedStack(FI), 0);
1393 }
1394
1395 SDValue
1396 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1397                                         unsigned CallConv,
1398                                         bool isVarArg,
1399                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1400                                         DebugLoc dl,
1401                                         SelectionDAG &DAG,
1402                                         SmallVectorImpl<SDValue> &InVals) {
1403
1404   MachineFunction &MF = DAG.getMachineFunction();
1405   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1406
1407   const Function* Fn = MF.getFunction();
1408   if (Fn->hasExternalLinkage() &&
1409       Subtarget->isTargetCygMing() &&
1410       Fn->getName() == "main")
1411     FuncInfo->setForceFramePointer(true);
1412
1413   // Decorate the function name.
1414   FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1415
1416   MachineFrameInfo *MFI = MF.getFrameInfo();
1417   bool Is64Bit = Subtarget->is64Bit();
1418   bool IsWin64 = Subtarget->isTargetWin64();
1419
1420   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1421          "Var args not supported with calling convention fastcc");
1422
1423   // Assign locations to all of the incoming arguments.
1424   SmallVector<CCValAssign, 16> ArgLocs;
1425   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1426                  ArgLocs, *DAG.getContext());
1427   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1428
1429   unsigned LastVal = ~0U;
1430   SDValue ArgValue;
1431   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1432     CCValAssign &VA = ArgLocs[i];
1433     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1434     // places.
1435     assert(VA.getValNo() != LastVal &&
1436            "Don't support value assigned to multiple locs yet");
1437     LastVal = VA.getValNo();
1438
1439     if (VA.isRegLoc()) {
1440       EVT RegVT = VA.getLocVT();
1441       TargetRegisterClass *RC = NULL;
1442       if (RegVT == MVT::i32)
1443         RC = X86::GR32RegisterClass;
1444       else if (Is64Bit && RegVT == MVT::i64)
1445         RC = X86::GR64RegisterClass;
1446       else if (RegVT == MVT::f32)
1447         RC = X86::FR32RegisterClass;
1448       else if (RegVT == MVT::f64)
1449         RC = X86::FR64RegisterClass;
1450       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1451         RC = X86::VR128RegisterClass;
1452       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1453         RC = X86::VR64RegisterClass;
1454       else
1455         llvm_unreachable("Unknown argument type!");
1456
1457       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1458       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1459
1460       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1461       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1462       // right size.
1463       if (VA.getLocInfo() == CCValAssign::SExt)
1464         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1465                                DAG.getValueType(VA.getValVT()));
1466       else if (VA.getLocInfo() == CCValAssign::ZExt)
1467         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1468                                DAG.getValueType(VA.getValVT()));
1469       else if (VA.getLocInfo() == CCValAssign::BCvt)
1470         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1471
1472       if (VA.isExtInLoc()) {
1473         // Handle MMX values passed in XMM regs.
1474         if (RegVT.isVector()) {
1475           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1476                                  ArgValue, DAG.getConstant(0, MVT::i64));
1477           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1478         } else
1479           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1480       }
1481     } else {
1482       assert(VA.isMemLoc());
1483       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1484     }
1485
1486     // If value is passed via pointer - do a load.
1487     if (VA.getLocInfo() == CCValAssign::Indirect)
1488       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1489
1490     InVals.push_back(ArgValue);
1491   }
1492
1493   // The x86-64 ABI for returning structs by value requires that we copy
1494   // the sret argument into %rax for the return. Save the argument into
1495   // a virtual register so that we can access it from the return points.
1496   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1497     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1498     unsigned Reg = FuncInfo->getSRetReturnReg();
1499     if (!Reg) {
1500       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1501       FuncInfo->setSRetReturnReg(Reg);
1502     }
1503     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1504     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1505   }
1506
1507   unsigned StackSize = CCInfo.getNextStackOffset();
1508   // align stack specially for tail calls
1509   if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1510     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1511
1512   // If the function takes variable number of arguments, make a frame index for
1513   // the start of the first vararg value... for expansion of llvm.va_start.
1514   if (isVarArg) {
1515     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1516       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1517     }
1518     if (Is64Bit) {
1519       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1520
1521       // FIXME: We should really autogenerate these arrays
1522       static const unsigned GPR64ArgRegsWin64[] = {
1523         X86::RCX, X86::RDX, X86::R8,  X86::R9
1524       };
1525       static const unsigned XMMArgRegsWin64[] = {
1526         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1527       };
1528       static const unsigned GPR64ArgRegs64Bit[] = {
1529         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1530       };
1531       static const unsigned XMMArgRegs64Bit[] = {
1532         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1533         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1534       };
1535       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1536
1537       if (IsWin64) {
1538         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1539         GPR64ArgRegs = GPR64ArgRegsWin64;
1540         XMMArgRegs = XMMArgRegsWin64;
1541       } else {
1542         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1543         GPR64ArgRegs = GPR64ArgRegs64Bit;
1544         XMMArgRegs = XMMArgRegs64Bit;
1545       }
1546       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1547                                                        TotalNumIntRegs);
1548       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1549                                                        TotalNumXMMRegs);
1550
1551       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1552       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1553              "SSE register cannot be used when SSE is disabled!");
1554       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1555              "SSE register cannot be used when SSE is disabled!");
1556       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1557         // Kernel mode asks for SSE to be disabled, so don't push them
1558         // on the stack.
1559         TotalNumXMMRegs = 0;
1560
1561       // For X86-64, if there are vararg parameters that are passed via
1562       // registers, then we must store them to their spots on the stack so they
1563       // may be loaded by deferencing the result of va_next.
1564       VarArgsGPOffset = NumIntRegs * 8;
1565       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1566       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1567                                                  TotalNumXMMRegs * 16, 16);
1568
1569       // Store the integer parameter registers.
1570       SmallVector<SDValue, 8> MemOps;
1571       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1572       unsigned Offset = VarArgsGPOffset;
1573       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1574         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1575                                   DAG.getIntPtrConstant(Offset));
1576         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1577                                      X86::GR64RegisterClass);
1578         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1579         SDValue Store =
1580           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1581                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1582                        Offset);
1583         MemOps.push_back(Store);
1584         Offset += 8;
1585       }
1586
1587       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1588         // Now store the XMM (fp + vector) parameter registers.
1589         SmallVector<SDValue, 11> SaveXMMOps;
1590         SaveXMMOps.push_back(Chain);
1591
1592         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1593         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1594         SaveXMMOps.push_back(ALVal);
1595
1596         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1597         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1598
1599         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1600           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1601                                        X86::VR128RegisterClass);
1602           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1603           SaveXMMOps.push_back(Val);
1604         }
1605         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1606                                      MVT::Other,
1607                                      &SaveXMMOps[0], SaveXMMOps.size()));
1608       }
1609
1610       if (!MemOps.empty())
1611         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1612                             &MemOps[0], MemOps.size());
1613     }
1614   }
1615
1616   // Some CCs need callee pop.
1617   if (IsCalleePop(isVarArg, CallConv)) {
1618     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1619     BytesCallerReserves = 0;
1620   } else {
1621     BytesToPopOnReturn  = 0; // Callee pops nothing.
1622     // If this is an sret function, the return should pop the hidden pointer.
1623     if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1624       BytesToPopOnReturn = 4;
1625     BytesCallerReserves = StackSize;
1626   }
1627
1628   if (!Is64Bit) {
1629     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1630     if (CallConv == CallingConv::X86_FastCall)
1631       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1632   }
1633
1634   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1635
1636   return Chain;
1637 }
1638
1639 SDValue
1640 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1641                                     SDValue StackPtr, SDValue Arg,
1642                                     DebugLoc dl, SelectionDAG &DAG,
1643                                     const CCValAssign &VA,
1644                                     ISD::ArgFlagsTy Flags) {
1645   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1646   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1647   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1648   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1649   if (Flags.isByVal()) {
1650     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1651   }
1652   return DAG.getStore(Chain, dl, Arg, PtrOff,
1653                       PseudoSourceValue::getStack(), LocMemOffset);
1654 }
1655
1656 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1657 /// optimization is performed and it is required.
1658 SDValue
1659 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1660                                            SDValue &OutRetAddr,
1661                                            SDValue Chain,
1662                                            bool IsTailCall,
1663                                            bool Is64Bit,
1664                                            int FPDiff,
1665                                            DebugLoc dl) {
1666   if (!IsTailCall || FPDiff==0) return Chain;
1667
1668   // Adjust the Return address stack slot.
1669   EVT VT = getPointerTy();
1670   OutRetAddr = getReturnAddressFrameIndex(DAG);
1671
1672   // Load the "old" Return address.
1673   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1674   return SDValue(OutRetAddr.getNode(), 1);
1675 }
1676
1677 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1678 /// optimization is performed and it is required (FPDiff!=0).
1679 static SDValue
1680 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1681                          SDValue Chain, SDValue RetAddrFrIdx,
1682                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1683   // Store the return address to the appropriate stack slot.
1684   if (!FPDiff) return Chain;
1685   // Calculate the new stack slot for the return address.
1686   int SlotSize = Is64Bit ? 8 : 4;
1687   int NewReturnAddrFI =
1688     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1689   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1690   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1691   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1692                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1693   return Chain;
1694 }
1695
1696 SDValue
1697 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1698                              unsigned CallConv, bool isVarArg, bool isTailCall,
1699                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1700                              const SmallVectorImpl<ISD::InputArg> &Ins,
1701                              DebugLoc dl, SelectionDAG &DAG,
1702                              SmallVectorImpl<SDValue> &InVals) {
1703
1704   MachineFunction &MF = DAG.getMachineFunction();
1705   bool Is64Bit        = Subtarget->is64Bit();
1706   bool IsStructRet    = CallIsStructReturn(Outs);
1707
1708   assert((!isTailCall ||
1709           (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1710          "IsEligibleForTailCallOptimization missed a case!");
1711   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1712          "Var args not supported with calling convention fastcc");
1713
1714   // Analyze operands of the call, assigning locations to each operand.
1715   SmallVector<CCValAssign, 16> ArgLocs;
1716   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1717                  ArgLocs, *DAG.getContext());
1718   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1719
1720   // Get a count of how many bytes are to be pushed on the stack.
1721   unsigned NumBytes = CCInfo.getNextStackOffset();
1722   if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1723     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1724
1725   int FPDiff = 0;
1726   if (isTailCall) {
1727     // Lower arguments at fp - stackoffset + fpdiff.
1728     unsigned NumBytesCallerPushed =
1729       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1730     FPDiff = NumBytesCallerPushed - NumBytes;
1731
1732     // Set the delta of movement of the returnaddr stackslot.
1733     // But only set if delta is greater than previous delta.
1734     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1735       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1736   }
1737
1738   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1739
1740   SDValue RetAddrFrIdx;
1741   // Load return adress for tail calls.
1742   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1743                                   FPDiff, dl);
1744
1745   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1746   SmallVector<SDValue, 8> MemOpChains;
1747   SDValue StackPtr;
1748
1749   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1750   // of tail call optimization arguments are handle later.
1751   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1752     CCValAssign &VA = ArgLocs[i];
1753     EVT RegVT = VA.getLocVT();
1754     SDValue Arg = Outs[i].Val;
1755     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1756     bool isByVal = Flags.isByVal();
1757
1758     // Promote the value if needed.
1759     switch (VA.getLocInfo()) {
1760     default: llvm_unreachable("Unknown loc info!");
1761     case CCValAssign::Full: break;
1762     case CCValAssign::SExt:
1763       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1764       break;
1765     case CCValAssign::ZExt:
1766       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1767       break;
1768     case CCValAssign::AExt:
1769       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1770         // Special case: passing MMX values in XMM registers.
1771         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1772         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1773         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1774       } else
1775         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1776       break;
1777     case CCValAssign::BCvt:
1778       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1779       break;
1780     case CCValAssign::Indirect: {
1781       // Store the argument.
1782       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1783       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1784       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1785                            PseudoSourceValue::getFixedStack(FI), 0);
1786       Arg = SpillSlot;
1787       break;
1788     }
1789     }
1790
1791     if (VA.isRegLoc()) {
1792       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1793     } else {
1794       if (!isTailCall || (isTailCall && isByVal)) {
1795         assert(VA.isMemLoc());
1796         if (StackPtr.getNode() == 0)
1797           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1798
1799         MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1800                                                dl, DAG, VA, Flags));
1801       }
1802     }
1803   }
1804
1805   if (!MemOpChains.empty())
1806     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1807                         &MemOpChains[0], MemOpChains.size());
1808
1809   // Build a sequence of copy-to-reg nodes chained together with token chain
1810   // and flag operands which copy the outgoing args into registers.
1811   SDValue InFlag;
1812   // Tail call byval lowering might overwrite argument registers so in case of
1813   // tail call optimization the copies to registers are lowered later.
1814   if (!isTailCall)
1815     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1816       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1817                                RegsToPass[i].second, InFlag);
1818       InFlag = Chain.getValue(1);
1819     }
1820
1821
1822   if (Subtarget->isPICStyleGOT()) {
1823     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1824     // GOT pointer.
1825     if (!isTailCall) {
1826       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1827                                DAG.getNode(X86ISD::GlobalBaseReg,
1828                                            DebugLoc::getUnknownLoc(),
1829                                            getPointerTy()),
1830                                InFlag);
1831       InFlag = Chain.getValue(1);
1832     } else {
1833       // If we are tail calling and generating PIC/GOT style code load the
1834       // address of the callee into ECX. The value in ecx is used as target of
1835       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1836       // for tail calls on PIC/GOT architectures. Normally we would just put the
1837       // address of GOT into ebx and then call target@PLT. But for tail calls
1838       // ebx would be restored (since ebx is callee saved) before jumping to the
1839       // target@PLT.
1840
1841       // Note: The actual moving to ECX is done further down.
1842       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1843       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1844           !G->getGlobal()->hasProtectedVisibility())
1845         Callee = LowerGlobalAddress(Callee, DAG);
1846       else if (isa<ExternalSymbolSDNode>(Callee))
1847         Callee = LowerExternalSymbol(Callee, DAG);
1848     }
1849   }
1850
1851   if (Is64Bit && isVarArg) {
1852     // From AMD64 ABI document:
1853     // For calls that may call functions that use varargs or stdargs
1854     // (prototype-less calls or calls to functions containing ellipsis (...) in
1855     // the declaration) %al is used as hidden argument to specify the number
1856     // of SSE registers used. The contents of %al do not need to match exactly
1857     // the number of registers, but must be an ubound on the number of SSE
1858     // registers used and is in the range 0 - 8 inclusive.
1859
1860     // FIXME: Verify this on Win64
1861     // Count the number of XMM registers allocated.
1862     static const unsigned XMMArgRegs[] = {
1863       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1864       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1865     };
1866     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1867     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1868            && "SSE registers cannot be used when SSE is disabled");
1869
1870     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1871                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1872     InFlag = Chain.getValue(1);
1873   }
1874
1875
1876   // For tail calls lower the arguments to the 'real' stack slot.
1877   if (isTailCall) {
1878     // Force all the incoming stack arguments to be loaded from the stack
1879     // before any new outgoing arguments are stored to the stack, because the
1880     // outgoing stack slots may alias the incoming argument stack slots, and
1881     // the alias isn't otherwise explicit. This is slightly more conservative
1882     // than necessary, because it means that each store effectively depends
1883     // on every argument instead of just those arguments it would clobber.
1884     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1885
1886     SmallVector<SDValue, 8> MemOpChains2;
1887     SDValue FIN;
1888     int FI = 0;
1889     // Do not flag preceeding copytoreg stuff together with the following stuff.
1890     InFlag = SDValue();
1891     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1892       CCValAssign &VA = ArgLocs[i];
1893       if (!VA.isRegLoc()) {
1894         assert(VA.isMemLoc());
1895         SDValue Arg = Outs[i].Val;
1896         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1897         // Create frame index.
1898         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1899         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1900         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1901         FIN = DAG.getFrameIndex(FI, getPointerTy());
1902
1903         if (Flags.isByVal()) {
1904           // Copy relative to framepointer.
1905           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1906           if (StackPtr.getNode() == 0)
1907             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1908                                           getPointerTy());
1909           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1910
1911           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1912                                                            ArgChain,
1913                                                            Flags, DAG, dl));
1914         } else {
1915           // Store relative to framepointer.
1916           MemOpChains2.push_back(
1917             DAG.getStore(ArgChain, dl, Arg, FIN,
1918                          PseudoSourceValue::getFixedStack(FI), 0));
1919         }
1920       }
1921     }
1922
1923     if (!MemOpChains2.empty())
1924       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1925                           &MemOpChains2[0], MemOpChains2.size());
1926
1927     // Copy arguments to their registers.
1928     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1929       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1930                                RegsToPass[i].second, InFlag);
1931       InFlag = Chain.getValue(1);
1932     }
1933     InFlag =SDValue();
1934
1935     // Store the return address to the appropriate stack slot.
1936     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1937                                      FPDiff, dl);
1938   }
1939
1940   // If the callee is a GlobalAddress node (quite common, every direct call is)
1941   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1942   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1943     // We should use extra load for direct calls to dllimported functions in
1944     // non-JIT mode.
1945     GlobalValue *GV = G->getGlobal();
1946     if (!GV->hasDLLImportLinkage()) {
1947       unsigned char OpFlags = 0;
1948
1949       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1950       // external symbols most go through the PLT in PIC mode.  If the symbol
1951       // has hidden or protected visibility, or if it is static or local, then
1952       // we don't need to use the PLT - we can directly call it.
1953       if (Subtarget->isTargetELF() &&
1954           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1955           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1956         OpFlags = X86II::MO_PLT;
1957       } else if (Subtarget->isPICStyleStubAny() &&
1958                (GV->isDeclaration() || GV->isWeakForLinker()) &&
1959                Subtarget->getDarwinVers() < 9) {
1960         // PC-relative references to external symbols should go through $stub,
1961         // unless we're building with the leopard linker or later, which
1962         // automatically synthesizes these stubs.
1963         OpFlags = X86II::MO_DARWIN_STUB;
1964       }
1965
1966       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1967                                           G->getOffset(), OpFlags);
1968     }
1969   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1970     unsigned char OpFlags = 0;
1971
1972     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1973     // symbols should go through the PLT.
1974     if (Subtarget->isTargetELF() &&
1975         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1976       OpFlags = X86II::MO_PLT;
1977     } else if (Subtarget->isPICStyleStubAny() &&
1978              Subtarget->getDarwinVers() < 9) {
1979       // PC-relative references to external symbols should go through $stub,
1980       // unless we're building with the leopard linker or later, which
1981       // automatically synthesizes these stubs.
1982       OpFlags = X86II::MO_DARWIN_STUB;
1983     }
1984
1985     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1986                                          OpFlags);
1987   } else if (isTailCall) {
1988     unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1989
1990     Chain = DAG.getCopyToReg(Chain,  dl,
1991                              DAG.getRegister(Opc, getPointerTy()),
1992                              Callee,InFlag);
1993     Callee = DAG.getRegister(Opc, getPointerTy());
1994     // Add register as live out.
1995     MF.getRegInfo().addLiveOut(Opc);
1996   }
1997
1998   // Returns a chain & a flag for retval copy to use.
1999   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2000   SmallVector<SDValue, 8> Ops;
2001
2002   if (isTailCall) {
2003     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2004                            DAG.getIntPtrConstant(0, true), InFlag);
2005     InFlag = Chain.getValue(1);
2006   }
2007
2008   Ops.push_back(Chain);
2009   Ops.push_back(Callee);
2010
2011   if (isTailCall)
2012     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2013
2014   // Add argument registers to the end of the list so that they are known live
2015   // into the call.
2016   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2017     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2018                                   RegsToPass[i].second.getValueType()));
2019
2020   // Add an implicit use GOT pointer in EBX.
2021   if (!isTailCall && Subtarget->isPICStyleGOT())
2022     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2023
2024   // Add an implicit use of AL for x86 vararg functions.
2025   if (Is64Bit && isVarArg)
2026     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2027
2028   if (InFlag.getNode())
2029     Ops.push_back(InFlag);
2030
2031   if (isTailCall) {
2032     // If this is the first return lowered for this function, add the regs
2033     // to the liveout set for the function.
2034     if (MF.getRegInfo().liveout_empty()) {
2035       SmallVector<CCValAssign, 16> RVLocs;
2036       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2037                      *DAG.getContext());
2038       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2039       for (unsigned i = 0; i != RVLocs.size(); ++i)
2040         if (RVLocs[i].isRegLoc())
2041           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2042     }
2043
2044     assert(((Callee.getOpcode() == ISD::Register &&
2045                (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2046                 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2047               Callee.getOpcode() == ISD::TargetExternalSymbol ||
2048               Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2049              "Expecting an global address, external symbol, or register");
2050
2051     return DAG.getNode(X86ISD::TC_RETURN, dl,
2052                        NodeTys, &Ops[0], Ops.size());
2053   }
2054
2055   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2056   InFlag = Chain.getValue(1);
2057
2058   // Create the CALLSEQ_END node.
2059   unsigned NumBytesForCalleeToPush;
2060   if (IsCalleePop(isVarArg, CallConv))
2061     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2062   else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2063     // If this is is a call to a struct-return function, the callee
2064     // pops the hidden struct pointer, so we have to push it back.
2065     // This is common for Darwin/X86, Linux & Mingw32 targets.
2066     NumBytesForCalleeToPush = 4;
2067   else
2068     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2069
2070   // Returns a flag for retval copy to use.
2071   Chain = DAG.getCALLSEQ_END(Chain,
2072                              DAG.getIntPtrConstant(NumBytes, true),
2073                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2074                                                    true),
2075                              InFlag);
2076   InFlag = Chain.getValue(1);
2077
2078   // Handle result values, copying them out of physregs into vregs that we
2079   // return.
2080   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2081                          Ins, dl, DAG, InVals);
2082 }
2083
2084
2085 //===----------------------------------------------------------------------===//
2086 //                Fast Calling Convention (tail call) implementation
2087 //===----------------------------------------------------------------------===//
2088
2089 //  Like std call, callee cleans arguments, convention except that ECX is
2090 //  reserved for storing the tail called function address. Only 2 registers are
2091 //  free for argument passing (inreg). Tail call optimization is performed
2092 //  provided:
2093 //                * tailcallopt is enabled
2094 //                * caller/callee are fastcc
2095 //  On X86_64 architecture with GOT-style position independent code only local
2096 //  (within module) calls are supported at the moment.
2097 //  To keep the stack aligned according to platform abi the function
2098 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2099 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2100 //  If a tail called function callee has more arguments than the caller the
2101 //  caller needs to make sure that there is room to move the RETADDR to. This is
2102 //  achieved by reserving an area the size of the argument delta right after the
2103 //  original REtADDR, but before the saved framepointer or the spilled registers
2104 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2105 //  stack layout:
2106 //    arg1
2107 //    arg2
2108 //    RETADDR
2109 //    [ new RETADDR
2110 //      move area ]
2111 //    (possible EBP)
2112 //    ESI
2113 //    EDI
2114 //    local1 ..
2115
2116 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2117 /// for a 16 byte align requirement.
2118 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2119                                                         SelectionDAG& DAG) {
2120   MachineFunction &MF = DAG.getMachineFunction();
2121   const TargetMachine &TM = MF.getTarget();
2122   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2123   unsigned StackAlignment = TFI.getStackAlignment();
2124   uint64_t AlignMask = StackAlignment - 1;
2125   int64_t Offset = StackSize;
2126   uint64_t SlotSize = TD->getPointerSize();
2127   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2128     // Number smaller than 12 so just add the difference.
2129     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2130   } else {
2131     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2132     Offset = ((~AlignMask) & Offset) + StackAlignment +
2133       (StackAlignment-SlotSize);
2134   }
2135   return Offset;
2136 }
2137
2138 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2139 /// for tail call optimization. Targets which want to do tail call
2140 /// optimization should implement this function.
2141 bool
2142 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2143                                                      unsigned CalleeCC,
2144                                                      bool isVarArg,
2145                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2146                                                      SelectionDAG& DAG) const {
2147   MachineFunction &MF = DAG.getMachineFunction();
2148   unsigned CallerCC = MF.getFunction()->getCallingConv();
2149   return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2150 }
2151
2152 FastISel *
2153 X86TargetLowering::createFastISel(MachineFunction &mf,
2154                                   MachineModuleInfo *mmo,
2155                                   DwarfWriter *dw,
2156                                   DenseMap<const Value *, unsigned> &vm,
2157                                   DenseMap<const BasicBlock *,
2158                                            MachineBasicBlock *> &bm,
2159                                   DenseMap<const AllocaInst *, int> &am
2160 #ifndef NDEBUG
2161                                   , SmallSet<Instruction*, 8> &cil
2162 #endif
2163                                   ) {
2164   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2165 #ifndef NDEBUG
2166                              , cil
2167 #endif
2168                              );
2169 }
2170
2171
2172 //===----------------------------------------------------------------------===//
2173 //                           Other Lowering Hooks
2174 //===----------------------------------------------------------------------===//
2175
2176
2177 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2178   MachineFunction &MF = DAG.getMachineFunction();
2179   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2180   int ReturnAddrIndex = FuncInfo->getRAIndex();
2181
2182   if (ReturnAddrIndex == 0) {
2183     // Set up a frame object for the return address.
2184     uint64_t SlotSize = TD->getPointerSize();
2185     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2186     FuncInfo->setRAIndex(ReturnAddrIndex);
2187   }
2188
2189   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2190 }
2191
2192
2193 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2194                                        bool hasSymbolicDisplacement) {
2195   // Offset should fit into 32 bit immediate field.
2196   if (!isInt32(Offset))
2197     return false;
2198
2199   // If we don't have a symbolic displacement - we don't have any extra
2200   // restrictions.
2201   if (!hasSymbolicDisplacement)
2202     return true;
2203
2204   // FIXME: Some tweaks might be needed for medium code model.
2205   if (M != CodeModel::Small && M != CodeModel::Kernel)
2206     return false;
2207
2208   // For small code model we assume that latest object is 16MB before end of 31
2209   // bits boundary. We may also accept pretty large negative constants knowing
2210   // that all objects are in the positive half of address space.
2211   if (M == CodeModel::Small && Offset < 16*1024*1024)
2212     return true;
2213
2214   // For kernel code model we know that all object resist in the negative half
2215   // of 32bits address space. We may not accept negative offsets, since they may
2216   // be just off and we may accept pretty large positive ones.
2217   if (M == CodeModel::Kernel && Offset > 0)
2218     return true;
2219
2220   return false;
2221 }
2222
2223 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2224 /// specific condition code, returning the condition code and the LHS/RHS of the
2225 /// comparison to make.
2226 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2227                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2228   if (!isFP) {
2229     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2230       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2231         // X > -1   -> X == 0, jump !sign.
2232         RHS = DAG.getConstant(0, RHS.getValueType());
2233         return X86::COND_NS;
2234       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2235         // X < 0   -> X == 0, jump on sign.
2236         return X86::COND_S;
2237       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2238         // X < 1   -> X <= 0
2239         RHS = DAG.getConstant(0, RHS.getValueType());
2240         return X86::COND_LE;
2241       }
2242     }
2243
2244     switch (SetCCOpcode) {
2245     default: llvm_unreachable("Invalid integer condition!");
2246     case ISD::SETEQ:  return X86::COND_E;
2247     case ISD::SETGT:  return X86::COND_G;
2248     case ISD::SETGE:  return X86::COND_GE;
2249     case ISD::SETLT:  return X86::COND_L;
2250     case ISD::SETLE:  return X86::COND_LE;
2251     case ISD::SETNE:  return X86::COND_NE;
2252     case ISD::SETULT: return X86::COND_B;
2253     case ISD::SETUGT: return X86::COND_A;
2254     case ISD::SETULE: return X86::COND_BE;
2255     case ISD::SETUGE: return X86::COND_AE;
2256     }
2257   }
2258
2259   // First determine if it is required or is profitable to flip the operands.
2260
2261   // If LHS is a foldable load, but RHS is not, flip the condition.
2262   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2263       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2264     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2265     std::swap(LHS, RHS);
2266   }
2267
2268   switch (SetCCOpcode) {
2269   default: break;
2270   case ISD::SETOLT:
2271   case ISD::SETOLE:
2272   case ISD::SETUGT:
2273   case ISD::SETUGE:
2274     std::swap(LHS, RHS);
2275     break;
2276   }
2277
2278   // On a floating point condition, the flags are set as follows:
2279   // ZF  PF  CF   op
2280   //  0 | 0 | 0 | X > Y
2281   //  0 | 0 | 1 | X < Y
2282   //  1 | 0 | 0 | X == Y
2283   //  1 | 1 | 1 | unordered
2284   switch (SetCCOpcode) {
2285   default: llvm_unreachable("Condcode should be pre-legalized away");
2286   case ISD::SETUEQ:
2287   case ISD::SETEQ:   return X86::COND_E;
2288   case ISD::SETOLT:              // flipped
2289   case ISD::SETOGT:
2290   case ISD::SETGT:   return X86::COND_A;
2291   case ISD::SETOLE:              // flipped
2292   case ISD::SETOGE:
2293   case ISD::SETGE:   return X86::COND_AE;
2294   case ISD::SETUGT:              // flipped
2295   case ISD::SETULT:
2296   case ISD::SETLT:   return X86::COND_B;
2297   case ISD::SETUGE:              // flipped
2298   case ISD::SETULE:
2299   case ISD::SETLE:   return X86::COND_BE;
2300   case ISD::SETONE:
2301   case ISD::SETNE:   return X86::COND_NE;
2302   case ISD::SETUO:   return X86::COND_P;
2303   case ISD::SETO:    return X86::COND_NP;
2304   }
2305 }
2306
2307 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2308 /// code. Current x86 isa includes the following FP cmov instructions:
2309 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2310 static bool hasFPCMov(unsigned X86CC) {
2311   switch (X86CC) {
2312   default:
2313     return false;
2314   case X86::COND_B:
2315   case X86::COND_BE:
2316   case X86::COND_E:
2317   case X86::COND_P:
2318   case X86::COND_A:
2319   case X86::COND_AE:
2320   case X86::COND_NE:
2321   case X86::COND_NP:
2322     return true;
2323   }
2324 }
2325
2326 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2327 /// the specified range (L, H].
2328 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2329   return (Val < 0) || (Val >= Low && Val < Hi);
2330 }
2331
2332 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2333 /// specified value.
2334 static bool isUndefOrEqual(int Val, int CmpVal) {
2335   if (Val < 0 || Val == CmpVal)
2336     return true;
2337   return false;
2338 }
2339
2340 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2341 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2342 /// the second operand.
2343 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2344   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2345     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2346   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2347     return (Mask[0] < 2 && Mask[1] < 2);
2348   return false;
2349 }
2350
2351 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2352   SmallVector<int, 8> M;
2353   N->getMask(M);
2354   return ::isPSHUFDMask(M, N->getValueType(0));
2355 }
2356
2357 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2358 /// is suitable for input to PSHUFHW.
2359 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2360   if (VT != MVT::v8i16)
2361     return false;
2362
2363   // Lower quadword copied in order or undef.
2364   for (int i = 0; i != 4; ++i)
2365     if (Mask[i] >= 0 && Mask[i] != i)
2366       return false;
2367
2368   // Upper quadword shuffled.
2369   for (int i = 4; i != 8; ++i)
2370     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2371       return false;
2372
2373   return true;
2374 }
2375
2376 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2377   SmallVector<int, 8> M;
2378   N->getMask(M);
2379   return ::isPSHUFHWMask(M, N->getValueType(0));
2380 }
2381
2382 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2383 /// is suitable for input to PSHUFLW.
2384 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2385   if (VT != MVT::v8i16)
2386     return false;
2387
2388   // Upper quadword copied in order.
2389   for (int i = 4; i != 8; ++i)
2390     if (Mask[i] >= 0 && Mask[i] != i)
2391       return false;
2392
2393   // Lower quadword shuffled.
2394   for (int i = 0; i != 4; ++i)
2395     if (Mask[i] >= 4)
2396       return false;
2397
2398   return true;
2399 }
2400
2401 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2402   SmallVector<int, 8> M;
2403   N->getMask(M);
2404   return ::isPSHUFLWMask(M, N->getValueType(0));
2405 }
2406
2407 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2408 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2409 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2410   int NumElems = VT.getVectorNumElements();
2411   if (NumElems != 2 && NumElems != 4)
2412     return false;
2413
2414   int Half = NumElems / 2;
2415   for (int i = 0; i < Half; ++i)
2416     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2417       return false;
2418   for (int i = Half; i < NumElems; ++i)
2419     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2420       return false;
2421
2422   return true;
2423 }
2424
2425 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2426   SmallVector<int, 8> M;
2427   N->getMask(M);
2428   return ::isSHUFPMask(M, N->getValueType(0));
2429 }
2430
2431 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2432 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2433 /// half elements to come from vector 1 (which would equal the dest.) and
2434 /// the upper half to come from vector 2.
2435 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2436   int NumElems = VT.getVectorNumElements();
2437
2438   if (NumElems != 2 && NumElems != 4)
2439     return false;
2440
2441   int Half = NumElems / 2;
2442   for (int i = 0; i < Half; ++i)
2443     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2444       return false;
2445   for (int i = Half; i < NumElems; ++i)
2446     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2447       return false;
2448   return true;
2449 }
2450
2451 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2452   SmallVector<int, 8> M;
2453   N->getMask(M);
2454   return isCommutedSHUFPMask(M, N->getValueType(0));
2455 }
2456
2457 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2458 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2459 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2460   if (N->getValueType(0).getVectorNumElements() != 4)
2461     return false;
2462
2463   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2464   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2465          isUndefOrEqual(N->getMaskElt(1), 7) &&
2466          isUndefOrEqual(N->getMaskElt(2), 2) &&
2467          isUndefOrEqual(N->getMaskElt(3), 3);
2468 }
2469
2470 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2471 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2472 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2473   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2474
2475   if (NumElems != 2 && NumElems != 4)
2476     return false;
2477
2478   for (unsigned i = 0; i < NumElems/2; ++i)
2479     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2480       return false;
2481
2482   for (unsigned i = NumElems/2; i < NumElems; ++i)
2483     if (!isUndefOrEqual(N->getMaskElt(i), i))
2484       return false;
2485
2486   return true;
2487 }
2488
2489 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2490 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2491 /// and MOVLHPS.
2492 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2493   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2494
2495   if (NumElems != 2 && NumElems != 4)
2496     return false;
2497
2498   for (unsigned i = 0; i < NumElems/2; ++i)
2499     if (!isUndefOrEqual(N->getMaskElt(i), i))
2500       return false;
2501
2502   for (unsigned i = 0; i < NumElems/2; ++i)
2503     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2504       return false;
2505
2506   return true;
2507 }
2508
2509 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2510 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2511 /// <2, 3, 2, 3>
2512 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2513   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2514
2515   if (NumElems != 4)
2516     return false;
2517
2518   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2519          isUndefOrEqual(N->getMaskElt(1), 3) &&
2520          isUndefOrEqual(N->getMaskElt(2), 2) &&
2521          isUndefOrEqual(N->getMaskElt(3), 3);
2522 }
2523
2524 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2525 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2526 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2527                          bool V2IsSplat = false) {
2528   int NumElts = VT.getVectorNumElements();
2529   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2530     return false;
2531
2532   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2533     int BitI  = Mask[i];
2534     int BitI1 = Mask[i+1];
2535     if (!isUndefOrEqual(BitI, j))
2536       return false;
2537     if (V2IsSplat) {
2538       if (!isUndefOrEqual(BitI1, NumElts))
2539         return false;
2540     } else {
2541       if (!isUndefOrEqual(BitI1, j + NumElts))
2542         return false;
2543     }
2544   }
2545   return true;
2546 }
2547
2548 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2549   SmallVector<int, 8> M;
2550   N->getMask(M);
2551   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2552 }
2553
2554 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2555 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2556 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2557                          bool V2IsSplat = false) {
2558   int NumElts = VT.getVectorNumElements();
2559   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2560     return false;
2561
2562   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2563     int BitI  = Mask[i];
2564     int BitI1 = Mask[i+1];
2565     if (!isUndefOrEqual(BitI, j + NumElts/2))
2566       return false;
2567     if (V2IsSplat) {
2568       if (isUndefOrEqual(BitI1, NumElts))
2569         return false;
2570     } else {
2571       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2572         return false;
2573     }
2574   }
2575   return true;
2576 }
2577
2578 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2579   SmallVector<int, 8> M;
2580   N->getMask(M);
2581   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2582 }
2583
2584 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2585 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2586 /// <0, 0, 1, 1>
2587 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2588   int NumElems = VT.getVectorNumElements();
2589   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2590     return false;
2591
2592   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2593     int BitI  = Mask[i];
2594     int BitI1 = Mask[i+1];
2595     if (!isUndefOrEqual(BitI, j))
2596       return false;
2597     if (!isUndefOrEqual(BitI1, j))
2598       return false;
2599   }
2600   return true;
2601 }
2602
2603 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2604   SmallVector<int, 8> M;
2605   N->getMask(M);
2606   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2607 }
2608
2609 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2610 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2611 /// <2, 2, 3, 3>
2612 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2613   int NumElems = VT.getVectorNumElements();
2614   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2615     return false;
2616
2617   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2618     int BitI  = Mask[i];
2619     int BitI1 = Mask[i+1];
2620     if (!isUndefOrEqual(BitI, j))
2621       return false;
2622     if (!isUndefOrEqual(BitI1, j))
2623       return false;
2624   }
2625   return true;
2626 }
2627
2628 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2629   SmallVector<int, 8> M;
2630   N->getMask(M);
2631   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2632 }
2633
2634 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2635 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2636 /// MOVSD, and MOVD, i.e. setting the lowest element.
2637 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2638   if (VT.getVectorElementType().getSizeInBits() < 32)
2639     return false;
2640
2641   int NumElts = VT.getVectorNumElements();
2642
2643   if (!isUndefOrEqual(Mask[0], NumElts))
2644     return false;
2645
2646   for (int i = 1; i < NumElts; ++i)
2647     if (!isUndefOrEqual(Mask[i], i))
2648       return false;
2649
2650   return true;
2651 }
2652
2653 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2654   SmallVector<int, 8> M;
2655   N->getMask(M);
2656   return ::isMOVLMask(M, N->getValueType(0));
2657 }
2658
2659 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2660 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2661 /// element of vector 2 and the other elements to come from vector 1 in order.
2662 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2663                                bool V2IsSplat = false, bool V2IsUndef = false) {
2664   int NumOps = VT.getVectorNumElements();
2665   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2666     return false;
2667
2668   if (!isUndefOrEqual(Mask[0], 0))
2669     return false;
2670
2671   for (int i = 1; i < NumOps; ++i)
2672     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2673           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2674           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2675       return false;
2676
2677   return true;
2678 }
2679
2680 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2681                            bool V2IsUndef = false) {
2682   SmallVector<int, 8> M;
2683   N->getMask(M);
2684   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2685 }
2686
2687 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2688 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2689 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2690   if (N->getValueType(0).getVectorNumElements() != 4)
2691     return false;
2692
2693   // Expect 1, 1, 3, 3
2694   for (unsigned i = 0; i < 2; ++i) {
2695     int Elt = N->getMaskElt(i);
2696     if (Elt >= 0 && Elt != 1)
2697       return false;
2698   }
2699
2700   bool HasHi = false;
2701   for (unsigned i = 2; i < 4; ++i) {
2702     int Elt = N->getMaskElt(i);
2703     if (Elt >= 0 && Elt != 3)
2704       return false;
2705     if (Elt == 3)
2706       HasHi = true;
2707   }
2708   // Don't use movshdup if it can be done with a shufps.
2709   // FIXME: verify that matching u, u, 3, 3 is what we want.
2710   return HasHi;
2711 }
2712
2713 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2714 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2715 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2716   if (N->getValueType(0).getVectorNumElements() != 4)
2717     return false;
2718
2719   // Expect 0, 0, 2, 2
2720   for (unsigned i = 0; i < 2; ++i)
2721     if (N->getMaskElt(i) > 0)
2722       return false;
2723
2724   bool HasHi = false;
2725   for (unsigned i = 2; i < 4; ++i) {
2726     int Elt = N->getMaskElt(i);
2727     if (Elt >= 0 && Elt != 2)
2728       return false;
2729     if (Elt == 2)
2730       HasHi = true;
2731   }
2732   // Don't use movsldup if it can be done with a shufps.
2733   return HasHi;
2734 }
2735
2736 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2737 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2738 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2739   int e = N->getValueType(0).getVectorNumElements() / 2;
2740
2741   for (int i = 0; i < e; ++i)
2742     if (!isUndefOrEqual(N->getMaskElt(i), i))
2743       return false;
2744   for (int i = 0; i < e; ++i)
2745     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2746       return false;
2747   return true;
2748 }
2749
2750 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2751 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2752 /// instructions.
2753 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2755   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2756
2757   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2758   unsigned Mask = 0;
2759   for (int i = 0; i < NumOperands; ++i) {
2760     int Val = SVOp->getMaskElt(NumOperands-i-1);
2761     if (Val < 0) Val = 0;
2762     if (Val >= NumOperands) Val -= NumOperands;
2763     Mask |= Val;
2764     if (i != NumOperands - 1)
2765       Mask <<= Shift;
2766   }
2767   return Mask;
2768 }
2769
2770 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2771 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2772 /// instructions.
2773 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2775   unsigned Mask = 0;
2776   // 8 nodes, but we only care about the last 4.
2777   for (unsigned i = 7; i >= 4; --i) {
2778     int Val = SVOp->getMaskElt(i);
2779     if (Val >= 0)
2780       Mask |= (Val - 4);
2781     if (i != 4)
2782       Mask <<= 2;
2783   }
2784   return Mask;
2785 }
2786
2787 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2788 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2789 /// instructions.
2790 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2791   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2792   unsigned Mask = 0;
2793   // 8 nodes, but we only care about the first 4.
2794   for (int i = 3; i >= 0; --i) {
2795     int Val = SVOp->getMaskElt(i);
2796     if (Val >= 0)
2797       Mask |= Val;
2798     if (i != 0)
2799       Mask <<= 2;
2800   }
2801   return Mask;
2802 }
2803
2804 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2805 /// constant +0.0.
2806 bool X86::isZeroNode(SDValue Elt) {
2807   return ((isa<ConstantSDNode>(Elt) &&
2808            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2809           (isa<ConstantFPSDNode>(Elt) &&
2810            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2811 }
2812
2813 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2814 /// their permute mask.
2815 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2816                                     SelectionDAG &DAG) {
2817   EVT VT = SVOp->getValueType(0);
2818   unsigned NumElems = VT.getVectorNumElements();
2819   SmallVector<int, 8> MaskVec;
2820
2821   for (unsigned i = 0; i != NumElems; ++i) {
2822     int idx = SVOp->getMaskElt(i);
2823     if (idx < 0)
2824       MaskVec.push_back(idx);
2825     else if (idx < (int)NumElems)
2826       MaskVec.push_back(idx + NumElems);
2827     else
2828       MaskVec.push_back(idx - NumElems);
2829   }
2830   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2831                               SVOp->getOperand(0), &MaskVec[0]);
2832 }
2833
2834 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2835 /// the two vector operands have swapped position.
2836 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2837   unsigned NumElems = VT.getVectorNumElements();
2838   for (unsigned i = 0; i != NumElems; ++i) {
2839     int idx = Mask[i];
2840     if (idx < 0)
2841       continue;
2842     else if (idx < (int)NumElems)
2843       Mask[i] = idx + NumElems;
2844     else
2845       Mask[i] = idx - NumElems;
2846   }
2847 }
2848
2849 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2850 /// match movhlps. The lower half elements should come from upper half of
2851 /// V1 (and in order), and the upper half elements should come from the upper
2852 /// half of V2 (and in order).
2853 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2854   if (Op->getValueType(0).getVectorNumElements() != 4)
2855     return false;
2856   for (unsigned i = 0, e = 2; i != e; ++i)
2857     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2858       return false;
2859   for (unsigned i = 2; i != 4; ++i)
2860     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2861       return false;
2862   return true;
2863 }
2864
2865 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2866 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2867 /// required.
2868 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2869   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2870     return false;
2871   N = N->getOperand(0).getNode();
2872   if (!ISD::isNON_EXTLoad(N))
2873     return false;
2874   if (LD)
2875     *LD = cast<LoadSDNode>(N);
2876   return true;
2877 }
2878
2879 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2880 /// match movlp{s|d}. The lower half elements should come from lower half of
2881 /// V1 (and in order), and the upper half elements should come from the upper
2882 /// half of V2 (and in order). And since V1 will become the source of the
2883 /// MOVLP, it must be either a vector load or a scalar load to vector.
2884 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2885                                ShuffleVectorSDNode *Op) {
2886   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2887     return false;
2888   // Is V2 is a vector load, don't do this transformation. We will try to use
2889   // load folding shufps op.
2890   if (ISD::isNON_EXTLoad(V2))
2891     return false;
2892
2893   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2894
2895   if (NumElems != 2 && NumElems != 4)
2896     return false;
2897   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2898     if (!isUndefOrEqual(Op->getMaskElt(i), i))
2899       return false;
2900   for (unsigned i = NumElems/2; i != NumElems; ++i)
2901     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2902       return false;
2903   return true;
2904 }
2905
2906 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2907 /// all the same.
2908 static bool isSplatVector(SDNode *N) {
2909   if (N->getOpcode() != ISD::BUILD_VECTOR)
2910     return false;
2911
2912   SDValue SplatValue = N->getOperand(0);
2913   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2914     if (N->getOperand(i) != SplatValue)
2915       return false;
2916   return true;
2917 }
2918
2919 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2920 /// to an zero vector.
2921 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2922 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2923   SDValue V1 = N->getOperand(0);
2924   SDValue V2 = N->getOperand(1);
2925   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2926   for (unsigned i = 0; i != NumElems; ++i) {
2927     int Idx = N->getMaskElt(i);
2928     if (Idx >= (int)NumElems) {
2929       unsigned Opc = V2.getOpcode();
2930       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2931         continue;
2932       if (Opc != ISD::BUILD_VECTOR ||
2933           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
2934         return false;
2935     } else if (Idx >= 0) {
2936       unsigned Opc = V1.getOpcode();
2937       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2938         continue;
2939       if (Opc != ISD::BUILD_VECTOR ||
2940           !X86::isZeroNode(V1.getOperand(Idx)))
2941         return false;
2942     }
2943   }
2944   return true;
2945 }
2946
2947 /// getZeroVector - Returns a vector of specified type with all zero elements.
2948 ///
2949 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
2950                              DebugLoc dl) {
2951   assert(VT.isVector() && "Expected a vector type");
2952
2953   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2954   // type.  This ensures they get CSE'd.
2955   SDValue Vec;
2956   if (VT.getSizeInBits() == 64) { // MMX
2957     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2958     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2959   } else if (HasSSE2) {  // SSE2
2960     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2961     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2962   } else { // SSE1
2963     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2964     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2965   }
2966   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2967 }
2968
2969 /// getOnesVector - Returns a vector of specified type with all bits set.
2970 ///
2971 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2972   assert(VT.isVector() && "Expected a vector type");
2973
2974   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2975   // type.  This ensures they get CSE'd.
2976   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2977   SDValue Vec;
2978   if (VT.getSizeInBits() == 64)  // MMX
2979     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2980   else                                              // SSE
2981     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2982   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2983 }
2984
2985
2986 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2987 /// that point to V2 points to its first element.
2988 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2989   EVT VT = SVOp->getValueType(0);
2990   unsigned NumElems = VT.getVectorNumElements();
2991
2992   bool Changed = false;
2993   SmallVector<int, 8> MaskVec;
2994   SVOp->getMask(MaskVec);
2995
2996   for (unsigned i = 0; i != NumElems; ++i) {
2997     if (MaskVec[i] > (int)NumElems) {
2998       MaskVec[i] = NumElems;
2999       Changed = true;
3000     }
3001   }
3002   if (Changed)
3003     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3004                                 SVOp->getOperand(1), &MaskVec[0]);
3005   return SDValue(SVOp, 0);
3006 }
3007
3008 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3009 /// operation of specified width.
3010 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3011                        SDValue V2) {
3012   unsigned NumElems = VT.getVectorNumElements();
3013   SmallVector<int, 8> Mask;
3014   Mask.push_back(NumElems);
3015   for (unsigned i = 1; i != NumElems; ++i)
3016     Mask.push_back(i);
3017   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3018 }
3019
3020 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3021 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3022                           SDValue V2) {
3023   unsigned NumElems = VT.getVectorNumElements();
3024   SmallVector<int, 8> Mask;
3025   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3026     Mask.push_back(i);
3027     Mask.push_back(i + NumElems);
3028   }
3029   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3030 }
3031
3032 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3033 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3034                           SDValue V2) {
3035   unsigned NumElems = VT.getVectorNumElements();
3036   unsigned Half = NumElems/2;
3037   SmallVector<int, 8> Mask;
3038   for (unsigned i = 0; i != Half; ++i) {
3039     Mask.push_back(i + Half);
3040     Mask.push_back(i + NumElems + Half);
3041   }
3042   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3043 }
3044
3045 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3046 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3047                             bool HasSSE2) {
3048   if (SV->getValueType(0).getVectorNumElements() <= 4)
3049     return SDValue(SV, 0);
3050
3051   EVT PVT = MVT::v4f32;
3052   EVT VT = SV->getValueType(0);
3053   DebugLoc dl = SV->getDebugLoc();
3054   SDValue V1 = SV->getOperand(0);
3055   int NumElems = VT.getVectorNumElements();
3056   int EltNo = SV->getSplatIndex();
3057
3058   // unpack elements to the correct location
3059   while (NumElems > 4) {
3060     if (EltNo < NumElems/2) {
3061       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3062     } else {
3063       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3064       EltNo -= NumElems/2;
3065     }
3066     NumElems >>= 1;
3067   }
3068
3069   // Perform the splat.
3070   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3071   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3072   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3073   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3074 }
3075
3076 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3077 /// vector of zero or undef vector.  This produces a shuffle where the low
3078 /// element of V2 is swizzled into the zero/undef vector, landing at element
3079 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3080 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3081                                              bool isZero, bool HasSSE2,
3082                                              SelectionDAG &DAG) {
3083   EVT VT = V2.getValueType();
3084   SDValue V1 = isZero
3085     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3086   unsigned NumElems = VT.getVectorNumElements();
3087   SmallVector<int, 16> MaskVec;
3088   for (unsigned i = 0; i != NumElems; ++i)
3089     // If this is the insertion idx, put the low elt of V2 here.
3090     MaskVec.push_back(i == Idx ? NumElems : i);
3091   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3092 }
3093
3094 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3095 /// a shuffle that is zero.
3096 static
3097 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3098                                   bool Low, SelectionDAG &DAG) {
3099   unsigned NumZeros = 0;
3100   for (int i = 0; i < NumElems; ++i) {
3101     unsigned Index = Low ? i : NumElems-i-1;
3102     int Idx = SVOp->getMaskElt(Index);
3103     if (Idx < 0) {
3104       ++NumZeros;
3105       continue;
3106     }
3107     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3108     if (Elt.getNode() && X86::isZeroNode(Elt))
3109       ++NumZeros;
3110     else
3111       break;
3112   }
3113   return NumZeros;
3114 }
3115
3116 /// isVectorShift - Returns true if the shuffle can be implemented as a
3117 /// logical left or right shift of a vector.
3118 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3119 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3120                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3121   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3122
3123   isLeft = true;
3124   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3125   if (!NumZeros) {
3126     isLeft = false;
3127     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3128     if (!NumZeros)
3129       return false;
3130   }
3131   bool SeenV1 = false;
3132   bool SeenV2 = false;
3133   for (int i = NumZeros; i < NumElems; ++i) {
3134     int Val = isLeft ? (i - NumZeros) : i;
3135     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3136     if (Idx < 0)
3137       continue;
3138     if (Idx < NumElems)
3139       SeenV1 = true;
3140     else {
3141       Idx -= NumElems;
3142       SeenV2 = true;
3143     }
3144     if (Idx != Val)
3145       return false;
3146   }
3147   if (SeenV1 && SeenV2)
3148     return false;
3149
3150   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3151   ShAmt = NumZeros;
3152   return true;
3153 }
3154
3155
3156 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3157 ///
3158 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3159                                        unsigned NumNonZero, unsigned NumZero,
3160                                        SelectionDAG &DAG, TargetLowering &TLI) {
3161   if (NumNonZero > 8)
3162     return SDValue();
3163
3164   DebugLoc dl = Op.getDebugLoc();
3165   SDValue V(0, 0);
3166   bool First = true;
3167   for (unsigned i = 0; i < 16; ++i) {
3168     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3169     if (ThisIsNonZero && First) {
3170       if (NumZero)
3171         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3172       else
3173         V = DAG.getUNDEF(MVT::v8i16);
3174       First = false;
3175     }
3176
3177     if ((i & 1) != 0) {
3178       SDValue ThisElt(0, 0), LastElt(0, 0);
3179       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3180       if (LastIsNonZero) {
3181         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3182                               MVT::i16, Op.getOperand(i-1));
3183       }
3184       if (ThisIsNonZero) {
3185         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3186         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3187                               ThisElt, DAG.getConstant(8, MVT::i8));
3188         if (LastIsNonZero)
3189           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3190       } else
3191         ThisElt = LastElt;
3192
3193       if (ThisElt.getNode())
3194         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3195                         DAG.getIntPtrConstant(i/2));
3196     }
3197   }
3198
3199   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3200 }
3201
3202 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3203 ///
3204 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3205                                        unsigned NumNonZero, unsigned NumZero,
3206                                        SelectionDAG &DAG, TargetLowering &TLI) {
3207   if (NumNonZero > 4)
3208     return SDValue();
3209
3210   DebugLoc dl = Op.getDebugLoc();
3211   SDValue V(0, 0);
3212   bool First = true;
3213   for (unsigned i = 0; i < 8; ++i) {
3214     bool isNonZero = (NonZeros & (1 << i)) != 0;
3215     if (isNonZero) {
3216       if (First) {
3217         if (NumZero)
3218           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3219         else
3220           V = DAG.getUNDEF(MVT::v8i16);
3221         First = false;
3222       }
3223       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3224                       MVT::v8i16, V, Op.getOperand(i),
3225                       DAG.getIntPtrConstant(i));
3226     }
3227   }
3228
3229   return V;
3230 }
3231
3232 /// getVShift - Return a vector logical shift node.
3233 ///
3234 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3235                          unsigned NumBits, SelectionDAG &DAG,
3236                          const TargetLowering &TLI, DebugLoc dl) {
3237   bool isMMX = VT.getSizeInBits() == 64;
3238   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3239   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3240   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3241   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3242                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3243                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3244 }
3245
3246 SDValue
3247 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3248   DebugLoc dl = Op.getDebugLoc();
3249   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3250   if (ISD::isBuildVectorAllZeros(Op.getNode())
3251       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3252     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3253     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3254     // eliminated on x86-32 hosts.
3255     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3256       return Op;
3257
3258     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3259       return getOnesVector(Op.getValueType(), DAG, dl);
3260     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3261   }
3262
3263   EVT VT = Op.getValueType();
3264   EVT ExtVT = VT.getVectorElementType();
3265   unsigned EVTBits = ExtVT.getSizeInBits();
3266
3267   unsigned NumElems = Op.getNumOperands();
3268   unsigned NumZero  = 0;
3269   unsigned NumNonZero = 0;
3270   unsigned NonZeros = 0;
3271   bool IsAllConstants = true;
3272   SmallSet<SDValue, 8> Values;
3273   for (unsigned i = 0; i < NumElems; ++i) {
3274     SDValue Elt = Op.getOperand(i);
3275     if (Elt.getOpcode() == ISD::UNDEF)
3276       continue;
3277     Values.insert(Elt);
3278     if (Elt.getOpcode() != ISD::Constant &&
3279         Elt.getOpcode() != ISD::ConstantFP)
3280       IsAllConstants = false;
3281     if (X86::isZeroNode(Elt))
3282       NumZero++;
3283     else {
3284       NonZeros |= (1 << i);
3285       NumNonZero++;
3286     }
3287   }
3288
3289   if (NumNonZero == 0) {
3290     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3291     return DAG.getUNDEF(VT);
3292   }
3293
3294   // Special case for single non-zero, non-undef, element.
3295   if (NumNonZero == 1) {
3296     unsigned Idx = CountTrailingZeros_32(NonZeros);
3297     SDValue Item = Op.getOperand(Idx);
3298
3299     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3300     // the value are obviously zero, truncate the value to i32 and do the
3301     // insertion that way.  Only do this if the value is non-constant or if the
3302     // value is a constant being inserted into element 0.  It is cheaper to do
3303     // a constant pool load than it is to do a movd + shuffle.
3304     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3305         (!IsAllConstants || Idx == 0)) {
3306       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3307         // Handle MMX and SSE both.
3308         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3309         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3310
3311         // Truncate the value (which may itself be a constant) to i32, and
3312         // convert it to a vector with movd (S2V+shuffle to zero extend).
3313         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3314         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3315         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3316                                            Subtarget->hasSSE2(), DAG);
3317
3318         // Now we have our 32-bit value zero extended in the low element of
3319         // a vector.  If Idx != 0, swizzle it into place.
3320         if (Idx != 0) {
3321           SmallVector<int, 4> Mask;
3322           Mask.push_back(Idx);
3323           for (unsigned i = 1; i != VecElts; ++i)
3324             Mask.push_back(i);
3325           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3326                                       DAG.getUNDEF(Item.getValueType()),
3327                                       &Mask[0]);
3328         }
3329         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3330       }
3331     }
3332
3333     // If we have a constant or non-constant insertion into the low element of
3334     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3335     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3336     // depending on what the source datatype is.
3337     if (Idx == 0) {
3338       if (NumZero == 0) {
3339         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3340       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3341           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3342         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3343         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3344         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3345                                            DAG);
3346       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3347         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3348         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3349         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3350         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3351                                            Subtarget->hasSSE2(), DAG);
3352         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3353       }
3354     }
3355
3356     // Is it a vector logical left shift?
3357     if (NumElems == 2 && Idx == 1 &&
3358         X86::isZeroNode(Op.getOperand(0)) &&
3359         !X86::isZeroNode(Op.getOperand(1))) {
3360       unsigned NumBits = VT.getSizeInBits();
3361       return getVShift(true, VT,
3362                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3363                                    VT, Op.getOperand(1)),
3364                        NumBits/2, DAG, *this, dl);
3365     }
3366
3367     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3368       return SDValue();
3369
3370     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3371     // is a non-constant being inserted into an element other than the low one,
3372     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3373     // movd/movss) to move this into the low element, then shuffle it into
3374     // place.
3375     if (EVTBits == 32) {
3376       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3377
3378       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3379       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3380                                          Subtarget->hasSSE2(), DAG);
3381       SmallVector<int, 8> MaskVec;
3382       for (unsigned i = 0; i < NumElems; i++)
3383         MaskVec.push_back(i == Idx ? 0 : 1);
3384       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3385     }
3386   }
3387
3388   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3389   if (Values.size() == 1)
3390     return SDValue();
3391
3392   // A vector full of immediates; various special cases are already
3393   // handled, so this is best done with a single constant-pool load.
3394   if (IsAllConstants)
3395     return SDValue();
3396
3397   // Let legalizer expand 2-wide build_vectors.
3398   if (EVTBits == 64) {
3399     if (NumNonZero == 1) {
3400       // One half is zero or undef.
3401       unsigned Idx = CountTrailingZeros_32(NonZeros);
3402       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3403                                  Op.getOperand(Idx));
3404       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3405                                          Subtarget->hasSSE2(), DAG);
3406     }
3407     return SDValue();
3408   }
3409
3410   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3411   if (EVTBits == 8 && NumElems == 16) {
3412     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3413                                         *this);
3414     if (V.getNode()) return V;
3415   }
3416
3417   if (EVTBits == 16 && NumElems == 8) {
3418     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3419                                         *this);
3420     if (V.getNode()) return V;
3421   }
3422
3423   // If element VT is == 32 bits, turn it into a number of shuffles.
3424   SmallVector<SDValue, 8> V;
3425   V.resize(NumElems);
3426   if (NumElems == 4 && NumZero > 0) {
3427     for (unsigned i = 0; i < 4; ++i) {
3428       bool isZero = !(NonZeros & (1 << i));
3429       if (isZero)
3430         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3431       else
3432         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3433     }
3434
3435     for (unsigned i = 0; i < 2; ++i) {
3436       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3437         default: break;
3438         case 0:
3439           V[i] = V[i*2];  // Must be a zero vector.
3440           break;
3441         case 1:
3442           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3443           break;
3444         case 2:
3445           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3446           break;
3447         case 3:
3448           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3449           break;
3450       }
3451     }
3452
3453     SmallVector<int, 8> MaskVec;
3454     bool Reverse = (NonZeros & 0x3) == 2;
3455     for (unsigned i = 0; i < 2; ++i)
3456       MaskVec.push_back(Reverse ? 1-i : i);
3457     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3458     for (unsigned i = 0; i < 2; ++i)
3459       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3460     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3461   }
3462
3463   if (Values.size() > 2) {
3464     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3465     // values to be inserted is equal to the number of elements, in which case
3466     // use the unpack code below in the hopes of matching the consecutive elts
3467     // load merge pattern for shuffles.
3468     // FIXME: We could probably just check that here directly.
3469     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3470         getSubtarget()->hasSSE41()) {
3471       V[0] = DAG.getUNDEF(VT);
3472       for (unsigned i = 0; i < NumElems; ++i)
3473         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3474           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3475                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3476       return V[0];
3477     }
3478     // Expand into a number of unpckl*.
3479     // e.g. for v4f32
3480     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3481     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3482     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3483     for (unsigned i = 0; i < NumElems; ++i)
3484       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3485     NumElems >>= 1;
3486     while (NumElems != 0) {
3487       for (unsigned i = 0; i < NumElems; ++i)
3488         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3489       NumElems >>= 1;
3490     }
3491     return V[0];
3492   }
3493
3494   return SDValue();
3495 }
3496
3497 // v8i16 shuffles - Prefer shuffles in the following order:
3498 // 1. [all]   pshuflw, pshufhw, optional move
3499 // 2. [ssse3] 1 x pshufb
3500 // 3. [ssse3] 2 x pshufb + 1 x por
3501 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3502 static
3503 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3504                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3505   SDValue V1 = SVOp->getOperand(0);
3506   SDValue V2 = SVOp->getOperand(1);
3507   DebugLoc dl = SVOp->getDebugLoc();
3508   SmallVector<int, 8> MaskVals;
3509
3510   // Determine if more than 1 of the words in each of the low and high quadwords
3511   // of the result come from the same quadword of one of the two inputs.  Undef
3512   // mask values count as coming from any quadword, for better codegen.
3513   SmallVector<unsigned, 4> LoQuad(4);
3514   SmallVector<unsigned, 4> HiQuad(4);
3515   BitVector InputQuads(4);
3516   for (unsigned i = 0; i < 8; ++i) {
3517     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3518     int EltIdx = SVOp->getMaskElt(i);
3519     MaskVals.push_back(EltIdx);
3520     if (EltIdx < 0) {
3521       ++Quad[0];
3522       ++Quad[1];
3523       ++Quad[2];
3524       ++Quad[3];
3525       continue;
3526     }
3527     ++Quad[EltIdx / 4];
3528     InputQuads.set(EltIdx / 4);
3529   }
3530
3531   int BestLoQuad = -1;
3532   unsigned MaxQuad = 1;
3533   for (unsigned i = 0; i < 4; ++i) {
3534     if (LoQuad[i] > MaxQuad) {
3535       BestLoQuad = i;
3536       MaxQuad = LoQuad[i];
3537     }
3538   }
3539
3540   int BestHiQuad = -1;
3541   MaxQuad = 1;
3542   for (unsigned i = 0; i < 4; ++i) {
3543     if (HiQuad[i] > MaxQuad) {
3544       BestHiQuad = i;
3545       MaxQuad = HiQuad[i];
3546     }
3547   }
3548
3549   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3550   // of the two input vectors, shuffle them into one input vector so only a
3551   // single pshufb instruction is necessary. If There are more than 2 input
3552   // quads, disable the next transformation since it does not help SSSE3.
3553   bool V1Used = InputQuads[0] || InputQuads[1];
3554   bool V2Used = InputQuads[2] || InputQuads[3];
3555   if (TLI.getSubtarget()->hasSSSE3()) {
3556     if (InputQuads.count() == 2 && V1Used && V2Used) {
3557       BestLoQuad = InputQuads.find_first();
3558       BestHiQuad = InputQuads.find_next(BestLoQuad);
3559     }
3560     if (InputQuads.count() > 2) {
3561       BestLoQuad = -1;
3562       BestHiQuad = -1;
3563     }
3564   }
3565
3566   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3567   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3568   // words from all 4 input quadwords.
3569   SDValue NewV;
3570   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3571     SmallVector<int, 8> MaskV;
3572     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3573     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3574     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3575                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3576                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3577     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3578
3579     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3580     // source words for the shuffle, to aid later transformations.
3581     bool AllWordsInNewV = true;
3582     bool InOrder[2] = { true, true };
3583     for (unsigned i = 0; i != 8; ++i) {
3584       int idx = MaskVals[i];
3585       if (idx != (int)i)
3586         InOrder[i/4] = false;
3587       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3588         continue;
3589       AllWordsInNewV = false;
3590       break;
3591     }
3592
3593     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3594     if (AllWordsInNewV) {
3595       for (int i = 0; i != 8; ++i) {
3596         int idx = MaskVals[i];
3597         if (idx < 0)
3598           continue;
3599         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3600         if ((idx != i) && idx < 4)
3601           pshufhw = false;
3602         if ((idx != i) && idx > 3)
3603           pshuflw = false;
3604       }
3605       V1 = NewV;
3606       V2Used = false;
3607       BestLoQuad = 0;
3608       BestHiQuad = 1;
3609     }
3610
3611     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3612     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3613     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3614       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3615                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3616     }
3617   }
3618
3619   // If we have SSSE3, and all words of the result are from 1 input vector,
3620   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3621   // is present, fall back to case 4.
3622   if (TLI.getSubtarget()->hasSSSE3()) {
3623     SmallVector<SDValue,16> pshufbMask;
3624
3625     // If we have elements from both input vectors, set the high bit of the
3626     // shuffle mask element to zero out elements that come from V2 in the V1
3627     // mask, and elements that come from V1 in the V2 mask, so that the two
3628     // results can be OR'd together.
3629     bool TwoInputs = V1Used && V2Used;
3630     for (unsigned i = 0; i != 8; ++i) {
3631       int EltIdx = MaskVals[i] * 2;
3632       if (TwoInputs && (EltIdx >= 16)) {
3633         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3634         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3635         continue;
3636       }
3637       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3638       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3639     }
3640     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3641     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3642                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3643                                  MVT::v16i8, &pshufbMask[0], 16));
3644     if (!TwoInputs)
3645       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3646
3647     // Calculate the shuffle mask for the second input, shuffle it, and
3648     // OR it with the first shuffled input.
3649     pshufbMask.clear();
3650     for (unsigned i = 0; i != 8; ++i) {
3651       int EltIdx = MaskVals[i] * 2;
3652       if (EltIdx < 16) {
3653         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3654         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3655         continue;
3656       }
3657       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3658       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3659     }
3660     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3661     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3662                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3663                                  MVT::v16i8, &pshufbMask[0], 16));
3664     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3665     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3666   }
3667
3668   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3669   // and update MaskVals with new element order.
3670   BitVector InOrder(8);
3671   if (BestLoQuad >= 0) {
3672     SmallVector<int, 8> MaskV;
3673     for (int i = 0; i != 4; ++i) {
3674       int idx = MaskVals[i];
3675       if (idx < 0) {
3676         MaskV.push_back(-1);
3677         InOrder.set(i);
3678       } else if ((idx / 4) == BestLoQuad) {
3679         MaskV.push_back(idx & 3);
3680         InOrder.set(i);
3681       } else {
3682         MaskV.push_back(-1);
3683       }
3684     }
3685     for (unsigned i = 4; i != 8; ++i)
3686       MaskV.push_back(i);
3687     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3688                                 &MaskV[0]);
3689   }
3690
3691   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3692   // and update MaskVals with the new element order.
3693   if (BestHiQuad >= 0) {
3694     SmallVector<int, 8> MaskV;
3695     for (unsigned i = 0; i != 4; ++i)
3696       MaskV.push_back(i);
3697     for (unsigned i = 4; i != 8; ++i) {
3698       int idx = MaskVals[i];
3699       if (idx < 0) {
3700         MaskV.push_back(-1);
3701         InOrder.set(i);
3702       } else if ((idx / 4) == BestHiQuad) {
3703         MaskV.push_back((idx & 3) + 4);
3704         InOrder.set(i);
3705       } else {
3706         MaskV.push_back(-1);
3707       }
3708     }
3709     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3710                                 &MaskV[0]);
3711   }
3712
3713   // In case BestHi & BestLo were both -1, which means each quadword has a word
3714   // from each of the four input quadwords, calculate the InOrder bitvector now
3715   // before falling through to the insert/extract cleanup.
3716   if (BestLoQuad == -1 && BestHiQuad == -1) {
3717     NewV = V1;
3718     for (int i = 0; i != 8; ++i)
3719       if (MaskVals[i] < 0 || MaskVals[i] == i)
3720         InOrder.set(i);
3721   }
3722
3723   // The other elements are put in the right place using pextrw and pinsrw.
3724   for (unsigned i = 0; i != 8; ++i) {
3725     if (InOrder[i])
3726       continue;
3727     int EltIdx = MaskVals[i];
3728     if (EltIdx < 0)
3729       continue;
3730     SDValue ExtOp = (EltIdx < 8)
3731     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3732                   DAG.getIntPtrConstant(EltIdx))
3733     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3734                   DAG.getIntPtrConstant(EltIdx - 8));
3735     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3736                        DAG.getIntPtrConstant(i));
3737   }
3738   return NewV;
3739 }
3740
3741 // v16i8 shuffles - Prefer shuffles in the following order:
3742 // 1. [ssse3] 1 x pshufb
3743 // 2. [ssse3] 2 x pshufb + 1 x por
3744 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
3745 static
3746 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3747                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3748   SDValue V1 = SVOp->getOperand(0);
3749   SDValue V2 = SVOp->getOperand(1);
3750   DebugLoc dl = SVOp->getDebugLoc();
3751   SmallVector<int, 16> MaskVals;
3752   SVOp->getMask(MaskVals);
3753
3754   // If we have SSSE3, case 1 is generated when all result bytes come from
3755   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
3756   // present, fall back to case 3.
3757   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3758   bool V1Only = true;
3759   bool V2Only = true;
3760   for (unsigned i = 0; i < 16; ++i) {
3761     int EltIdx = MaskVals[i];
3762     if (EltIdx < 0)
3763       continue;
3764     if (EltIdx < 16)
3765       V2Only = false;
3766     else
3767       V1Only = false;
3768   }
3769
3770   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3771   if (TLI.getSubtarget()->hasSSSE3()) {
3772     SmallVector<SDValue,16> pshufbMask;
3773
3774     // If all result elements are from one input vector, then only translate
3775     // undef mask values to 0x80 (zero out result) in the pshufb mask.
3776     //
3777     // Otherwise, we have elements from both input vectors, and must zero out
3778     // elements that come from V2 in the first mask, and V1 in the second mask
3779     // so that we can OR them together.
3780     bool TwoInputs = !(V1Only || V2Only);
3781     for (unsigned i = 0; i != 16; ++i) {
3782       int EltIdx = MaskVals[i];
3783       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3784         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3785         continue;
3786       }
3787       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3788     }
3789     // If all the elements are from V2, assign it to V1 and return after
3790     // building the first pshufb.
3791     if (V2Only)
3792       V1 = V2;
3793     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3794                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3795                                  MVT::v16i8, &pshufbMask[0], 16));
3796     if (!TwoInputs)
3797       return V1;
3798
3799     // Calculate the shuffle mask for the second input, shuffle it, and
3800     // OR it with the first shuffled input.
3801     pshufbMask.clear();
3802     for (unsigned i = 0; i != 16; ++i) {
3803       int EltIdx = MaskVals[i];
3804       if (EltIdx < 16) {
3805         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3806         continue;
3807       }
3808       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3809     }
3810     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3811                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3812                                  MVT::v16i8, &pshufbMask[0], 16));
3813     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3814   }
3815
3816   // No SSSE3 - Calculate in place words and then fix all out of place words
3817   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
3818   // the 16 different words that comprise the two doublequadword input vectors.
3819   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3820   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3821   SDValue NewV = V2Only ? V2 : V1;
3822   for (int i = 0; i != 8; ++i) {
3823     int Elt0 = MaskVals[i*2];
3824     int Elt1 = MaskVals[i*2+1];
3825
3826     // This word of the result is all undef, skip it.
3827     if (Elt0 < 0 && Elt1 < 0)
3828       continue;
3829
3830     // This word of the result is already in the correct place, skip it.
3831     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3832       continue;
3833     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3834       continue;
3835
3836     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3837     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3838     SDValue InsElt;
3839
3840     // If Elt0 and Elt1 are defined, are consecutive, and can be load
3841     // using a single extract together, load it and store it.
3842     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3843       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3844                            DAG.getIntPtrConstant(Elt1 / 2));
3845       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3846                         DAG.getIntPtrConstant(i));
3847       continue;
3848     }
3849
3850     // If Elt1 is defined, extract it from the appropriate source.  If the
3851     // source byte is not also odd, shift the extracted word left 8 bits
3852     // otherwise clear the bottom 8 bits if we need to do an or.
3853     if (Elt1 >= 0) {
3854       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3855                            DAG.getIntPtrConstant(Elt1 / 2));
3856       if ((Elt1 & 1) == 0)
3857         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3858                              DAG.getConstant(8, TLI.getShiftAmountTy()));
3859       else if (Elt0 >= 0)
3860         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3861                              DAG.getConstant(0xFF00, MVT::i16));
3862     }
3863     // If Elt0 is defined, extract it from the appropriate source.  If the
3864     // source byte is not also even, shift the extracted word right 8 bits. If
3865     // Elt1 was also defined, OR the extracted values together before
3866     // inserting them in the result.
3867     if (Elt0 >= 0) {
3868       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3869                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3870       if ((Elt0 & 1) != 0)
3871         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3872                               DAG.getConstant(8, TLI.getShiftAmountTy()));
3873       else if (Elt1 >= 0)
3874         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3875                              DAG.getConstant(0x00FF, MVT::i16));
3876       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3877                          : InsElt0;
3878     }
3879     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3880                        DAG.getIntPtrConstant(i));
3881   }
3882   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3883 }
3884
3885 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3886 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3887 /// done when every pair / quad of shuffle mask elements point to elements in
3888 /// the right sequence. e.g.
3889 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3890 static
3891 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3892                                  SelectionDAG &DAG,
3893                                  TargetLowering &TLI, DebugLoc dl) {
3894   EVT VT = SVOp->getValueType(0);
3895   SDValue V1 = SVOp->getOperand(0);
3896   SDValue V2 = SVOp->getOperand(1);
3897   unsigned NumElems = VT.getVectorNumElements();
3898   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3899   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3900   EVT MaskEltVT = MaskVT.getVectorElementType();
3901   EVT NewVT = MaskVT;
3902   switch (VT.getSimpleVT().SimpleTy) {
3903   default: assert(false && "Unexpected!");
3904   case MVT::v4f32: NewVT = MVT::v2f64; break;
3905   case MVT::v4i32: NewVT = MVT::v2i64; break;
3906   case MVT::v8i16: NewVT = MVT::v4i32; break;
3907   case MVT::v16i8: NewVT = MVT::v4i32; break;
3908   }
3909
3910   if (NewWidth == 2) {
3911     if (VT.isInteger())
3912       NewVT = MVT::v2i64;
3913     else
3914       NewVT = MVT::v2f64;
3915   }
3916   int Scale = NumElems / NewWidth;
3917   SmallVector<int, 8> MaskVec;
3918   for (unsigned i = 0; i < NumElems; i += Scale) {
3919     int StartIdx = -1;
3920     for (int j = 0; j < Scale; ++j) {
3921       int EltIdx = SVOp->getMaskElt(i+j);
3922       if (EltIdx < 0)
3923         continue;
3924       if (StartIdx == -1)
3925         StartIdx = EltIdx - (EltIdx % Scale);
3926       if (EltIdx != StartIdx + j)
3927         return SDValue();
3928     }
3929     if (StartIdx == -1)
3930       MaskVec.push_back(-1);
3931     else
3932       MaskVec.push_back(StartIdx / Scale);
3933   }
3934
3935   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3936   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3937   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3938 }
3939
3940 /// getVZextMovL - Return a zero-extending vector move low node.
3941 ///
3942 static SDValue getVZextMovL(EVT VT, EVT OpVT,
3943                             SDValue SrcOp, SelectionDAG &DAG,
3944                             const X86Subtarget *Subtarget, DebugLoc dl) {
3945   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3946     LoadSDNode *LD = NULL;
3947     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3948       LD = dyn_cast<LoadSDNode>(SrcOp);
3949     if (!LD) {
3950       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3951       // instead.
3952       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3953       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
3954           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3955           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3956           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
3957         // PR2108
3958         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3959         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3960                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3961                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3962                                                    OpVT,
3963                                                    SrcOp.getOperand(0)
3964                                                           .getOperand(0))));
3965       }
3966     }
3967   }
3968
3969   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3970                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3971                                  DAG.getNode(ISD::BIT_CONVERT, dl,
3972                                              OpVT, SrcOp)));
3973 }
3974
3975 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3976 /// shuffles.
3977 static SDValue
3978 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3979   SDValue V1 = SVOp->getOperand(0);
3980   SDValue V2 = SVOp->getOperand(1);
3981   DebugLoc dl = SVOp->getDebugLoc();
3982   EVT VT = SVOp->getValueType(0);
3983
3984   SmallVector<std::pair<int, int>, 8> Locs;
3985   Locs.resize(4);
3986   SmallVector<int, 8> Mask1(4U, -1);
3987   SmallVector<int, 8> PermMask;
3988   SVOp->getMask(PermMask);
3989
3990   unsigned NumHi = 0;
3991   unsigned NumLo = 0;
3992   for (unsigned i = 0; i != 4; ++i) {
3993     int Idx = PermMask[i];
3994     if (Idx < 0) {
3995       Locs[i] = std::make_pair(-1, -1);
3996     } else {
3997       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3998       if (Idx < 4) {
3999         Locs[i] = std::make_pair(0, NumLo);
4000         Mask1[NumLo] = Idx;
4001         NumLo++;
4002       } else {
4003         Locs[i] = std::make_pair(1, NumHi);
4004         if (2+NumHi < 4)
4005           Mask1[2+NumHi] = Idx;
4006         NumHi++;
4007       }
4008     }
4009   }
4010
4011   if (NumLo <= 2 && NumHi <= 2) {
4012     // If no more than two elements come from either vector. This can be
4013     // implemented with two shuffles. First shuffle gather the elements.
4014     // The second shuffle, which takes the first shuffle as both of its
4015     // vector operands, put the elements into the right order.
4016     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4017
4018     SmallVector<int, 8> Mask2(4U, -1);
4019
4020     for (unsigned i = 0; i != 4; ++i) {
4021       if (Locs[i].first == -1)
4022         continue;
4023       else {
4024         unsigned Idx = (i < 2) ? 0 : 4;
4025         Idx += Locs[i].first * 2 + Locs[i].second;
4026         Mask2[i] = Idx;
4027       }
4028     }
4029
4030     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4031   } else if (NumLo == 3 || NumHi == 3) {
4032     // Otherwise, we must have three elements from one vector, call it X, and
4033     // one element from the other, call it Y.  First, use a shufps to build an
4034     // intermediate vector with the one element from Y and the element from X
4035     // that will be in the same half in the final destination (the indexes don't
4036     // matter). Then, use a shufps to build the final vector, taking the half
4037     // containing the element from Y from the intermediate, and the other half
4038     // from X.
4039     if (NumHi == 3) {
4040       // Normalize it so the 3 elements come from V1.
4041       CommuteVectorShuffleMask(PermMask, VT);
4042       std::swap(V1, V2);
4043     }
4044
4045     // Find the element from V2.
4046     unsigned HiIndex;
4047     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4048       int Val = PermMask[HiIndex];
4049       if (Val < 0)
4050         continue;
4051       if (Val >= 4)
4052         break;
4053     }
4054
4055     Mask1[0] = PermMask[HiIndex];
4056     Mask1[1] = -1;
4057     Mask1[2] = PermMask[HiIndex^1];
4058     Mask1[3] = -1;
4059     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4060
4061     if (HiIndex >= 2) {
4062       Mask1[0] = PermMask[0];
4063       Mask1[1] = PermMask[1];
4064       Mask1[2] = HiIndex & 1 ? 6 : 4;
4065       Mask1[3] = HiIndex & 1 ? 4 : 6;
4066       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4067     } else {
4068       Mask1[0] = HiIndex & 1 ? 2 : 0;
4069       Mask1[1] = HiIndex & 1 ? 0 : 2;
4070       Mask1[2] = PermMask[2];
4071       Mask1[3] = PermMask[3];
4072       if (Mask1[2] >= 0)
4073         Mask1[2] += 4;
4074       if (Mask1[3] >= 0)
4075         Mask1[3] += 4;
4076       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4077     }
4078   }
4079
4080   // Break it into (shuffle shuffle_hi, shuffle_lo).
4081   Locs.clear();
4082   SmallVector<int,8> LoMask(4U, -1);
4083   SmallVector<int,8> HiMask(4U, -1);
4084
4085   SmallVector<int,8> *MaskPtr = &LoMask;
4086   unsigned MaskIdx = 0;
4087   unsigned LoIdx = 0;
4088   unsigned HiIdx = 2;
4089   for (unsigned i = 0; i != 4; ++i) {
4090     if (i == 2) {
4091       MaskPtr = &HiMask;
4092       MaskIdx = 1;
4093       LoIdx = 0;
4094       HiIdx = 2;
4095     }
4096     int Idx = PermMask[i];
4097     if (Idx < 0) {
4098       Locs[i] = std::make_pair(-1, -1);
4099     } else if (Idx < 4) {
4100       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4101       (*MaskPtr)[LoIdx] = Idx;
4102       LoIdx++;
4103     } else {
4104       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4105       (*MaskPtr)[HiIdx] = Idx;
4106       HiIdx++;
4107     }
4108   }
4109
4110   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4111   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4112   SmallVector<int, 8> MaskOps;
4113   for (unsigned i = 0; i != 4; ++i) {
4114     if (Locs[i].first == -1) {
4115       MaskOps.push_back(-1);
4116     } else {
4117       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4118       MaskOps.push_back(Idx);
4119     }
4120   }
4121   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4122 }
4123
4124 SDValue
4125 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4126   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4127   SDValue V1 = Op.getOperand(0);
4128   SDValue V2 = Op.getOperand(1);
4129   EVT VT = Op.getValueType();
4130   DebugLoc dl = Op.getDebugLoc();
4131   unsigned NumElems = VT.getVectorNumElements();
4132   bool isMMX = VT.getSizeInBits() == 64;
4133   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4134   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4135   bool V1IsSplat = false;
4136   bool V2IsSplat = false;
4137
4138   if (isZeroShuffle(SVOp))
4139     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4140
4141   // Promote splats to v4f32.
4142   if (SVOp->isSplat()) {
4143     if (isMMX || NumElems < 4)
4144       return Op;
4145     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4146   }
4147
4148   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4149   // do it!
4150   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4151     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4152     if (NewOp.getNode())
4153       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4154                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4155   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4156     // FIXME: Figure out a cleaner way to do this.
4157     // Try to make use of movq to zero out the top part.
4158     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4159       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4160       if (NewOp.getNode()) {
4161         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4162           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4163                               DAG, Subtarget, dl);
4164       }
4165     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4166       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4167       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4168         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4169                             DAG, Subtarget, dl);
4170     }
4171   }
4172
4173   if (X86::isPSHUFDMask(SVOp))
4174     return Op;
4175
4176   // Check if this can be converted into a logical shift.
4177   bool isLeft = false;
4178   unsigned ShAmt = 0;
4179   SDValue ShVal;
4180   bool isShift = getSubtarget()->hasSSE2() &&
4181   isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4182   if (isShift && ShVal.hasOneUse()) {
4183     // If the shifted value has multiple uses, it may be cheaper to use
4184     // v_set0 + movlhps or movhlps, etc.
4185     EVT EVT = VT.getVectorElementType();
4186     ShAmt *= EVT.getSizeInBits();
4187     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4188   }
4189
4190   if (X86::isMOVLMask(SVOp)) {
4191     if (V1IsUndef)
4192       return V2;
4193     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4194       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4195     if (!isMMX)
4196       return Op;
4197   }
4198
4199   // FIXME: fold these into legal mask.
4200   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4201                  X86::isMOVSLDUPMask(SVOp) ||
4202                  X86::isMOVHLPSMask(SVOp) ||
4203                  X86::isMOVHPMask(SVOp) ||
4204                  X86::isMOVLPMask(SVOp)))
4205     return Op;
4206
4207   if (ShouldXformToMOVHLPS(SVOp) ||
4208       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4209     return CommuteVectorShuffle(SVOp, DAG);
4210
4211   if (isShift) {
4212     // No better options. Use a vshl / vsrl.
4213     EVT EVT = VT.getVectorElementType();
4214     ShAmt *= EVT.getSizeInBits();
4215     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4216   }
4217
4218   bool Commuted = false;
4219   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4220   // 1,1,1,1 -> v8i16 though.
4221   V1IsSplat = isSplatVector(V1.getNode());
4222   V2IsSplat = isSplatVector(V2.getNode());
4223
4224   // Canonicalize the splat or undef, if present, to be on the RHS.
4225   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4226     Op = CommuteVectorShuffle(SVOp, DAG);
4227     SVOp = cast<ShuffleVectorSDNode>(Op);
4228     V1 = SVOp->getOperand(0);
4229     V2 = SVOp->getOperand(1);
4230     std::swap(V1IsSplat, V2IsSplat);
4231     std::swap(V1IsUndef, V2IsUndef);
4232     Commuted = true;
4233   }
4234
4235   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4236     // Shuffling low element of v1 into undef, just return v1.
4237     if (V2IsUndef)
4238       return V1;
4239     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4240     // the instruction selector will not match, so get a canonical MOVL with
4241     // swapped operands to undo the commute.
4242     return getMOVL(DAG, dl, VT, V2, V1);
4243   }
4244
4245   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4246       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4247       X86::isUNPCKLMask(SVOp) ||
4248       X86::isUNPCKHMask(SVOp))
4249     return Op;
4250
4251   if (V2IsSplat) {
4252     // Normalize mask so all entries that point to V2 points to its first
4253     // element then try to match unpck{h|l} again. If match, return a
4254     // new vector_shuffle with the corrected mask.
4255     SDValue NewMask = NormalizeMask(SVOp, DAG);
4256     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4257     if (NSVOp != SVOp) {
4258       if (X86::isUNPCKLMask(NSVOp, true)) {
4259         return NewMask;
4260       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4261         return NewMask;
4262       }
4263     }
4264   }
4265
4266   if (Commuted) {
4267     // Commute is back and try unpck* again.
4268     // FIXME: this seems wrong.
4269     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4270     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4271     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4272         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4273         X86::isUNPCKLMask(NewSVOp) ||
4274         X86::isUNPCKHMask(NewSVOp))
4275       return NewOp;
4276   }
4277
4278   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4279
4280   // Normalize the node to match x86 shuffle ops if needed
4281   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4282     return CommuteVectorShuffle(SVOp, DAG);
4283
4284   // Check for legal shuffle and return?
4285   SmallVector<int, 16> PermMask;
4286   SVOp->getMask(PermMask);
4287   if (isShuffleMaskLegal(PermMask, VT))
4288     return Op;
4289
4290   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4291   if (VT == MVT::v8i16) {
4292     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4293     if (NewOp.getNode())
4294       return NewOp;
4295   }
4296
4297   if (VT == MVT::v16i8) {
4298     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4299     if (NewOp.getNode())
4300       return NewOp;
4301   }
4302
4303   // Handle all 4 wide cases with a number of shuffles except for MMX.
4304   if (NumElems == 4 && !isMMX)
4305     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4306
4307   return SDValue();
4308 }
4309
4310 SDValue
4311 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4312                                                 SelectionDAG &DAG) {
4313   EVT VT = Op.getValueType();
4314   DebugLoc dl = Op.getDebugLoc();
4315   if (VT.getSizeInBits() == 8) {
4316     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4317                                     Op.getOperand(0), Op.getOperand(1));
4318     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4319                                     DAG.getValueType(VT));
4320     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4321   } else if (VT.getSizeInBits() == 16) {
4322     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4323     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4324     if (Idx == 0)
4325       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4326                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4327                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4328                                                  MVT::v4i32,
4329                                                  Op.getOperand(0)),
4330                                      Op.getOperand(1)));
4331     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4332                                     Op.getOperand(0), Op.getOperand(1));
4333     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4334                                     DAG.getValueType(VT));
4335     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4336   } else if (VT == MVT::f32) {
4337     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4338     // the result back to FR32 register. It's only worth matching if the
4339     // result has a single use which is a store or a bitcast to i32.  And in
4340     // the case of a store, it's not worth it if the index is a constant 0,
4341     // because a MOVSSmr can be used instead, which is smaller and faster.
4342     if (!Op.hasOneUse())
4343       return SDValue();
4344     SDNode *User = *Op.getNode()->use_begin();
4345     if ((User->getOpcode() != ISD::STORE ||
4346          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4347           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4348         (User->getOpcode() != ISD::BIT_CONVERT ||
4349          User->getValueType(0) != MVT::i32))
4350       return SDValue();
4351     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4352                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4353                                               Op.getOperand(0)),
4354                                               Op.getOperand(1));
4355     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4356   } else if (VT == MVT::i32) {
4357     // ExtractPS works with constant index.
4358     if (isa<ConstantSDNode>(Op.getOperand(1)))
4359       return Op;
4360   }
4361   return SDValue();
4362 }
4363
4364
4365 SDValue
4366 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4367   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4368     return SDValue();
4369
4370   if (Subtarget->hasSSE41()) {
4371     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4372     if (Res.getNode())
4373       return Res;
4374   }
4375
4376   EVT VT = Op.getValueType();
4377   DebugLoc dl = Op.getDebugLoc();
4378   // TODO: handle v16i8.
4379   if (VT.getSizeInBits() == 16) {
4380     SDValue Vec = Op.getOperand(0);
4381     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4382     if (Idx == 0)
4383       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4384                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4385                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4386                                                  MVT::v4i32, Vec),
4387                                      Op.getOperand(1)));
4388     // Transform it so it match pextrw which produces a 32-bit result.
4389     EVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4390     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4391                                     Op.getOperand(0), Op.getOperand(1));
4392     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4393                                     DAG.getValueType(VT));
4394     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4395   } else if (VT.getSizeInBits() == 32) {
4396     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4397     if (Idx == 0)
4398       return Op;
4399
4400     // SHUFPS the element to the lowest double word, then movss.
4401     int Mask[4] = { Idx, -1, -1, -1 };
4402     EVT VVT = Op.getOperand(0).getValueType();
4403     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4404                                        DAG.getUNDEF(VVT), Mask);
4405     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4406                        DAG.getIntPtrConstant(0));
4407   } else if (VT.getSizeInBits() == 64) {
4408     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4409     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4410     //        to match extract_elt for f64.
4411     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4412     if (Idx == 0)
4413       return Op;
4414
4415     // UNPCKHPD the element to the lowest double word, then movsd.
4416     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4417     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4418     int Mask[2] = { 1, -1 };
4419     EVT VVT = Op.getOperand(0).getValueType();
4420     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4421                                        DAG.getUNDEF(VVT), Mask);
4422     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4423                        DAG.getIntPtrConstant(0));
4424   }
4425
4426   return SDValue();
4427 }
4428
4429 SDValue
4430 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4431   EVT VT = Op.getValueType();
4432   EVT EVT = VT.getVectorElementType();
4433   DebugLoc dl = Op.getDebugLoc();
4434
4435   SDValue N0 = Op.getOperand(0);
4436   SDValue N1 = Op.getOperand(1);
4437   SDValue N2 = Op.getOperand(2);
4438
4439   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4440       isa<ConstantSDNode>(N2)) {
4441     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4442                                               : X86ISD::PINSRW;
4443     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4444     // argument.
4445     if (N1.getValueType() != MVT::i32)
4446       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4447     if (N2.getValueType() != MVT::i32)
4448       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4449     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4450   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4451     // Bits [7:6] of the constant are the source select.  This will always be
4452     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4453     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4454     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4455     // Bits [5:4] of the constant are the destination select.  This is the
4456     //  value of the incoming immediate.
4457     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4458     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4459     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4460     // Create this as a scalar to vector..
4461     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4462     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4463   } else if (EVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4464     // PINSR* works with constant index.
4465     return Op;
4466   }
4467   return SDValue();
4468 }
4469
4470 SDValue
4471 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4472   EVT VT = Op.getValueType();
4473   EVT EVT = VT.getVectorElementType();
4474
4475   if (Subtarget->hasSSE41())
4476     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4477
4478   if (EVT == MVT::i8)
4479     return SDValue();
4480
4481   DebugLoc dl = Op.getDebugLoc();
4482   SDValue N0 = Op.getOperand(0);
4483   SDValue N1 = Op.getOperand(1);
4484   SDValue N2 = Op.getOperand(2);
4485
4486   if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4487     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4488     // as its second argument.
4489     if (N1.getValueType() != MVT::i32)
4490       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4491     if (N2.getValueType() != MVT::i32)
4492       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4493     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4494   }
4495   return SDValue();
4496 }
4497
4498 SDValue
4499 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4500   DebugLoc dl = Op.getDebugLoc();
4501   if (Op.getValueType() == MVT::v2f32)
4502     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4503                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4504                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4505                                                Op.getOperand(0))));
4506
4507   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4508     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4509
4510   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4511   EVT VT = MVT::v2i32;
4512   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4513   default: break;
4514   case MVT::v16i8:
4515   case MVT::v8i16:
4516     VT = MVT::v4i32;
4517     break;
4518   }
4519   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4520                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4521 }
4522
4523 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4524 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4525 // one of the above mentioned nodes. It has to be wrapped because otherwise
4526 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4527 // be used to form addressing mode. These wrapped nodes will be selected
4528 // into MOV32ri.
4529 SDValue
4530 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4531   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4532
4533   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4534   // global base reg.
4535   unsigned char OpFlag = 0;
4536   unsigned WrapperKind = X86ISD::Wrapper;
4537   CodeModel::Model M = getTargetMachine().getCodeModel();
4538
4539   if (Subtarget->isPICStyleRIPRel() &&
4540       (M == CodeModel::Small || M == CodeModel::Kernel))
4541     WrapperKind = X86ISD::WrapperRIP;
4542   else if (Subtarget->isPICStyleGOT())
4543     OpFlag = X86II::MO_GOTOFF;
4544   else if (Subtarget->isPICStyleStubPIC())
4545     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4546
4547   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4548                                              CP->getAlignment(),
4549                                              CP->getOffset(), OpFlag);
4550   DebugLoc DL = CP->getDebugLoc();
4551   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4552   // With PIC, the address is actually $g + Offset.
4553   if (OpFlag) {
4554     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4555                          DAG.getNode(X86ISD::GlobalBaseReg,
4556                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4557                          Result);
4558   }
4559
4560   return Result;
4561 }
4562
4563 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4564   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4565
4566   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4567   // global base reg.
4568   unsigned char OpFlag = 0;
4569   unsigned WrapperKind = X86ISD::Wrapper;
4570   CodeModel::Model M = getTargetMachine().getCodeModel();
4571
4572   if (Subtarget->isPICStyleRIPRel() &&
4573       (M == CodeModel::Small || M == CodeModel::Kernel))
4574     WrapperKind = X86ISD::WrapperRIP;
4575   else if (Subtarget->isPICStyleGOT())
4576     OpFlag = X86II::MO_GOTOFF;
4577   else if (Subtarget->isPICStyleStubPIC())
4578     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4579
4580   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4581                                           OpFlag);
4582   DebugLoc DL = JT->getDebugLoc();
4583   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4584
4585   // With PIC, the address is actually $g + Offset.
4586   if (OpFlag) {
4587     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4588                          DAG.getNode(X86ISD::GlobalBaseReg,
4589                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4590                          Result);
4591   }
4592
4593   return Result;
4594 }
4595
4596 SDValue
4597 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4598   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4599
4600   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4601   // global base reg.
4602   unsigned char OpFlag = 0;
4603   unsigned WrapperKind = X86ISD::Wrapper;
4604   CodeModel::Model M = getTargetMachine().getCodeModel();
4605
4606   if (Subtarget->isPICStyleRIPRel() &&
4607       (M == CodeModel::Small || M == CodeModel::Kernel))
4608     WrapperKind = X86ISD::WrapperRIP;
4609   else if (Subtarget->isPICStyleGOT())
4610     OpFlag = X86II::MO_GOTOFF;
4611   else if (Subtarget->isPICStyleStubPIC())
4612     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4613
4614   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4615
4616   DebugLoc DL = Op.getDebugLoc();
4617   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4618
4619
4620   // With PIC, the address is actually $g + Offset.
4621   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4622       !Subtarget->is64Bit()) {
4623     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4624                          DAG.getNode(X86ISD::GlobalBaseReg,
4625                                      DebugLoc::getUnknownLoc(),
4626                                      getPointerTy()),
4627                          Result);
4628   }
4629
4630   return Result;
4631 }
4632
4633 SDValue
4634 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4635                                       int64_t Offset,
4636                                       SelectionDAG &DAG) const {
4637   // Create the TargetGlobalAddress node, folding in the constant
4638   // offset if it is legal.
4639   unsigned char OpFlags =
4640     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4641   CodeModel::Model M = getTargetMachine().getCodeModel();
4642   SDValue Result;
4643   if (OpFlags == X86II::MO_NO_FLAG &&
4644       X86::isOffsetSuitableForCodeModel(Offset, M)) {
4645     // A direct static reference to a global.
4646     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4647     Offset = 0;
4648   } else {
4649     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4650   }
4651
4652   if (Subtarget->isPICStyleRIPRel() &&
4653       (M == CodeModel::Small || M == CodeModel::Kernel))
4654     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4655   else
4656     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4657
4658   // With PIC, the address is actually $g + Offset.
4659   if (isGlobalRelativeToPICBase(OpFlags)) {
4660     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4661                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4662                          Result);
4663   }
4664
4665   // For globals that require a load from a stub to get the address, emit the
4666   // load.
4667   if (isGlobalStubReference(OpFlags))
4668     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4669                          PseudoSourceValue::getGOT(), 0);
4670
4671   // If there was a non-zero offset that we didn't fold, create an explicit
4672   // addition for it.
4673   if (Offset != 0)
4674     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4675                          DAG.getConstant(Offset, getPointerTy()));
4676
4677   return Result;
4678 }
4679
4680 SDValue
4681 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4682   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4683   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4684   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4685 }
4686
4687 static SDValue
4688 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4689            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4690            unsigned char OperandFlags) {
4691   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4692   DebugLoc dl = GA->getDebugLoc();
4693   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4694                                            GA->getValueType(0),
4695                                            GA->getOffset(),
4696                                            OperandFlags);
4697   if (InFlag) {
4698     SDValue Ops[] = { Chain,  TGA, *InFlag };
4699     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4700   } else {
4701     SDValue Ops[]  = { Chain, TGA };
4702     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4703   }
4704   SDValue Flag = Chain.getValue(1);
4705   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4706 }
4707
4708 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4709 static SDValue
4710 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4711                                 const EVT PtrVT) {
4712   SDValue InFlag;
4713   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
4714   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4715                                      DAG.getNode(X86ISD::GlobalBaseReg,
4716                                                  DebugLoc::getUnknownLoc(),
4717                                                  PtrVT), InFlag);
4718   InFlag = Chain.getValue(1);
4719
4720   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4721 }
4722
4723 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4724 static SDValue
4725 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4726                                 const EVT PtrVT) {
4727   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4728                     X86::RAX, X86II::MO_TLSGD);
4729 }
4730
4731 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4732 // "local exec" model.
4733 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4734                                    const EVT PtrVT, TLSModel::Model model,
4735                                    bool is64Bit) {
4736   DebugLoc dl = GA->getDebugLoc();
4737   // Get the Thread Pointer
4738   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4739                              DebugLoc::getUnknownLoc(), PtrVT,
4740                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
4741                                              MVT::i32));
4742
4743   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4744                                       NULL, 0);
4745
4746   unsigned char OperandFlags = 0;
4747   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
4748   // initialexec.
4749   unsigned WrapperKind = X86ISD::Wrapper;
4750   if (model == TLSModel::LocalExec) {
4751     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4752   } else if (is64Bit) {
4753     assert(model == TLSModel::InitialExec);
4754     OperandFlags = X86II::MO_GOTTPOFF;
4755     WrapperKind = X86ISD::WrapperRIP;
4756   } else {
4757     assert(model == TLSModel::InitialExec);
4758     OperandFlags = X86II::MO_INDNTPOFF;
4759   }
4760
4761   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4762   // exec)
4763   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4764                                            GA->getOffset(), OperandFlags);
4765   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4766
4767   if (model == TLSModel::InitialExec)
4768     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4769                          PseudoSourceValue::getGOT(), 0);
4770
4771   // The address of the thread local variable is the add of the thread
4772   // pointer with the offset of the variable.
4773   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4774 }
4775
4776 SDValue
4777 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4778   // TODO: implement the "local dynamic" model
4779   // TODO: implement the "initial exec"model for pic executables
4780   assert(Subtarget->isTargetELF() &&
4781          "TLS not implemented for non-ELF targets");
4782   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4783   const GlobalValue *GV = GA->getGlobal();
4784
4785   // If GV is an alias then use the aliasee for determining
4786   // thread-localness.
4787   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4788     GV = GA->resolveAliasedGlobal(false);
4789
4790   TLSModel::Model model = getTLSModel(GV,
4791                                       getTargetMachine().getRelocationModel());
4792
4793   switch (model) {
4794   case TLSModel::GeneralDynamic:
4795   case TLSModel::LocalDynamic: // not implemented
4796     if (Subtarget->is64Bit())
4797       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4798     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4799
4800   case TLSModel::InitialExec:
4801   case TLSModel::LocalExec:
4802     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4803                                Subtarget->is64Bit());
4804   }
4805
4806   llvm_unreachable("Unreachable");
4807   return SDValue();
4808 }
4809
4810
4811 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4812 /// take a 2 x i32 value to shift plus a shift amount.
4813 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4814   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4815   EVT VT = Op.getValueType();
4816   unsigned VTBits = VT.getSizeInBits();
4817   DebugLoc dl = Op.getDebugLoc();
4818   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4819   SDValue ShOpLo = Op.getOperand(0);
4820   SDValue ShOpHi = Op.getOperand(1);
4821   SDValue ShAmt  = Op.getOperand(2);
4822   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4823                                      DAG.getConstant(VTBits - 1, MVT::i8))
4824                        : DAG.getConstant(0, VT);
4825
4826   SDValue Tmp2, Tmp3;
4827   if (Op.getOpcode() == ISD::SHL_PARTS) {
4828     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4829     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4830   } else {
4831     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4832     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4833   }
4834
4835   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4836                                 DAG.getConstant(VTBits, MVT::i8));
4837   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4838                              AndNode, DAG.getConstant(0, MVT::i8));
4839
4840   SDValue Hi, Lo;
4841   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4842   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4843   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4844
4845   if (Op.getOpcode() == ISD::SHL_PARTS) {
4846     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4847     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4848   } else {
4849     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4850     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4851   }
4852
4853   SDValue Ops[2] = { Lo, Hi };
4854   return DAG.getMergeValues(Ops, 2, dl);
4855 }
4856
4857 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4858   EVT SrcVT = Op.getOperand(0).getValueType();
4859
4860   if (SrcVT.isVector()) {
4861     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4862       return Op;
4863     }
4864     return SDValue();
4865   }
4866
4867   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4868          "Unknown SINT_TO_FP to lower!");
4869
4870   // These are really Legal; return the operand so the caller accepts it as
4871   // Legal.
4872   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4873     return Op;
4874   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4875       Subtarget->is64Bit()) {
4876     return Op;
4877   }
4878
4879   DebugLoc dl = Op.getDebugLoc();
4880   unsigned Size = SrcVT.getSizeInBits()/8;
4881   MachineFunction &MF = DAG.getMachineFunction();
4882   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4883   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4884   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4885                                StackSlot,
4886                                PseudoSourceValue::getFixedStack(SSFI), 0);
4887   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4888 }
4889
4890 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
4891                                      SDValue StackSlot,
4892                                      SelectionDAG &DAG) {
4893   // Build the FILD
4894   DebugLoc dl = Op.getDebugLoc();
4895   SDVTList Tys;
4896   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4897   if (useSSE)
4898     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4899   else
4900     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4901   SmallVector<SDValue, 8> Ops;
4902   Ops.push_back(Chain);
4903   Ops.push_back(StackSlot);
4904   Ops.push_back(DAG.getValueType(SrcVT));
4905   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4906                                  Tys, &Ops[0], Ops.size());
4907
4908   if (useSSE) {
4909     Chain = Result.getValue(1);
4910     SDValue InFlag = Result.getValue(2);
4911
4912     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4913     // shouldn't be necessary except that RFP cannot be live across
4914     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4915     MachineFunction &MF = DAG.getMachineFunction();
4916     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4917     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4918     Tys = DAG.getVTList(MVT::Other);
4919     SmallVector<SDValue, 8> Ops;
4920     Ops.push_back(Chain);
4921     Ops.push_back(Result);
4922     Ops.push_back(StackSlot);
4923     Ops.push_back(DAG.getValueType(Op.getValueType()));
4924     Ops.push_back(InFlag);
4925     Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4926     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4927                          PseudoSourceValue::getFixedStack(SSFI), 0);
4928   }
4929
4930   return Result;
4931 }
4932
4933 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4934 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4935   // This algorithm is not obvious. Here it is in C code, more or less:
4936   /*
4937     double uint64_to_double( uint32_t hi, uint32_t lo ) {
4938       static const __m128i exp = { 0x4330000045300000ULL, 0 };
4939       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4940
4941       // Copy ints to xmm registers.
4942       __m128i xh = _mm_cvtsi32_si128( hi );
4943       __m128i xl = _mm_cvtsi32_si128( lo );
4944
4945       // Combine into low half of a single xmm register.
4946       __m128i x = _mm_unpacklo_epi32( xh, xl );
4947       __m128d d;
4948       double sd;
4949
4950       // Merge in appropriate exponents to give the integer bits the right
4951       // magnitude.
4952       x = _mm_unpacklo_epi32( x, exp );
4953
4954       // Subtract away the biases to deal with the IEEE-754 double precision
4955       // implicit 1.
4956       d = _mm_sub_pd( (__m128d) x, bias );
4957
4958       // All conversions up to here are exact. The correctly rounded result is
4959       // calculated using the current rounding mode using the following
4960       // horizontal add.
4961       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4962       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
4963                                 // store doesn't really need to be here (except
4964                                 // maybe to zero the other double)
4965       return sd;
4966     }
4967   */
4968
4969   DebugLoc dl = Op.getDebugLoc();
4970   LLVMContext *Context = DAG.getContext();
4971
4972   // Build some magic constants.
4973   std::vector<Constant*> CV0;
4974   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
4975   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
4976   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4977   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4978   Constant *C0 = ConstantVector::get(CV0);
4979   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4980
4981   std::vector<Constant*> CV1;
4982   CV1.push_back(
4983     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
4984   CV1.push_back(
4985     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
4986   Constant *C1 = ConstantVector::get(CV1);
4987   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4988
4989   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4990                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4991                                         Op.getOperand(0),
4992                                         DAG.getIntPtrConstant(1)));
4993   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4994                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4995                                         Op.getOperand(0),
4996                                         DAG.getIntPtrConstant(0)));
4997   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4998   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4999                               PseudoSourceValue::getConstantPool(), 0,
5000                               false, 16);
5001   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5002   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5003   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5004                               PseudoSourceValue::getConstantPool(), 0,
5005                               false, 16);
5006   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5007
5008   // Add the halves; easiest way is to swap them into another reg first.
5009   int ShufMask[2] = { 1, -1 };
5010   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5011                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5012   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5013   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5014                      DAG.getIntPtrConstant(0));
5015 }
5016
5017 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5018 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5019   DebugLoc dl = Op.getDebugLoc();
5020   // FP constant to bias correct the final result.
5021   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5022                                    MVT::f64);
5023
5024   // Load the 32-bit value into an XMM register.
5025   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5026                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5027                                          Op.getOperand(0),
5028                                          DAG.getIntPtrConstant(0)));
5029
5030   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5031                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5032                      DAG.getIntPtrConstant(0));
5033
5034   // Or the load with the bias.
5035   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5036                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5037                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5038                                                    MVT::v2f64, Load)),
5039                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5040                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5041                                                    MVT::v2f64, Bias)));
5042   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5043                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5044                    DAG.getIntPtrConstant(0));
5045
5046   // Subtract the bias.
5047   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5048
5049   // Handle final rounding.
5050   EVT DestVT = Op.getValueType();
5051
5052   if (DestVT.bitsLT(MVT::f64)) {
5053     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5054                        DAG.getIntPtrConstant(0));
5055   } else if (DestVT.bitsGT(MVT::f64)) {
5056     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5057   }
5058
5059   // Handle final rounding.
5060   return Sub;
5061 }
5062
5063 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5064   SDValue N0 = Op.getOperand(0);
5065   DebugLoc dl = Op.getDebugLoc();
5066
5067   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5068   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5069   // the optimization here.
5070   if (DAG.SignBitIsZero(N0))
5071     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5072
5073   EVT SrcVT = N0.getValueType();
5074   if (SrcVT == MVT::i64) {
5075     // We only handle SSE2 f64 target here; caller can expand the rest.
5076     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5077       return SDValue();
5078
5079     return LowerUINT_TO_FP_i64(Op, DAG);
5080   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5081     return LowerUINT_TO_FP_i32(Op, DAG);
5082   }
5083
5084   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5085
5086   // Make a 64-bit buffer, and use it to build an FILD.
5087   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5088   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5089   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5090                                    getPointerTy(), StackSlot, WordOff);
5091   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5092                                 StackSlot, NULL, 0);
5093   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5094                                 OffsetSlot, NULL, 0);
5095   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5096 }
5097
5098 std::pair<SDValue,SDValue> X86TargetLowering::
5099 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5100   DebugLoc dl = Op.getDebugLoc();
5101
5102   EVT DstTy = Op.getValueType();
5103
5104   if (!IsSigned) {
5105     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5106     DstTy = MVT::i64;
5107   }
5108
5109   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5110          DstTy.getSimpleVT() >= MVT::i16 &&
5111          "Unknown FP_TO_SINT to lower!");
5112
5113   // These are really Legal.
5114   if (DstTy == MVT::i32 &&
5115       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5116     return std::make_pair(SDValue(), SDValue());
5117   if (Subtarget->is64Bit() &&
5118       DstTy == MVT::i64 &&
5119       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5120     return std::make_pair(SDValue(), SDValue());
5121
5122   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5123   // stack slot.
5124   MachineFunction &MF = DAG.getMachineFunction();
5125   unsigned MemSize = DstTy.getSizeInBits()/8;
5126   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5127   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5128
5129   unsigned Opc;
5130   switch (DstTy.getSimpleVT().SimpleTy) {
5131   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5132   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5133   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5134   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5135   }
5136
5137   SDValue Chain = DAG.getEntryNode();
5138   SDValue Value = Op.getOperand(0);
5139   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5140     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5141     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5142                          PseudoSourceValue::getFixedStack(SSFI), 0);
5143     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5144     SDValue Ops[] = {
5145       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5146     };
5147     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5148     Chain = Value.getValue(1);
5149     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5150     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5151   }
5152
5153   // Build the FP_TO_INT*_IN_MEM
5154   SDValue Ops[] = { Chain, Value, StackSlot };
5155   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5156
5157   return std::make_pair(FIST, StackSlot);
5158 }
5159
5160 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5161   if (Op.getValueType().isVector()) {
5162     if (Op.getValueType() == MVT::v2i32 &&
5163         Op.getOperand(0).getValueType() == MVT::v2f64) {
5164       return Op;
5165     }
5166     return SDValue();
5167   }
5168
5169   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5170   SDValue FIST = Vals.first, StackSlot = Vals.second;
5171   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5172   if (FIST.getNode() == 0) return Op;
5173
5174   // Load the result.
5175   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5176                      FIST, StackSlot, NULL, 0);
5177 }
5178
5179 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5180   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5181   SDValue FIST = Vals.first, StackSlot = Vals.second;
5182   assert(FIST.getNode() && "Unexpected failure");
5183
5184   // Load the result.
5185   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5186                      FIST, StackSlot, NULL, 0);
5187 }
5188
5189 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5190   LLVMContext *Context = DAG.getContext();
5191   DebugLoc dl = Op.getDebugLoc();
5192   EVT VT = Op.getValueType();
5193   EVT EltVT = VT;
5194   if (VT.isVector())
5195     EltVT = VT.getVectorElementType();
5196   std::vector<Constant*> CV;
5197   if (EltVT == MVT::f64) {
5198     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5199     CV.push_back(C);
5200     CV.push_back(C);
5201   } else {
5202     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5203     CV.push_back(C);
5204     CV.push_back(C);
5205     CV.push_back(C);
5206     CV.push_back(C);
5207   }
5208   Constant *C = ConstantVector::get(CV);
5209   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5210   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5211                                PseudoSourceValue::getConstantPool(), 0,
5212                                false, 16);
5213   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5214 }
5215
5216 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5217   LLVMContext *Context = DAG.getContext();
5218   DebugLoc dl = Op.getDebugLoc();
5219   EVT VT = Op.getValueType();
5220   EVT EltVT = VT;
5221   unsigned EltNum = 1;
5222   if (VT.isVector()) {
5223     EltVT = VT.getVectorElementType();
5224     EltNum = VT.getVectorNumElements();
5225   }
5226   std::vector<Constant*> CV;
5227   if (EltVT == MVT::f64) {
5228     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5229     CV.push_back(C);
5230     CV.push_back(C);
5231   } else {
5232     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5233     CV.push_back(C);
5234     CV.push_back(C);
5235     CV.push_back(C);
5236     CV.push_back(C);
5237   }
5238   Constant *C = ConstantVector::get(CV);
5239   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5240   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5241                                PseudoSourceValue::getConstantPool(), 0,
5242                                false, 16);
5243   if (VT.isVector()) {
5244     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5245                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5246                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5247                                 Op.getOperand(0)),
5248                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5249   } else {
5250     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5251   }
5252 }
5253
5254 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5255   LLVMContext *Context = DAG.getContext();
5256   SDValue Op0 = Op.getOperand(0);
5257   SDValue Op1 = Op.getOperand(1);
5258   DebugLoc dl = Op.getDebugLoc();
5259   EVT VT = Op.getValueType();
5260   EVT SrcVT = Op1.getValueType();
5261
5262   // If second operand is smaller, extend it first.
5263   if (SrcVT.bitsLT(VT)) {
5264     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5265     SrcVT = VT;
5266   }
5267   // And if it is bigger, shrink it first.
5268   if (SrcVT.bitsGT(VT)) {
5269     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5270     SrcVT = VT;
5271   }
5272
5273   // At this point the operands and the result should have the same
5274   // type, and that won't be f80 since that is not custom lowered.
5275
5276   // First get the sign bit of second operand.
5277   std::vector<Constant*> CV;
5278   if (SrcVT == MVT::f64) {
5279     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5280     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5281   } else {
5282     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5283     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5284     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5285     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5286   }
5287   Constant *C = ConstantVector::get(CV);
5288   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5289   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5290                                 PseudoSourceValue::getConstantPool(), 0,
5291                                 false, 16);
5292   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5293
5294   // Shift sign bit right or left if the two operands have different types.
5295   if (SrcVT.bitsGT(VT)) {
5296     // Op0 is MVT::f32, Op1 is MVT::f64.
5297     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5298     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5299                           DAG.getConstant(32, MVT::i32));
5300     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5301     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5302                           DAG.getIntPtrConstant(0));
5303   }
5304
5305   // Clear first operand sign bit.
5306   CV.clear();
5307   if (VT == MVT::f64) {
5308     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5309     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5310   } else {
5311     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5312     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5313     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5314     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5315   }
5316   C = ConstantVector::get(CV);
5317   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5318   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5319                                 PseudoSourceValue::getConstantPool(), 0,
5320                                 false, 16);
5321   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5322
5323   // Or the value with the sign bit.
5324   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5325 }
5326
5327 /// Emit nodes that will be selected as "test Op0,Op0", or something
5328 /// equivalent.
5329 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5330                                     SelectionDAG &DAG) {
5331   DebugLoc dl = Op.getDebugLoc();
5332
5333   // CF and OF aren't always set the way we want. Determine which
5334   // of these we need.
5335   bool NeedCF = false;
5336   bool NeedOF = false;
5337   switch (X86CC) {
5338   case X86::COND_A: case X86::COND_AE:
5339   case X86::COND_B: case X86::COND_BE:
5340     NeedCF = true;
5341     break;
5342   case X86::COND_G: case X86::COND_GE:
5343   case X86::COND_L: case X86::COND_LE:
5344   case X86::COND_O: case X86::COND_NO:
5345     NeedOF = true;
5346     break;
5347   default: break;
5348   }
5349
5350   // See if we can use the EFLAGS value from the operand instead of
5351   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5352   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5353   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5354     unsigned Opcode = 0;
5355     unsigned NumOperands = 0;
5356     switch (Op.getNode()->getOpcode()) {
5357     case ISD::ADD:
5358       // Due to an isel shortcoming, be conservative if this add is likely to
5359       // be selected as part of a load-modify-store instruction. When the root
5360       // node in a match is a store, isel doesn't know how to remap non-chain
5361       // non-flag uses of other nodes in the match, such as the ADD in this
5362       // case. This leads to the ADD being left around and reselected, with
5363       // the result being two adds in the output.
5364       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5365            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5366         if (UI->getOpcode() == ISD::STORE)
5367           goto default_case;
5368       if (ConstantSDNode *C =
5369             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5370         // An add of one will be selected as an INC.
5371         if (C->getAPIntValue() == 1) {
5372           Opcode = X86ISD::INC;
5373           NumOperands = 1;
5374           break;
5375         }
5376         // An add of negative one (subtract of one) will be selected as a DEC.
5377         if (C->getAPIntValue().isAllOnesValue()) {
5378           Opcode = X86ISD::DEC;
5379           NumOperands = 1;
5380           break;
5381         }
5382       }
5383       // Otherwise use a regular EFLAGS-setting add.
5384       Opcode = X86ISD::ADD;
5385       NumOperands = 2;
5386       break;
5387     case ISD::SUB:
5388       // Due to the ISEL shortcoming noted above, be conservative if this sub is
5389       // likely to be selected as part of a load-modify-store instruction.
5390       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5391            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5392         if (UI->getOpcode() == ISD::STORE)
5393           goto default_case;
5394       // Otherwise use a regular EFLAGS-setting sub.
5395       Opcode = X86ISD::SUB;
5396       NumOperands = 2;
5397       break;
5398     case X86ISD::ADD:
5399     case X86ISD::SUB:
5400     case X86ISD::INC:
5401     case X86ISD::DEC:
5402       return SDValue(Op.getNode(), 1);
5403     default:
5404     default_case:
5405       break;
5406     }
5407     if (Opcode != 0) {
5408       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5409       SmallVector<SDValue, 4> Ops;
5410       for (unsigned i = 0; i != NumOperands; ++i)
5411         Ops.push_back(Op.getOperand(i));
5412       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5413       DAG.ReplaceAllUsesWith(Op, New);
5414       return SDValue(New.getNode(), 1);
5415     }
5416   }
5417
5418   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5419   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5420                      DAG.getConstant(0, Op.getValueType()));
5421 }
5422
5423 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5424 /// equivalent.
5425 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5426                                    SelectionDAG &DAG) {
5427   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5428     if (C->getAPIntValue() == 0)
5429       return EmitTest(Op0, X86CC, DAG);
5430
5431   DebugLoc dl = Op0.getDebugLoc();
5432   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5433 }
5434
5435 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5436   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5437   SDValue Op0 = Op.getOperand(0);
5438   SDValue Op1 = Op.getOperand(1);
5439   DebugLoc dl = Op.getDebugLoc();
5440   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5441
5442   // Lower (X & (1 << N)) == 0 to BT(X, N).
5443   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5444   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5445   if (Op0.getOpcode() == ISD::AND &&
5446       Op0.hasOneUse() &&
5447       Op1.getOpcode() == ISD::Constant &&
5448       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5449       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5450     SDValue LHS, RHS;
5451     if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5452       if (ConstantSDNode *Op010C =
5453             dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5454         if (Op010C->getZExtValue() == 1) {
5455           LHS = Op0.getOperand(0);
5456           RHS = Op0.getOperand(1).getOperand(1);
5457         }
5458     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5459       if (ConstantSDNode *Op000C =
5460             dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5461         if (Op000C->getZExtValue() == 1) {
5462           LHS = Op0.getOperand(1);
5463           RHS = Op0.getOperand(0).getOperand(1);
5464         }
5465     } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5466       ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5467       SDValue AndLHS = Op0.getOperand(0);
5468       if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5469         LHS = AndLHS.getOperand(0);
5470         RHS = AndLHS.getOperand(1);
5471       }
5472     }
5473
5474     if (LHS.getNode()) {
5475       // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5476       // instruction.  Since the shift amount is in-range-or-undefined, we know
5477       // that doing a bittest on the i16 value is ok.  We extend to i32 because
5478       // the encoding for the i16 version is larger than the i32 version.
5479       if (LHS.getValueType() == MVT::i8)
5480         LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5481
5482       // If the operand types disagree, extend the shift amount to match.  Since
5483       // BT ignores high bits (like shifts) we can use anyextend.
5484       if (LHS.getValueType() != RHS.getValueType())
5485         RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5486
5487       SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5488       unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5489       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5490                          DAG.getConstant(Cond, MVT::i8), BT);
5491     }
5492   }
5493
5494   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5495   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5496
5497   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5498   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5499                      DAG.getConstant(X86CC, MVT::i8), Cond);
5500 }
5501
5502 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5503   SDValue Cond;
5504   SDValue Op0 = Op.getOperand(0);
5505   SDValue Op1 = Op.getOperand(1);
5506   SDValue CC = Op.getOperand(2);
5507   EVT VT = Op.getValueType();
5508   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5509   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5510   DebugLoc dl = Op.getDebugLoc();
5511
5512   if (isFP) {
5513     unsigned SSECC = 8;
5514     EVT VT0 = Op0.getValueType();
5515     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5516     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5517     bool Swap = false;
5518
5519     switch (SetCCOpcode) {
5520     default: break;
5521     case ISD::SETOEQ:
5522     case ISD::SETEQ:  SSECC = 0; break;
5523     case ISD::SETOGT:
5524     case ISD::SETGT: Swap = true; // Fallthrough
5525     case ISD::SETLT:
5526     case ISD::SETOLT: SSECC = 1; break;
5527     case ISD::SETOGE:
5528     case ISD::SETGE: Swap = true; // Fallthrough
5529     case ISD::SETLE:
5530     case ISD::SETOLE: SSECC = 2; break;
5531     case ISD::SETUO:  SSECC = 3; break;
5532     case ISD::SETUNE:
5533     case ISD::SETNE:  SSECC = 4; break;
5534     case ISD::SETULE: Swap = true;
5535     case ISD::SETUGE: SSECC = 5; break;
5536     case ISD::SETULT: Swap = true;
5537     case ISD::SETUGT: SSECC = 6; break;
5538     case ISD::SETO:   SSECC = 7; break;
5539     }
5540     if (Swap)
5541       std::swap(Op0, Op1);
5542
5543     // In the two special cases we can't handle, emit two comparisons.
5544     if (SSECC == 8) {
5545       if (SetCCOpcode == ISD::SETUEQ) {
5546         SDValue UNORD, EQ;
5547         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5548         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5549         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5550       }
5551       else if (SetCCOpcode == ISD::SETONE) {
5552         SDValue ORD, NEQ;
5553         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5554         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5555         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5556       }
5557       llvm_unreachable("Illegal FP comparison");
5558     }
5559     // Handle all other FP comparisons here.
5560     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5561   }
5562
5563   // We are handling one of the integer comparisons here.  Since SSE only has
5564   // GT and EQ comparisons for integer, swapping operands and multiple
5565   // operations may be required for some comparisons.
5566   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5567   bool Swap = false, Invert = false, FlipSigns = false;
5568
5569   switch (VT.getSimpleVT().SimpleTy) {
5570   default: break;
5571   case MVT::v8i8:
5572   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5573   case MVT::v4i16:
5574   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5575   case MVT::v2i32:
5576   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5577   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5578   }
5579
5580   switch (SetCCOpcode) {
5581   default: break;
5582   case ISD::SETNE:  Invert = true;
5583   case ISD::SETEQ:  Opc = EQOpc; break;
5584   case ISD::SETLT:  Swap = true;
5585   case ISD::SETGT:  Opc = GTOpc; break;
5586   case ISD::SETGE:  Swap = true;
5587   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5588   case ISD::SETULT: Swap = true;
5589   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5590   case ISD::SETUGE: Swap = true;
5591   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5592   }
5593   if (Swap)
5594     std::swap(Op0, Op1);
5595
5596   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5597   // bits of the inputs before performing those operations.
5598   if (FlipSigns) {
5599     EVT EltVT = VT.getVectorElementType();
5600     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5601                                       EltVT);
5602     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5603     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5604                                     SignBits.size());
5605     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5606     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5607   }
5608
5609   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5610
5611   // If the logical-not of the result is required, perform that now.
5612   if (Invert)
5613     Result = DAG.getNOT(dl, Result, VT);
5614
5615   return Result;
5616 }
5617
5618 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5619 static bool isX86LogicalCmp(SDValue Op) {
5620   unsigned Opc = Op.getNode()->getOpcode();
5621   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5622     return true;
5623   if (Op.getResNo() == 1 &&
5624       (Opc == X86ISD::ADD ||
5625        Opc == X86ISD::SUB ||
5626        Opc == X86ISD::SMUL ||
5627        Opc == X86ISD::UMUL ||
5628        Opc == X86ISD::INC ||
5629        Opc == X86ISD::DEC))
5630     return true;
5631
5632   return false;
5633 }
5634
5635 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5636   bool addTest = true;
5637   SDValue Cond  = Op.getOperand(0);
5638   DebugLoc dl = Op.getDebugLoc();
5639   SDValue CC;
5640
5641   if (Cond.getOpcode() == ISD::SETCC)
5642     Cond = LowerSETCC(Cond, DAG);
5643
5644   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5645   // setting operand in place of the X86ISD::SETCC.
5646   if (Cond.getOpcode() == X86ISD::SETCC) {
5647     CC = Cond.getOperand(0);
5648
5649     SDValue Cmp = Cond.getOperand(1);
5650     unsigned Opc = Cmp.getOpcode();
5651     EVT VT = Op.getValueType();
5652
5653     bool IllegalFPCMov = false;
5654     if (VT.isFloatingPoint() && !VT.isVector() &&
5655         !isScalarFPTypeInSSEReg(VT))  // FPStack?
5656       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5657
5658     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5659         Opc == X86ISD::BT) { // FIXME
5660       Cond = Cmp;
5661       addTest = false;
5662     }
5663   }
5664
5665   if (addTest) {
5666     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5667     Cond = EmitTest(Cond, X86::COND_NE, DAG);
5668   }
5669
5670   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5671   SmallVector<SDValue, 4> Ops;
5672   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5673   // condition is true.
5674   Ops.push_back(Op.getOperand(2));
5675   Ops.push_back(Op.getOperand(1));
5676   Ops.push_back(CC);
5677   Ops.push_back(Cond);
5678   return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5679 }
5680
5681 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5682 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5683 // from the AND / OR.
5684 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5685   Opc = Op.getOpcode();
5686   if (Opc != ISD::OR && Opc != ISD::AND)
5687     return false;
5688   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5689           Op.getOperand(0).hasOneUse() &&
5690           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5691           Op.getOperand(1).hasOneUse());
5692 }
5693
5694 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5695 // 1 and that the SETCC node has a single use.
5696 static bool isXor1OfSetCC(SDValue Op) {
5697   if (Op.getOpcode() != ISD::XOR)
5698     return false;
5699   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5700   if (N1C && N1C->getAPIntValue() == 1) {
5701     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5702       Op.getOperand(0).hasOneUse();
5703   }
5704   return false;
5705 }
5706
5707 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5708   bool addTest = true;
5709   SDValue Chain = Op.getOperand(0);
5710   SDValue Cond  = Op.getOperand(1);
5711   SDValue Dest  = Op.getOperand(2);
5712   DebugLoc dl = Op.getDebugLoc();
5713   SDValue CC;
5714
5715   if (Cond.getOpcode() == ISD::SETCC)
5716     Cond = LowerSETCC(Cond, DAG);
5717 #if 0
5718   // FIXME: LowerXALUO doesn't handle these!!
5719   else if (Cond.getOpcode() == X86ISD::ADD  ||
5720            Cond.getOpcode() == X86ISD::SUB  ||
5721            Cond.getOpcode() == X86ISD::SMUL ||
5722            Cond.getOpcode() == X86ISD::UMUL)
5723     Cond = LowerXALUO(Cond, DAG);
5724 #endif
5725
5726   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5727   // setting operand in place of the X86ISD::SETCC.
5728   if (Cond.getOpcode() == X86ISD::SETCC) {
5729     CC = Cond.getOperand(0);
5730
5731     SDValue Cmp = Cond.getOperand(1);
5732     unsigned Opc = Cmp.getOpcode();
5733     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5734     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5735       Cond = Cmp;
5736       addTest = false;
5737     } else {
5738       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5739       default: break;
5740       case X86::COND_O:
5741       case X86::COND_B:
5742         // These can only come from an arithmetic instruction with overflow,
5743         // e.g. SADDO, UADDO.
5744         Cond = Cond.getNode()->getOperand(1);
5745         addTest = false;
5746         break;
5747       }
5748     }
5749   } else {
5750     unsigned CondOpc;
5751     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5752       SDValue Cmp = Cond.getOperand(0).getOperand(1);
5753       if (CondOpc == ISD::OR) {
5754         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5755         // two branches instead of an explicit OR instruction with a
5756         // separate test.
5757         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5758             isX86LogicalCmp(Cmp)) {
5759           CC = Cond.getOperand(0).getOperand(0);
5760           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5761                               Chain, Dest, CC, Cmp);
5762           CC = Cond.getOperand(1).getOperand(0);
5763           Cond = Cmp;
5764           addTest = false;
5765         }
5766       } else { // ISD::AND
5767         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5768         // two branches instead of an explicit AND instruction with a
5769         // separate test. However, we only do this if this block doesn't
5770         // have a fall-through edge, because this requires an explicit
5771         // jmp when the condition is false.
5772         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5773             isX86LogicalCmp(Cmp) &&
5774             Op.getNode()->hasOneUse()) {
5775           X86::CondCode CCode =
5776             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5777           CCode = X86::GetOppositeBranchCondition(CCode);
5778           CC = DAG.getConstant(CCode, MVT::i8);
5779           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5780           // Look for an unconditional branch following this conditional branch.
5781           // We need this because we need to reverse the successors in order
5782           // to implement FCMP_OEQ.
5783           if (User.getOpcode() == ISD::BR) {
5784             SDValue FalseBB = User.getOperand(1);
5785             SDValue NewBR =
5786               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5787             assert(NewBR == User);
5788             Dest = FalseBB;
5789
5790             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5791                                 Chain, Dest, CC, Cmp);
5792             X86::CondCode CCode =
5793               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5794             CCode = X86::GetOppositeBranchCondition(CCode);
5795             CC = DAG.getConstant(CCode, MVT::i8);
5796             Cond = Cmp;
5797             addTest = false;
5798           }
5799         }
5800       }
5801     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5802       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5803       // It should be transformed during dag combiner except when the condition
5804       // is set by a arithmetics with overflow node.
5805       X86::CondCode CCode =
5806         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5807       CCode = X86::GetOppositeBranchCondition(CCode);
5808       CC = DAG.getConstant(CCode, MVT::i8);
5809       Cond = Cond.getOperand(0).getOperand(1);
5810       addTest = false;
5811     }
5812   }
5813
5814   if (addTest) {
5815     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5816     Cond = EmitTest(Cond, X86::COND_NE, DAG);
5817   }
5818   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5819                      Chain, Dest, CC, Cond);
5820 }
5821
5822
5823 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5824 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5825 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5826 // that the guard pages used by the OS virtual memory manager are allocated in
5827 // correct sequence.
5828 SDValue
5829 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5830                                            SelectionDAG &DAG) {
5831   assert(Subtarget->isTargetCygMing() &&
5832          "This should be used only on Cygwin/Mingw targets");
5833   DebugLoc dl = Op.getDebugLoc();
5834
5835   // Get the inputs.
5836   SDValue Chain = Op.getOperand(0);
5837   SDValue Size  = Op.getOperand(1);
5838   // FIXME: Ensure alignment here
5839
5840   SDValue Flag;
5841
5842   EVT IntPtr = getPointerTy();
5843   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5844
5845   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5846
5847   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5848   Flag = Chain.getValue(1);
5849
5850   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5851   SDValue Ops[] = { Chain,
5852                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
5853                       DAG.getRegister(X86::EAX, IntPtr),
5854                       DAG.getRegister(X86StackPtr, SPTy),
5855                       Flag };
5856   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5857   Flag = Chain.getValue(1);
5858
5859   Chain = DAG.getCALLSEQ_END(Chain,
5860                              DAG.getIntPtrConstant(0, true),
5861                              DAG.getIntPtrConstant(0, true),
5862                              Flag);
5863
5864   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5865
5866   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5867   return DAG.getMergeValues(Ops1, 2, dl);
5868 }
5869
5870 SDValue
5871 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5872                                            SDValue Chain,
5873                                            SDValue Dst, SDValue Src,
5874                                            SDValue Size, unsigned Align,
5875                                            const Value *DstSV,
5876                                            uint64_t DstSVOff) {
5877   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5878
5879   // If not DWORD aligned or size is more than the threshold, call the library.
5880   // The libc version is likely to be faster for these cases. It can use the
5881   // address value and run time information about the CPU.
5882   if ((Align & 3) != 0 ||
5883       !ConstantSize ||
5884       ConstantSize->getZExtValue() >
5885         getSubtarget()->getMaxInlineSizeThreshold()) {
5886     SDValue InFlag(0, 0);
5887
5888     // Check to see if there is a specialized entry-point for memory zeroing.
5889     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5890
5891     if (const char *bzeroEntry =  V &&
5892         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5893       EVT IntPtr = getPointerTy();
5894       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
5895       TargetLowering::ArgListTy Args;
5896       TargetLowering::ArgListEntry Entry;
5897       Entry.Node = Dst;
5898       Entry.Ty = IntPtrTy;
5899       Args.push_back(Entry);
5900       Entry.Node = Size;
5901       Args.push_back(Entry);
5902       std::pair<SDValue,SDValue> CallResult =
5903         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
5904                     false, false, false, false,
5905                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
5906                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5907       return CallResult.second;
5908     }
5909
5910     // Otherwise have the target-independent code call memset.
5911     return SDValue();
5912   }
5913
5914   uint64_t SizeVal = ConstantSize->getZExtValue();
5915   SDValue InFlag(0, 0);
5916   EVT AVT;
5917   SDValue Count;
5918   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5919   unsigned BytesLeft = 0;
5920   bool TwoRepStos = false;
5921   if (ValC) {
5922     unsigned ValReg;
5923     uint64_t Val = ValC->getZExtValue() & 255;
5924
5925     // If the value is a constant, then we can potentially use larger sets.
5926     switch (Align & 3) {
5927     case 2:   // WORD aligned
5928       AVT = MVT::i16;
5929       ValReg = X86::AX;
5930       Val = (Val << 8) | Val;
5931       break;
5932     case 0:  // DWORD aligned
5933       AVT = MVT::i32;
5934       ValReg = X86::EAX;
5935       Val = (Val << 8)  | Val;
5936       Val = (Val << 16) | Val;
5937       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5938         AVT = MVT::i64;
5939         ValReg = X86::RAX;
5940         Val = (Val << 32) | Val;
5941       }
5942       break;
5943     default:  // Byte aligned
5944       AVT = MVT::i8;
5945       ValReg = X86::AL;
5946       Count = DAG.getIntPtrConstant(SizeVal);
5947       break;
5948     }
5949
5950     if (AVT.bitsGT(MVT::i8)) {
5951       unsigned UBytes = AVT.getSizeInBits() / 8;
5952       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5953       BytesLeft = SizeVal % UBytes;
5954     }
5955
5956     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5957                               InFlag);
5958     InFlag = Chain.getValue(1);
5959   } else {
5960     AVT = MVT::i8;
5961     Count  = DAG.getIntPtrConstant(SizeVal);
5962     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5963     InFlag = Chain.getValue(1);
5964   }
5965
5966   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5967                                                               X86::ECX,
5968                             Count, InFlag);
5969   InFlag = Chain.getValue(1);
5970   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5971                                                               X86::EDI,
5972                             Dst, InFlag);
5973   InFlag = Chain.getValue(1);
5974
5975   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5976   SmallVector<SDValue, 8> Ops;
5977   Ops.push_back(Chain);
5978   Ops.push_back(DAG.getValueType(AVT));
5979   Ops.push_back(InFlag);
5980   Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5981
5982   if (TwoRepStos) {
5983     InFlag = Chain.getValue(1);
5984     Count  = Size;
5985     EVT CVT = Count.getValueType();
5986     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5987                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5988     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5989                                                              X86::ECX,
5990                               Left, InFlag);
5991     InFlag = Chain.getValue(1);
5992     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5993     Ops.clear();
5994     Ops.push_back(Chain);
5995     Ops.push_back(DAG.getValueType(MVT::i8));
5996     Ops.push_back(InFlag);
5997     Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5998   } else if (BytesLeft) {
5999     // Handle the last 1 - 7 bytes.
6000     unsigned Offset = SizeVal - BytesLeft;
6001     EVT AddrVT = Dst.getValueType();
6002     EVT SizeVT = Size.getValueType();
6003
6004     Chain = DAG.getMemset(Chain, dl,
6005                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6006                                       DAG.getConstant(Offset, AddrVT)),
6007                           Src,
6008                           DAG.getConstant(BytesLeft, SizeVT),
6009                           Align, DstSV, DstSVOff + Offset);
6010   }
6011
6012   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6013   return Chain;
6014 }
6015
6016 SDValue
6017 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6018                                       SDValue Chain, SDValue Dst, SDValue Src,
6019                                       SDValue Size, unsigned Align,
6020                                       bool AlwaysInline,
6021                                       const Value *DstSV, uint64_t DstSVOff,
6022                                       const Value *SrcSV, uint64_t SrcSVOff) {
6023   // This requires the copy size to be a constant, preferrably
6024   // within a subtarget-specific limit.
6025   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6026   if (!ConstantSize)
6027     return SDValue();
6028   uint64_t SizeVal = ConstantSize->getZExtValue();
6029   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6030     return SDValue();
6031
6032   /// If not DWORD aligned, call the library.
6033   if ((Align & 3) != 0)
6034     return SDValue();
6035
6036   // DWORD aligned
6037   EVT AVT = MVT::i32;
6038   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6039     AVT = MVT::i64;
6040
6041   unsigned UBytes = AVT.getSizeInBits() / 8;
6042   unsigned CountVal = SizeVal / UBytes;
6043   SDValue Count = DAG.getIntPtrConstant(CountVal);
6044   unsigned BytesLeft = SizeVal % UBytes;
6045
6046   SDValue InFlag(0, 0);
6047   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6048                                                               X86::ECX,
6049                             Count, InFlag);
6050   InFlag = Chain.getValue(1);
6051   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6052                                                              X86::EDI,
6053                             Dst, InFlag);
6054   InFlag = Chain.getValue(1);
6055   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6056                                                               X86::ESI,
6057                             Src, InFlag);
6058   InFlag = Chain.getValue(1);
6059
6060   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6061   SmallVector<SDValue, 8> Ops;
6062   Ops.push_back(Chain);
6063   Ops.push_back(DAG.getValueType(AVT));
6064   Ops.push_back(InFlag);
6065   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6066
6067   SmallVector<SDValue, 4> Results;
6068   Results.push_back(RepMovs);
6069   if (BytesLeft) {
6070     // Handle the last 1 - 7 bytes.
6071     unsigned Offset = SizeVal - BytesLeft;
6072     EVT DstVT = Dst.getValueType();
6073     EVT SrcVT = Src.getValueType();
6074     EVT SizeVT = Size.getValueType();
6075     Results.push_back(DAG.getMemcpy(Chain, dl,
6076                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6077                                                 DAG.getConstant(Offset, DstVT)),
6078                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6079                                                 DAG.getConstant(Offset, SrcVT)),
6080                                     DAG.getConstant(BytesLeft, SizeVT),
6081                                     Align, AlwaysInline,
6082                                     DstSV, DstSVOff + Offset,
6083                                     SrcSV, SrcSVOff + Offset));
6084   }
6085
6086   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6087                      &Results[0], Results.size());
6088 }
6089
6090 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6091   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6092   DebugLoc dl = Op.getDebugLoc();
6093
6094   if (!Subtarget->is64Bit()) {
6095     // vastart just stores the address of the VarArgsFrameIndex slot into the
6096     // memory location argument.
6097     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6098     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6099   }
6100
6101   // __va_list_tag:
6102   //   gp_offset         (0 - 6 * 8)
6103   //   fp_offset         (48 - 48 + 8 * 16)
6104   //   overflow_arg_area (point to parameters coming in memory).
6105   //   reg_save_area
6106   SmallVector<SDValue, 8> MemOps;
6107   SDValue FIN = Op.getOperand(1);
6108   // Store gp_offset
6109   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6110                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
6111                                  FIN, SV, 0);
6112   MemOps.push_back(Store);
6113
6114   // Store fp_offset
6115   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6116                     FIN, DAG.getIntPtrConstant(4));
6117   Store = DAG.getStore(Op.getOperand(0), dl,
6118                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6119                        FIN, SV, 0);
6120   MemOps.push_back(Store);
6121
6122   // Store ptr to overflow_arg_area
6123   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6124                     FIN, DAG.getIntPtrConstant(4));
6125   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6126   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6127   MemOps.push_back(Store);
6128
6129   // Store ptr to reg_save_area.
6130   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6131                     FIN, DAG.getIntPtrConstant(8));
6132   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6133   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6134   MemOps.push_back(Store);
6135   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6136                      &MemOps[0], MemOps.size());
6137 }
6138
6139 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6140   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6141   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6142   SDValue Chain = Op.getOperand(0);
6143   SDValue SrcPtr = Op.getOperand(1);
6144   SDValue SrcSV = Op.getOperand(2);
6145
6146   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6147   return SDValue();
6148 }
6149
6150 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6151   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6152   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6153   SDValue Chain = Op.getOperand(0);
6154   SDValue DstPtr = Op.getOperand(1);
6155   SDValue SrcPtr = Op.getOperand(2);
6156   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6157   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6158   DebugLoc dl = Op.getDebugLoc();
6159
6160   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6161                        DAG.getIntPtrConstant(24), 8, false,
6162                        DstSV, 0, SrcSV, 0);
6163 }
6164
6165 SDValue
6166 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6167   DebugLoc dl = Op.getDebugLoc();
6168   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6169   switch (IntNo) {
6170   default: return SDValue();    // Don't custom lower most intrinsics.
6171   // Comparison intrinsics.
6172   case Intrinsic::x86_sse_comieq_ss:
6173   case Intrinsic::x86_sse_comilt_ss:
6174   case Intrinsic::x86_sse_comile_ss:
6175   case Intrinsic::x86_sse_comigt_ss:
6176   case Intrinsic::x86_sse_comige_ss:
6177   case Intrinsic::x86_sse_comineq_ss:
6178   case Intrinsic::x86_sse_ucomieq_ss:
6179   case Intrinsic::x86_sse_ucomilt_ss:
6180   case Intrinsic::x86_sse_ucomile_ss:
6181   case Intrinsic::x86_sse_ucomigt_ss:
6182   case Intrinsic::x86_sse_ucomige_ss:
6183   case Intrinsic::x86_sse_ucomineq_ss:
6184   case Intrinsic::x86_sse2_comieq_sd:
6185   case Intrinsic::x86_sse2_comilt_sd:
6186   case Intrinsic::x86_sse2_comile_sd:
6187   case Intrinsic::x86_sse2_comigt_sd:
6188   case Intrinsic::x86_sse2_comige_sd:
6189   case Intrinsic::x86_sse2_comineq_sd:
6190   case Intrinsic::x86_sse2_ucomieq_sd:
6191   case Intrinsic::x86_sse2_ucomilt_sd:
6192   case Intrinsic::x86_sse2_ucomile_sd:
6193   case Intrinsic::x86_sse2_ucomigt_sd:
6194   case Intrinsic::x86_sse2_ucomige_sd:
6195   case Intrinsic::x86_sse2_ucomineq_sd: {
6196     unsigned Opc = 0;
6197     ISD::CondCode CC = ISD::SETCC_INVALID;
6198     switch (IntNo) {
6199     default: break;
6200     case Intrinsic::x86_sse_comieq_ss:
6201     case Intrinsic::x86_sse2_comieq_sd:
6202       Opc = X86ISD::COMI;
6203       CC = ISD::SETEQ;
6204       break;
6205     case Intrinsic::x86_sse_comilt_ss:
6206     case Intrinsic::x86_sse2_comilt_sd:
6207       Opc = X86ISD::COMI;
6208       CC = ISD::SETLT;
6209       break;
6210     case Intrinsic::x86_sse_comile_ss:
6211     case Intrinsic::x86_sse2_comile_sd:
6212       Opc = X86ISD::COMI;
6213       CC = ISD::SETLE;
6214       break;
6215     case Intrinsic::x86_sse_comigt_ss:
6216     case Intrinsic::x86_sse2_comigt_sd:
6217       Opc = X86ISD::COMI;
6218       CC = ISD::SETGT;
6219       break;
6220     case Intrinsic::x86_sse_comige_ss:
6221     case Intrinsic::x86_sse2_comige_sd:
6222       Opc = X86ISD::COMI;
6223       CC = ISD::SETGE;
6224       break;
6225     case Intrinsic::x86_sse_comineq_ss:
6226     case Intrinsic::x86_sse2_comineq_sd:
6227       Opc = X86ISD::COMI;
6228       CC = ISD::SETNE;
6229       break;
6230     case Intrinsic::x86_sse_ucomieq_ss:
6231     case Intrinsic::x86_sse2_ucomieq_sd:
6232       Opc = X86ISD::UCOMI;
6233       CC = ISD::SETEQ;
6234       break;
6235     case Intrinsic::x86_sse_ucomilt_ss:
6236     case Intrinsic::x86_sse2_ucomilt_sd:
6237       Opc = X86ISD::UCOMI;
6238       CC = ISD::SETLT;
6239       break;
6240     case Intrinsic::x86_sse_ucomile_ss:
6241     case Intrinsic::x86_sse2_ucomile_sd:
6242       Opc = X86ISD::UCOMI;
6243       CC = ISD::SETLE;
6244       break;
6245     case Intrinsic::x86_sse_ucomigt_ss:
6246     case Intrinsic::x86_sse2_ucomigt_sd:
6247       Opc = X86ISD::UCOMI;
6248       CC = ISD::SETGT;
6249       break;
6250     case Intrinsic::x86_sse_ucomige_ss:
6251     case Intrinsic::x86_sse2_ucomige_sd:
6252       Opc = X86ISD::UCOMI;
6253       CC = ISD::SETGE;
6254       break;
6255     case Intrinsic::x86_sse_ucomineq_ss:
6256     case Intrinsic::x86_sse2_ucomineq_sd:
6257       Opc = X86ISD::UCOMI;
6258       CC = ISD::SETNE;
6259       break;
6260     }
6261
6262     SDValue LHS = Op.getOperand(1);
6263     SDValue RHS = Op.getOperand(2);
6264     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6265     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6266     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6267                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6268     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6269   }
6270   // ptest intrinsics. The intrinsic these come from are designed to return
6271   // an integer value, not just an instruction so lower it to the ptest
6272   // pattern and a setcc for the result.
6273   case Intrinsic::x86_sse41_ptestz:
6274   case Intrinsic::x86_sse41_ptestc:
6275   case Intrinsic::x86_sse41_ptestnzc:{
6276     unsigned X86CC = 0;
6277     switch (IntNo) {
6278     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6279     case Intrinsic::x86_sse41_ptestz:
6280       // ZF = 1
6281       X86CC = X86::COND_E;
6282       break;
6283     case Intrinsic::x86_sse41_ptestc:
6284       // CF = 1
6285       X86CC = X86::COND_B;
6286       break;
6287     case Intrinsic::x86_sse41_ptestnzc:
6288       // ZF and CF = 0
6289       X86CC = X86::COND_A;
6290       break;
6291     }
6292
6293     SDValue LHS = Op.getOperand(1);
6294     SDValue RHS = Op.getOperand(2);
6295     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6296     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6297     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6298     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6299   }
6300
6301   // Fix vector shift instructions where the last operand is a non-immediate
6302   // i32 value.
6303   case Intrinsic::x86_sse2_pslli_w:
6304   case Intrinsic::x86_sse2_pslli_d:
6305   case Intrinsic::x86_sse2_pslli_q:
6306   case Intrinsic::x86_sse2_psrli_w:
6307   case Intrinsic::x86_sse2_psrli_d:
6308   case Intrinsic::x86_sse2_psrli_q:
6309   case Intrinsic::x86_sse2_psrai_w:
6310   case Intrinsic::x86_sse2_psrai_d:
6311   case Intrinsic::x86_mmx_pslli_w:
6312   case Intrinsic::x86_mmx_pslli_d:
6313   case Intrinsic::x86_mmx_pslli_q:
6314   case Intrinsic::x86_mmx_psrli_w:
6315   case Intrinsic::x86_mmx_psrli_d:
6316   case Intrinsic::x86_mmx_psrli_q:
6317   case Intrinsic::x86_mmx_psrai_w:
6318   case Intrinsic::x86_mmx_psrai_d: {
6319     SDValue ShAmt = Op.getOperand(2);
6320     if (isa<ConstantSDNode>(ShAmt))
6321       return SDValue();
6322
6323     unsigned NewIntNo = 0;
6324     EVT ShAmtVT = MVT::v4i32;
6325     switch (IntNo) {
6326     case Intrinsic::x86_sse2_pslli_w:
6327       NewIntNo = Intrinsic::x86_sse2_psll_w;
6328       break;
6329     case Intrinsic::x86_sse2_pslli_d:
6330       NewIntNo = Intrinsic::x86_sse2_psll_d;
6331       break;
6332     case Intrinsic::x86_sse2_pslli_q:
6333       NewIntNo = Intrinsic::x86_sse2_psll_q;
6334       break;
6335     case Intrinsic::x86_sse2_psrli_w:
6336       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6337       break;
6338     case Intrinsic::x86_sse2_psrli_d:
6339       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6340       break;
6341     case Intrinsic::x86_sse2_psrli_q:
6342       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6343       break;
6344     case Intrinsic::x86_sse2_psrai_w:
6345       NewIntNo = Intrinsic::x86_sse2_psra_w;
6346       break;
6347     case Intrinsic::x86_sse2_psrai_d:
6348       NewIntNo = Intrinsic::x86_sse2_psra_d;
6349       break;
6350     default: {
6351       ShAmtVT = MVT::v2i32;
6352       switch (IntNo) {
6353       case Intrinsic::x86_mmx_pslli_w:
6354         NewIntNo = Intrinsic::x86_mmx_psll_w;
6355         break;
6356       case Intrinsic::x86_mmx_pslli_d:
6357         NewIntNo = Intrinsic::x86_mmx_psll_d;
6358         break;
6359       case Intrinsic::x86_mmx_pslli_q:
6360         NewIntNo = Intrinsic::x86_mmx_psll_q;
6361         break;
6362       case Intrinsic::x86_mmx_psrli_w:
6363         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6364         break;
6365       case Intrinsic::x86_mmx_psrli_d:
6366         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6367         break;
6368       case Intrinsic::x86_mmx_psrli_q:
6369         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6370         break;
6371       case Intrinsic::x86_mmx_psrai_w:
6372         NewIntNo = Intrinsic::x86_mmx_psra_w;
6373         break;
6374       case Intrinsic::x86_mmx_psrai_d:
6375         NewIntNo = Intrinsic::x86_mmx_psra_d;
6376         break;
6377       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6378       }
6379       break;
6380     }
6381     }
6382     EVT VT = Op.getValueType();
6383     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6384                         DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6385     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6386                        DAG.getConstant(NewIntNo, MVT::i32),
6387                        Op.getOperand(1), ShAmt);
6388   }
6389   }
6390 }
6391
6392 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6393   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6394   DebugLoc dl = Op.getDebugLoc();
6395
6396   if (Depth > 0) {
6397     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6398     SDValue Offset =
6399       DAG.getConstant(TD->getPointerSize(),
6400                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6401     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6402                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6403                                    FrameAddr, Offset),
6404                        NULL, 0);
6405   }
6406
6407   // Just load the return address.
6408   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6409   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6410                      RetAddrFI, NULL, 0);
6411 }
6412
6413 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6414   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6415   MFI->setFrameAddressIsTaken(true);
6416   EVT VT = Op.getValueType();
6417   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6418   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6419   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6420   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6421   while (Depth--)
6422     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6423   return FrameAddr;
6424 }
6425
6426 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6427                                                      SelectionDAG &DAG) {
6428   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6429 }
6430
6431 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6432 {
6433   MachineFunction &MF = DAG.getMachineFunction();
6434   SDValue Chain     = Op.getOperand(0);
6435   SDValue Offset    = Op.getOperand(1);
6436   SDValue Handler   = Op.getOperand(2);
6437   DebugLoc dl       = Op.getDebugLoc();
6438
6439   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6440                                   getPointerTy());
6441   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6442
6443   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6444                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6445   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6446   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6447   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6448   MF.getRegInfo().addLiveOut(StoreAddrReg);
6449
6450   return DAG.getNode(X86ISD::EH_RETURN, dl,
6451                      MVT::Other,
6452                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6453 }
6454
6455 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6456                                              SelectionDAG &DAG) {
6457   SDValue Root = Op.getOperand(0);
6458   SDValue Trmp = Op.getOperand(1); // trampoline
6459   SDValue FPtr = Op.getOperand(2); // nested function
6460   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6461   DebugLoc dl  = Op.getDebugLoc();
6462
6463   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6464
6465   const X86InstrInfo *TII =
6466     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6467
6468   if (Subtarget->is64Bit()) {
6469     SDValue OutChains[6];
6470
6471     // Large code-model.
6472
6473     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6474     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6475
6476     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6477     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6478
6479     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6480
6481     // Load the pointer to the nested function into R11.
6482     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6483     SDValue Addr = Trmp;
6484     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6485                                 Addr, TrmpAddr, 0);
6486
6487     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6488                        DAG.getConstant(2, MVT::i64));
6489     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6490
6491     // Load the 'nest' parameter value into R10.
6492     // R10 is specified in X86CallingConv.td
6493     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6494     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6495                        DAG.getConstant(10, MVT::i64));
6496     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6497                                 Addr, TrmpAddr, 10);
6498
6499     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6500                        DAG.getConstant(12, MVT::i64));
6501     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6502
6503     // Jump to the nested function.
6504     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6505     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6506                        DAG.getConstant(20, MVT::i64));
6507     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6508                                 Addr, TrmpAddr, 20);
6509
6510     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6511     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6512                        DAG.getConstant(22, MVT::i64));
6513     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6514                                 TrmpAddr, 22);
6515
6516     SDValue Ops[] =
6517       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6518     return DAG.getMergeValues(Ops, 2, dl);
6519   } else {
6520     const Function *Func =
6521       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6522     unsigned CC = Func->getCallingConv();
6523     unsigned NestReg;
6524
6525     switch (CC) {
6526     default:
6527       llvm_unreachable("Unsupported calling convention");
6528     case CallingConv::C:
6529     case CallingConv::X86_StdCall: {
6530       // Pass 'nest' parameter in ECX.
6531       // Must be kept in sync with X86CallingConv.td
6532       NestReg = X86::ECX;
6533
6534       // Check that ECX wasn't needed by an 'inreg' parameter.
6535       const FunctionType *FTy = Func->getFunctionType();
6536       const AttrListPtr &Attrs = Func->getAttributes();
6537
6538       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6539         unsigned InRegCount = 0;
6540         unsigned Idx = 1;
6541
6542         for (FunctionType::param_iterator I = FTy->param_begin(),
6543              E = FTy->param_end(); I != E; ++I, ++Idx)
6544           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6545             // FIXME: should only count parameters that are lowered to integers.
6546             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6547
6548         if (InRegCount > 2) {
6549           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6550         }
6551       }
6552       break;
6553     }
6554     case CallingConv::X86_FastCall:
6555     case CallingConv::Fast:
6556       // Pass 'nest' parameter in EAX.
6557       // Must be kept in sync with X86CallingConv.td
6558       NestReg = X86::EAX;
6559       break;
6560     }
6561
6562     SDValue OutChains[4];
6563     SDValue Addr, Disp;
6564
6565     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6566                        DAG.getConstant(10, MVT::i32));
6567     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6568
6569     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6570     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6571     OutChains[0] = DAG.getStore(Root, dl,
6572                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6573                                 Trmp, TrmpAddr, 0);
6574
6575     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6576                        DAG.getConstant(1, MVT::i32));
6577     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6578
6579     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6580     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6581                        DAG.getConstant(5, MVT::i32));
6582     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6583                                 TrmpAddr, 5, false, 1);
6584
6585     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6586                        DAG.getConstant(6, MVT::i32));
6587     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6588
6589     SDValue Ops[] =
6590       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6591     return DAG.getMergeValues(Ops, 2, dl);
6592   }
6593 }
6594
6595 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6596   /*
6597    The rounding mode is in bits 11:10 of FPSR, and has the following
6598    settings:
6599      00 Round to nearest
6600      01 Round to -inf
6601      10 Round to +inf
6602      11 Round to 0
6603
6604   FLT_ROUNDS, on the other hand, expects the following:
6605     -1 Undefined
6606      0 Round to 0
6607      1 Round to nearest
6608      2 Round to +inf
6609      3 Round to -inf
6610
6611   To perform the conversion, we do:
6612     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6613   */
6614
6615   MachineFunction &MF = DAG.getMachineFunction();
6616   const TargetMachine &TM = MF.getTarget();
6617   const TargetFrameInfo &TFI = *TM.getFrameInfo();
6618   unsigned StackAlignment = TFI.getStackAlignment();
6619   EVT VT = Op.getValueType();
6620   DebugLoc dl = Op.getDebugLoc();
6621
6622   // Save FP Control Word to stack slot
6623   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6624   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6625
6626   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6627                               DAG.getEntryNode(), StackSlot);
6628
6629   // Load FP Control Word from stack slot
6630   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6631
6632   // Transform as necessary
6633   SDValue CWD1 =
6634     DAG.getNode(ISD::SRL, dl, MVT::i16,
6635                 DAG.getNode(ISD::AND, dl, MVT::i16,
6636                             CWD, DAG.getConstant(0x800, MVT::i16)),
6637                 DAG.getConstant(11, MVT::i8));
6638   SDValue CWD2 =
6639     DAG.getNode(ISD::SRL, dl, MVT::i16,
6640                 DAG.getNode(ISD::AND, dl, MVT::i16,
6641                             CWD, DAG.getConstant(0x400, MVT::i16)),
6642                 DAG.getConstant(9, MVT::i8));
6643
6644   SDValue RetVal =
6645     DAG.getNode(ISD::AND, dl, MVT::i16,
6646                 DAG.getNode(ISD::ADD, dl, MVT::i16,
6647                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6648                             DAG.getConstant(1, MVT::i16)),
6649                 DAG.getConstant(3, MVT::i16));
6650
6651
6652   return DAG.getNode((VT.getSizeInBits() < 16 ?
6653                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6654 }
6655
6656 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6657   EVT VT = Op.getValueType();
6658   EVT OpVT = VT;
6659   unsigned NumBits = VT.getSizeInBits();
6660   DebugLoc dl = Op.getDebugLoc();
6661
6662   Op = Op.getOperand(0);
6663   if (VT == MVT::i8) {
6664     // Zero extend to i32 since there is not an i8 bsr.
6665     OpVT = MVT::i32;
6666     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6667   }
6668
6669   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6670   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6671   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6672
6673   // If src is zero (i.e. bsr sets ZF), returns NumBits.
6674   SmallVector<SDValue, 4> Ops;
6675   Ops.push_back(Op);
6676   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6677   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6678   Ops.push_back(Op.getValue(1));
6679   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6680
6681   // Finally xor with NumBits-1.
6682   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6683
6684   if (VT == MVT::i8)
6685     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6686   return Op;
6687 }
6688
6689 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6690   EVT VT = Op.getValueType();
6691   EVT OpVT = VT;
6692   unsigned NumBits = VT.getSizeInBits();
6693   DebugLoc dl = Op.getDebugLoc();
6694
6695   Op = Op.getOperand(0);
6696   if (VT == MVT::i8) {
6697     OpVT = MVT::i32;
6698     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6699   }
6700
6701   // Issue a bsf (scan bits forward) which also sets EFLAGS.
6702   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6703   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6704
6705   // If src is zero (i.e. bsf sets ZF), returns NumBits.
6706   SmallVector<SDValue, 4> Ops;
6707   Ops.push_back(Op);
6708   Ops.push_back(DAG.getConstant(NumBits, OpVT));
6709   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6710   Ops.push_back(Op.getValue(1));
6711   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6712
6713   if (VT == MVT::i8)
6714     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6715   return Op;
6716 }
6717
6718 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6719   EVT VT = Op.getValueType();
6720   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6721   DebugLoc dl = Op.getDebugLoc();
6722
6723   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6724   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6725   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6726   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6727   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6728   //
6729   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6730   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6731   //  return AloBlo + AloBhi + AhiBlo;
6732
6733   SDValue A = Op.getOperand(0);
6734   SDValue B = Op.getOperand(1);
6735
6736   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6737                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6738                        A, DAG.getConstant(32, MVT::i32));
6739   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6740                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6741                        B, DAG.getConstant(32, MVT::i32));
6742   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6743                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6744                        A, B);
6745   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6746                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6747                        A, Bhi);
6748   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6749                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6750                        Ahi, B);
6751   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6752                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6753                        AloBhi, DAG.getConstant(32, MVT::i32));
6754   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6755                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6756                        AhiBlo, DAG.getConstant(32, MVT::i32));
6757   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6758   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6759   return Res;
6760 }
6761
6762
6763 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6764   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6765   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6766   // looks for this combo and may remove the "setcc" instruction if the "setcc"
6767   // has only one use.
6768   SDNode *N = Op.getNode();
6769   SDValue LHS = N->getOperand(0);
6770   SDValue RHS = N->getOperand(1);
6771   unsigned BaseOp = 0;
6772   unsigned Cond = 0;
6773   DebugLoc dl = Op.getDebugLoc();
6774
6775   switch (Op.getOpcode()) {
6776   default: llvm_unreachable("Unknown ovf instruction!");
6777   case ISD::SADDO:
6778     // A subtract of one will be selected as a INC. Note that INC doesn't
6779     // set CF, so we can't do this for UADDO.
6780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6781       if (C->getAPIntValue() == 1) {
6782         BaseOp = X86ISD::INC;
6783         Cond = X86::COND_O;
6784         break;
6785       }
6786     BaseOp = X86ISD::ADD;
6787     Cond = X86::COND_O;
6788     break;
6789   case ISD::UADDO:
6790     BaseOp = X86ISD::ADD;
6791     Cond = X86::COND_B;
6792     break;
6793   case ISD::SSUBO:
6794     // A subtract of one will be selected as a DEC. Note that DEC doesn't
6795     // set CF, so we can't do this for USUBO.
6796     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6797       if (C->getAPIntValue() == 1) {
6798         BaseOp = X86ISD::DEC;
6799         Cond = X86::COND_O;
6800         break;
6801       }
6802     BaseOp = X86ISD::SUB;
6803     Cond = X86::COND_O;
6804     break;
6805   case ISD::USUBO:
6806     BaseOp = X86ISD::SUB;
6807     Cond = X86::COND_B;
6808     break;
6809   case ISD::SMULO:
6810     BaseOp = X86ISD::SMUL;
6811     Cond = X86::COND_O;
6812     break;
6813   case ISD::UMULO:
6814     BaseOp = X86ISD::UMUL;
6815     Cond = X86::COND_B;
6816     break;
6817   }
6818
6819   // Also sets EFLAGS.
6820   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6821   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6822
6823   SDValue SetCC =
6824     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6825                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6826
6827   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6828   return Sum;
6829 }
6830
6831 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6832   EVT T = Op.getValueType();
6833   DebugLoc dl = Op.getDebugLoc();
6834   unsigned Reg = 0;
6835   unsigned size = 0;
6836   switch(T.getSimpleVT().SimpleTy) {
6837   default:
6838     assert(false && "Invalid value type!");
6839   case MVT::i8:  Reg = X86::AL;  size = 1; break;
6840   case MVT::i16: Reg = X86::AX;  size = 2; break;
6841   case MVT::i32: Reg = X86::EAX; size = 4; break;
6842   case MVT::i64:
6843     assert(Subtarget->is64Bit() && "Node not type legal!");
6844     Reg = X86::RAX; size = 8;
6845     break;
6846   }
6847   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6848                                     Op.getOperand(2), SDValue());
6849   SDValue Ops[] = { cpIn.getValue(0),
6850                     Op.getOperand(1),
6851                     Op.getOperand(3),
6852                     DAG.getTargetConstant(size, MVT::i8),
6853                     cpIn.getValue(1) };
6854   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6855   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6856   SDValue cpOut =
6857     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6858   return cpOut;
6859 }
6860
6861 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6862                                                  SelectionDAG &DAG) {
6863   assert(Subtarget->is64Bit() && "Result not type legalized?");
6864   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6865   SDValue TheChain = Op.getOperand(0);
6866   DebugLoc dl = Op.getDebugLoc();
6867   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6868   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6869   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6870                                    rax.getValue(2));
6871   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6872                             DAG.getConstant(32, MVT::i8));
6873   SDValue Ops[] = {
6874     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6875     rdx.getValue(1)
6876   };
6877   return DAG.getMergeValues(Ops, 2, dl);
6878 }
6879
6880 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6881   SDNode *Node = Op.getNode();
6882   DebugLoc dl = Node->getDebugLoc();
6883   EVT T = Node->getValueType(0);
6884   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6885                               DAG.getConstant(0, T), Node->getOperand(2));
6886   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6887                        cast<AtomicSDNode>(Node)->getMemoryVT(),
6888                        Node->getOperand(0),
6889                        Node->getOperand(1), negOp,
6890                        cast<AtomicSDNode>(Node)->getSrcValue(),
6891                        cast<AtomicSDNode>(Node)->getAlignment());
6892 }
6893
6894 /// LowerOperation - Provide custom lowering hooks for some operations.
6895 ///
6896 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6897   switch (Op.getOpcode()) {
6898   default: llvm_unreachable("Should not custom lower this!");
6899   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
6900   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
6901   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6902   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6903   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6904   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
6905   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6906   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6907   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6908   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6909   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
6910   case ISD::SHL_PARTS:
6911   case ISD::SRA_PARTS:
6912   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
6913   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
6914   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
6915   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
6916   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
6917   case ISD::FABS:               return LowerFABS(Op, DAG);
6918   case ISD::FNEG:               return LowerFNEG(Op, DAG);
6919   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
6920   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6921   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
6922   case ISD::SELECT:             return LowerSELECT(Op, DAG);
6923   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
6924   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6925   case ISD::VASTART:            return LowerVASTART(Op, DAG);
6926   case ISD::VAARG:              return LowerVAARG(Op, DAG);
6927   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
6928   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6929   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6930   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6931   case ISD::FRAME_TO_ARGS_OFFSET:
6932                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6933   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6934   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6935   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6936   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6937   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6938   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6939   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
6940   case ISD::SADDO:
6941   case ISD::UADDO:
6942   case ISD::SSUBO:
6943   case ISD::USUBO:
6944   case ISD::SMULO:
6945   case ISD::UMULO:              return LowerXALUO(Op, DAG);
6946   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
6947   }
6948 }
6949
6950 void X86TargetLowering::
6951 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6952                         SelectionDAG &DAG, unsigned NewOp) {
6953   EVT T = Node->getValueType(0);
6954   DebugLoc dl = Node->getDebugLoc();
6955   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6956
6957   SDValue Chain = Node->getOperand(0);
6958   SDValue In1 = Node->getOperand(1);
6959   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6960                              Node->getOperand(2), DAG.getIntPtrConstant(0));
6961   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6962                              Node->getOperand(2), DAG.getIntPtrConstant(1));
6963   // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6964   // have a MemOperand.  Pass the info through as a normal operand.
6965   SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6966   SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6967   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6968   SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6969   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6970   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6971   Results.push_back(Result.getValue(2));
6972 }
6973
6974 /// ReplaceNodeResults - Replace a node with an illegal result type
6975 /// with a new node built out of custom code.
6976 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6977                                            SmallVectorImpl<SDValue>&Results,
6978                                            SelectionDAG &DAG) {
6979   DebugLoc dl = N->getDebugLoc();
6980   switch (N->getOpcode()) {
6981   default:
6982     assert(false && "Do not know how to custom type legalize this operation!");
6983     return;
6984   case ISD::FP_TO_SINT: {
6985     std::pair<SDValue,SDValue> Vals =
6986         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6987     SDValue FIST = Vals.first, StackSlot = Vals.second;
6988     if (FIST.getNode() != 0) {
6989       EVT VT = N->getValueType(0);
6990       // Return a load from the stack slot.
6991       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6992     }
6993     return;
6994   }
6995   case ISD::READCYCLECOUNTER: {
6996     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6997     SDValue TheChain = N->getOperand(0);
6998     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6999     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7000                                      rd.getValue(1));
7001     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7002                                      eax.getValue(2));
7003     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7004     SDValue Ops[] = { eax, edx };
7005     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7006     Results.push_back(edx.getValue(1));
7007     return;
7008   }
7009   case ISD::ATOMIC_CMP_SWAP: {
7010     EVT T = N->getValueType(0);
7011     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7012     SDValue cpInL, cpInH;
7013     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7014                         DAG.getConstant(0, MVT::i32));
7015     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7016                         DAG.getConstant(1, MVT::i32));
7017     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7018     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7019                              cpInL.getValue(1));
7020     SDValue swapInL, swapInH;
7021     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7022                           DAG.getConstant(0, MVT::i32));
7023     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7024                           DAG.getConstant(1, MVT::i32));
7025     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7026                                cpInH.getValue(1));
7027     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7028                                swapInL.getValue(1));
7029     SDValue Ops[] = { swapInH.getValue(0),
7030                       N->getOperand(1),
7031                       swapInH.getValue(1) };
7032     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7033     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7034     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7035                                         MVT::i32, Result.getValue(1));
7036     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7037                                         MVT::i32, cpOutL.getValue(2));
7038     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7039     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7040     Results.push_back(cpOutH.getValue(1));
7041     return;
7042   }
7043   case ISD::ATOMIC_LOAD_ADD:
7044     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7045     return;
7046   case ISD::ATOMIC_LOAD_AND:
7047     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7048     return;
7049   case ISD::ATOMIC_LOAD_NAND:
7050     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7051     return;
7052   case ISD::ATOMIC_LOAD_OR:
7053     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7054     return;
7055   case ISD::ATOMIC_LOAD_SUB:
7056     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7057     return;
7058   case ISD::ATOMIC_LOAD_XOR:
7059     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7060     return;
7061   case ISD::ATOMIC_SWAP:
7062     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7063     return;
7064   }
7065 }
7066
7067 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7068   switch (Opcode) {
7069   default: return NULL;
7070   case X86ISD::BSF:                return "X86ISD::BSF";
7071   case X86ISD::BSR:                return "X86ISD::BSR";
7072   case X86ISD::SHLD:               return "X86ISD::SHLD";
7073   case X86ISD::SHRD:               return "X86ISD::SHRD";
7074   case X86ISD::FAND:               return "X86ISD::FAND";
7075   case X86ISD::FOR:                return "X86ISD::FOR";
7076   case X86ISD::FXOR:               return "X86ISD::FXOR";
7077   case X86ISD::FSRL:               return "X86ISD::FSRL";
7078   case X86ISD::FILD:               return "X86ISD::FILD";
7079   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7080   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7081   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7082   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7083   case X86ISD::FLD:                return "X86ISD::FLD";
7084   case X86ISD::FST:                return "X86ISD::FST";
7085   case X86ISD::CALL:               return "X86ISD::CALL";
7086   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7087   case X86ISD::BT:                 return "X86ISD::BT";
7088   case X86ISD::CMP:                return "X86ISD::CMP";
7089   case X86ISD::COMI:               return "X86ISD::COMI";
7090   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7091   case X86ISD::SETCC:              return "X86ISD::SETCC";
7092   case X86ISD::CMOV:               return "X86ISD::CMOV";
7093   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7094   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7095   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7096   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7097   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7098   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7099   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7100   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7101   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7102   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7103   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7104   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7105   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7106   case X86ISD::FMAX:               return "X86ISD::FMAX";
7107   case X86ISD::FMIN:               return "X86ISD::FMIN";
7108   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7109   case X86ISD::FRCP:               return "X86ISD::FRCP";
7110   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7111   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7112   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7113   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7114   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7115   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7116   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7117   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7118   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7119   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7120   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7121   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7122   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7123   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7124   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7125   case X86ISD::VSHL:               return "X86ISD::VSHL";
7126   case X86ISD::VSRL:               return "X86ISD::VSRL";
7127   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7128   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7129   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7130   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7131   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7132   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7133   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7134   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7135   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7136   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7137   case X86ISD::ADD:                return "X86ISD::ADD";
7138   case X86ISD::SUB:                return "X86ISD::SUB";
7139   case X86ISD::SMUL:               return "X86ISD::SMUL";
7140   case X86ISD::UMUL:               return "X86ISD::UMUL";
7141   case X86ISD::INC:                return "X86ISD::INC";
7142   case X86ISD::DEC:                return "X86ISD::DEC";
7143   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7144   case X86ISD::PTEST:              return "X86ISD::PTEST";
7145   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7146   }
7147 }
7148
7149 // isLegalAddressingMode - Return true if the addressing mode represented
7150 // by AM is legal for this target, for a load/store of the specified type.
7151 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7152                                               const Type *Ty) const {
7153   // X86 supports extremely general addressing modes.
7154   CodeModel::Model M = getTargetMachine().getCodeModel();
7155
7156   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7157   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7158     return false;
7159
7160   if (AM.BaseGV) {
7161     unsigned GVFlags =
7162       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7163
7164     // If a reference to this global requires an extra load, we can't fold it.
7165     if (isGlobalStubReference(GVFlags))
7166       return false;
7167
7168     // If BaseGV requires a register for the PIC base, we cannot also have a
7169     // BaseReg specified.
7170     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7171       return false;
7172
7173     // If lower 4G is not available, then we must use rip-relative addressing.
7174     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7175       return false;
7176   }
7177
7178   switch (AM.Scale) {
7179   case 0:
7180   case 1:
7181   case 2:
7182   case 4:
7183   case 8:
7184     // These scales always work.
7185     break;
7186   case 3:
7187   case 5:
7188   case 9:
7189     // These scales are formed with basereg+scalereg.  Only accept if there is
7190     // no basereg yet.
7191     if (AM.HasBaseReg)
7192       return false;
7193     break;
7194   default:  // Other stuff never works.
7195     return false;
7196   }
7197
7198   return true;
7199 }
7200
7201
7202 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7203   if (!Ty1->isInteger() || !Ty2->isInteger())
7204     return false;
7205   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7206   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7207   if (NumBits1 <= NumBits2)
7208     return false;
7209   return Subtarget->is64Bit() || NumBits1 < 64;
7210 }
7211
7212 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7213   if (!VT1.isInteger() || !VT2.isInteger())
7214     return false;
7215   unsigned NumBits1 = VT1.getSizeInBits();
7216   unsigned NumBits2 = VT2.getSizeInBits();
7217   if (NumBits1 <= NumBits2)
7218     return false;
7219   return Subtarget->is64Bit() || NumBits1 < 64;
7220 }
7221
7222 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7223   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7224   return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7225          Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7226 }
7227
7228 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7229   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7230   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7231 }
7232
7233 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7234   // i16 instructions are longer (0x66 prefix) and potentially slower.
7235   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7236 }
7237
7238 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7239 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7240 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7241 /// are assumed to be legal.
7242 bool
7243 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7244                                       EVT VT) const {
7245   // Only do shuffles on 128-bit vector types for now.
7246   if (VT.getSizeInBits() == 64)
7247     return false;
7248
7249   // FIXME: pshufb, blends, palignr, shifts.
7250   return (VT.getVectorNumElements() == 2 ||
7251           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7252           isMOVLMask(M, VT) ||
7253           isSHUFPMask(M, VT) ||
7254           isPSHUFDMask(M, VT) ||
7255           isPSHUFHWMask(M, VT) ||
7256           isPSHUFLWMask(M, VT) ||
7257           isUNPCKLMask(M, VT) ||
7258           isUNPCKHMask(M, VT) ||
7259           isUNPCKL_v_undef_Mask(M, VT) ||
7260           isUNPCKH_v_undef_Mask(M, VT));
7261 }
7262
7263 bool
7264 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7265                                           EVT VT) const {
7266   unsigned NumElts = VT.getVectorNumElements();
7267   // FIXME: This collection of masks seems suspect.
7268   if (NumElts == 2)
7269     return true;
7270   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7271     return (isMOVLMask(Mask, VT)  ||
7272             isCommutedMOVLMask(Mask, VT, true) ||
7273             isSHUFPMask(Mask, VT) ||
7274             isCommutedSHUFPMask(Mask, VT));
7275   }
7276   return false;
7277 }
7278
7279 //===----------------------------------------------------------------------===//
7280 //                           X86 Scheduler Hooks
7281 //===----------------------------------------------------------------------===//
7282
7283 // private utility function
7284 MachineBasicBlock *
7285 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7286                                                        MachineBasicBlock *MBB,
7287                                                        unsigned regOpc,
7288                                                        unsigned immOpc,
7289                                                        unsigned LoadOpc,
7290                                                        unsigned CXchgOpc,
7291                                                        unsigned copyOpc,
7292                                                        unsigned notOpc,
7293                                                        unsigned EAXreg,
7294                                                        TargetRegisterClass *RC,
7295                                                        bool invSrc) const {
7296   // For the atomic bitwise operator, we generate
7297   //   thisMBB:
7298   //   newMBB:
7299   //     ld  t1 = [bitinstr.addr]
7300   //     op  t2 = t1, [bitinstr.val]
7301   //     mov EAX = t1
7302   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7303   //     bz  newMBB
7304   //     fallthrough -->nextMBB
7305   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7306   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7307   MachineFunction::iterator MBBIter = MBB;
7308   ++MBBIter;
7309
7310   /// First build the CFG
7311   MachineFunction *F = MBB->getParent();
7312   MachineBasicBlock *thisMBB = MBB;
7313   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7314   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7315   F->insert(MBBIter, newMBB);
7316   F->insert(MBBIter, nextMBB);
7317
7318   // Move all successors to thisMBB to nextMBB
7319   nextMBB->transferSuccessors(thisMBB);
7320
7321   // Update thisMBB to fall through to newMBB
7322   thisMBB->addSuccessor(newMBB);
7323
7324   // newMBB jumps to itself and fall through to nextMBB
7325   newMBB->addSuccessor(nextMBB);
7326   newMBB->addSuccessor(newMBB);
7327
7328   // Insert instructions into newMBB based on incoming instruction
7329   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7330          "unexpected number of operands");
7331   DebugLoc dl = bInstr->getDebugLoc();
7332   MachineOperand& destOper = bInstr->getOperand(0);
7333   MachineOperand* argOpers[2 + X86AddrNumOperands];
7334   int numArgs = bInstr->getNumOperands() - 1;
7335   for (int i=0; i < numArgs; ++i)
7336     argOpers[i] = &bInstr->getOperand(i+1);
7337
7338   // x86 address has 4 operands: base, index, scale, and displacement
7339   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7340   int valArgIndx = lastAddrIndx + 1;
7341
7342   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7343   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7344   for (int i=0; i <= lastAddrIndx; ++i)
7345     (*MIB).addOperand(*argOpers[i]);
7346
7347   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7348   if (invSrc) {
7349     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7350   }
7351   else
7352     tt = t1;
7353
7354   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7355   assert((argOpers[valArgIndx]->isReg() ||
7356           argOpers[valArgIndx]->isImm()) &&
7357          "invalid operand");
7358   if (argOpers[valArgIndx]->isReg())
7359     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7360   else
7361     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7362   MIB.addReg(tt);
7363   (*MIB).addOperand(*argOpers[valArgIndx]);
7364
7365   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7366   MIB.addReg(t1);
7367
7368   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7369   for (int i=0; i <= lastAddrIndx; ++i)
7370     (*MIB).addOperand(*argOpers[i]);
7371   MIB.addReg(t2);
7372   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7373   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7374
7375   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7376   MIB.addReg(EAXreg);
7377
7378   // insert branch
7379   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7380
7381   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7382   return nextMBB;
7383 }
7384
7385 // private utility function:  64 bit atomics on 32 bit host.
7386 MachineBasicBlock *
7387 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7388                                                        MachineBasicBlock *MBB,
7389                                                        unsigned regOpcL,
7390                                                        unsigned regOpcH,
7391                                                        unsigned immOpcL,
7392                                                        unsigned immOpcH,
7393                                                        bool invSrc) const {
7394   // For the atomic bitwise operator, we generate
7395   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7396   //     ld t1,t2 = [bitinstr.addr]
7397   //   newMBB:
7398   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7399   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7400   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7401   //     mov ECX, EBX <- t5, t6
7402   //     mov EAX, EDX <- t1, t2
7403   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7404   //     mov t3, t4 <- EAX, EDX
7405   //     bz  newMBB
7406   //     result in out1, out2
7407   //     fallthrough -->nextMBB
7408
7409   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7410   const unsigned LoadOpc = X86::MOV32rm;
7411   const unsigned copyOpc = X86::MOV32rr;
7412   const unsigned NotOpc = X86::NOT32r;
7413   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7414   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7415   MachineFunction::iterator MBBIter = MBB;
7416   ++MBBIter;
7417
7418   /// First build the CFG
7419   MachineFunction *F = MBB->getParent();
7420   MachineBasicBlock *thisMBB = MBB;
7421   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7422   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7423   F->insert(MBBIter, newMBB);
7424   F->insert(MBBIter, nextMBB);
7425
7426   // Move all successors to thisMBB to nextMBB
7427   nextMBB->transferSuccessors(thisMBB);
7428
7429   // Update thisMBB to fall through to newMBB
7430   thisMBB->addSuccessor(newMBB);
7431
7432   // newMBB jumps to itself and fall through to nextMBB
7433   newMBB->addSuccessor(nextMBB);
7434   newMBB->addSuccessor(newMBB);
7435
7436   DebugLoc dl = bInstr->getDebugLoc();
7437   // Insert instructions into newMBB based on incoming instruction
7438   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7439   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7440          "unexpected number of operands");
7441   MachineOperand& dest1Oper = bInstr->getOperand(0);
7442   MachineOperand& dest2Oper = bInstr->getOperand(1);
7443   MachineOperand* argOpers[2 + X86AddrNumOperands];
7444   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7445     argOpers[i] = &bInstr->getOperand(i+2);
7446
7447   // x86 address has 4 operands: base, index, scale, and displacement
7448   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7449
7450   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7451   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7452   for (int i=0; i <= lastAddrIndx; ++i)
7453     (*MIB).addOperand(*argOpers[i]);
7454   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7455   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7456   // add 4 to displacement.
7457   for (int i=0; i <= lastAddrIndx-2; ++i)
7458     (*MIB).addOperand(*argOpers[i]);
7459   MachineOperand newOp3 = *(argOpers[3]);
7460   if (newOp3.isImm())
7461     newOp3.setImm(newOp3.getImm()+4);
7462   else
7463     newOp3.setOffset(newOp3.getOffset()+4);
7464   (*MIB).addOperand(newOp3);
7465   (*MIB).addOperand(*argOpers[lastAddrIndx]);
7466
7467   // t3/4 are defined later, at the bottom of the loop
7468   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7469   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7470   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7471     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7472   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7473     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7474
7475   unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7476   unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7477   if (invSrc) {
7478     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7479     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7480   } else {
7481     tt1 = t1;
7482     tt2 = t2;
7483   }
7484
7485   int valArgIndx = lastAddrIndx + 1;
7486   assert((argOpers[valArgIndx]->isReg() ||
7487           argOpers[valArgIndx]->isImm()) &&
7488          "invalid operand");
7489   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7490   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7491   if (argOpers[valArgIndx]->isReg())
7492     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7493   else
7494     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7495   if (regOpcL != X86::MOV32rr)
7496     MIB.addReg(tt1);
7497   (*MIB).addOperand(*argOpers[valArgIndx]);
7498   assert(argOpers[valArgIndx + 1]->isReg() ==
7499          argOpers[valArgIndx]->isReg());
7500   assert(argOpers[valArgIndx + 1]->isImm() ==
7501          argOpers[valArgIndx]->isImm());
7502   if (argOpers[valArgIndx + 1]->isReg())
7503     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7504   else
7505     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7506   if (regOpcH != X86::MOV32rr)
7507     MIB.addReg(tt2);
7508   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7509
7510   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7511   MIB.addReg(t1);
7512   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7513   MIB.addReg(t2);
7514
7515   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7516   MIB.addReg(t5);
7517   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7518   MIB.addReg(t6);
7519
7520   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7521   for (int i=0; i <= lastAddrIndx; ++i)
7522     (*MIB).addOperand(*argOpers[i]);
7523
7524   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7525   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7526
7527   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7528   MIB.addReg(X86::EAX);
7529   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7530   MIB.addReg(X86::EDX);
7531
7532   // insert branch
7533   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7534
7535   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7536   return nextMBB;
7537 }
7538
7539 // private utility function
7540 MachineBasicBlock *
7541 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7542                                                       MachineBasicBlock *MBB,
7543                                                       unsigned cmovOpc) const {
7544   // For the atomic min/max operator, we generate
7545   //   thisMBB:
7546   //   newMBB:
7547   //     ld t1 = [min/max.addr]
7548   //     mov t2 = [min/max.val]
7549   //     cmp  t1, t2
7550   //     cmov[cond] t2 = t1
7551   //     mov EAX = t1
7552   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7553   //     bz   newMBB
7554   //     fallthrough -->nextMBB
7555   //
7556   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7557   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7558   MachineFunction::iterator MBBIter = MBB;
7559   ++MBBIter;
7560
7561   /// First build the CFG
7562   MachineFunction *F = MBB->getParent();
7563   MachineBasicBlock *thisMBB = MBB;
7564   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7565   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7566   F->insert(MBBIter, newMBB);
7567   F->insert(MBBIter, nextMBB);
7568
7569   // Move all successors of thisMBB to nextMBB
7570   nextMBB->transferSuccessors(thisMBB);
7571
7572   // Update thisMBB to fall through to newMBB
7573   thisMBB->addSuccessor(newMBB);
7574
7575   // newMBB jumps to newMBB and fall through to nextMBB
7576   newMBB->addSuccessor(nextMBB);
7577   newMBB->addSuccessor(newMBB);
7578
7579   DebugLoc dl = mInstr->getDebugLoc();
7580   // Insert instructions into newMBB based on incoming instruction
7581   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7582          "unexpected number of operands");
7583   MachineOperand& destOper = mInstr->getOperand(0);
7584   MachineOperand* argOpers[2 + X86AddrNumOperands];
7585   int numArgs = mInstr->getNumOperands() - 1;
7586   for (int i=0; i < numArgs; ++i)
7587     argOpers[i] = &mInstr->getOperand(i+1);
7588
7589   // x86 address has 4 operands: base, index, scale, and displacement
7590   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7591   int valArgIndx = lastAddrIndx + 1;
7592
7593   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7594   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7595   for (int i=0; i <= lastAddrIndx; ++i)
7596     (*MIB).addOperand(*argOpers[i]);
7597
7598   // We only support register and immediate values
7599   assert((argOpers[valArgIndx]->isReg() ||
7600           argOpers[valArgIndx]->isImm()) &&
7601          "invalid operand");
7602
7603   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7604   if (argOpers[valArgIndx]->isReg())
7605     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7606   else
7607     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7608   (*MIB).addOperand(*argOpers[valArgIndx]);
7609
7610   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7611   MIB.addReg(t1);
7612
7613   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7614   MIB.addReg(t1);
7615   MIB.addReg(t2);
7616
7617   // Generate movc
7618   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7619   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7620   MIB.addReg(t2);
7621   MIB.addReg(t1);
7622
7623   // Cmp and exchange if none has modified the memory location
7624   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7625   for (int i=0; i <= lastAddrIndx; ++i)
7626     (*MIB).addOperand(*argOpers[i]);
7627   MIB.addReg(t3);
7628   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7629   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7630
7631   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7632   MIB.addReg(X86::EAX);
7633
7634   // insert branch
7635   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7636
7637   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
7638   return nextMBB;
7639 }
7640
7641 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
7642 // all of this code can be replaced with that in the .td file.
7643 MachineBasicBlock *
7644 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
7645                             unsigned numArgs, bool memArg) const {
7646
7647   MachineFunction *F = BB->getParent();
7648   DebugLoc dl = MI->getDebugLoc();
7649   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7650
7651   unsigned Opc;
7652
7653   if (memArg) {
7654     Opc = numArgs == 3 ?
7655       X86::PCMPISTRM128rm :
7656       X86::PCMPESTRM128rm;
7657   } else {
7658     Opc = numArgs == 3 ?
7659       X86::PCMPISTRM128rr :
7660       X86::PCMPESTRM128rr;
7661   }
7662
7663   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
7664
7665   for (unsigned i = 0; i < numArgs; ++i) {
7666     MachineOperand &Op = MI->getOperand(i+1);
7667
7668     if (!(Op.isReg() && Op.isImplicit()))
7669       MIB.addOperand(Op);
7670   }
7671
7672   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
7673     .addReg(X86::XMM0);
7674
7675   F->DeleteMachineInstr(MI);
7676
7677   return BB;
7678 }
7679
7680 MachineBasicBlock *
7681 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7682                                                  MachineInstr *MI,
7683                                                  MachineBasicBlock *MBB) const {
7684   // Emit code to save XMM registers to the stack. The ABI says that the
7685   // number of registers to save is given in %al, so it's theoretically
7686   // possible to do an indirect jump trick to avoid saving all of them,
7687   // however this code takes a simpler approach and just executes all
7688   // of the stores if %al is non-zero. It's less code, and it's probably
7689   // easier on the hardware branch predictor, and stores aren't all that
7690   // expensive anyway.
7691
7692   // Create the new basic blocks. One block contains all the XMM stores,
7693   // and one block is the final destination regardless of whether any
7694   // stores were performed.
7695   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7696   MachineFunction *F = MBB->getParent();
7697   MachineFunction::iterator MBBIter = MBB;
7698   ++MBBIter;
7699   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7700   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7701   F->insert(MBBIter, XMMSaveMBB);
7702   F->insert(MBBIter, EndMBB);
7703
7704   // Set up the CFG.
7705   // Move any original successors of MBB to the end block.
7706   EndMBB->transferSuccessors(MBB);
7707   // The original block will now fall through to the XMM save block.
7708   MBB->addSuccessor(XMMSaveMBB);
7709   // The XMMSaveMBB will fall through to the end block.
7710   XMMSaveMBB->addSuccessor(EndMBB);
7711
7712   // Now add the instructions.
7713   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7714   DebugLoc DL = MI->getDebugLoc();
7715
7716   unsigned CountReg = MI->getOperand(0).getReg();
7717   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7718   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7719
7720   if (!Subtarget->isTargetWin64()) {
7721     // If %al is 0, branch around the XMM save block.
7722     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
7723     BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
7724     MBB->addSuccessor(EndMBB);
7725   }
7726
7727   // In the XMM save block, save all the XMM argument registers.
7728   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
7729     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
7730     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
7731       .addFrameIndex(RegSaveFrameIndex)
7732       .addImm(/*Scale=*/1)
7733       .addReg(/*IndexReg=*/0)
7734       .addImm(/*Disp=*/Offset)
7735       .addReg(/*Segment=*/0)
7736       .addReg(MI->getOperand(i).getReg())
7737       .addMemOperand(MachineMemOperand(
7738                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
7739                        MachineMemOperand::MOStore, Offset,
7740                        /*Size=*/16, /*Align=*/16));
7741   }
7742
7743   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7744
7745   return EndMBB;
7746 }
7747
7748 MachineBasicBlock *
7749 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7750                                                MachineBasicBlock *BB) const {
7751   DebugLoc dl = MI->getDebugLoc();
7752   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7753   switch (MI->getOpcode()) {
7754   default: assert(false && "Unexpected instr type to insert");
7755   case X86::CMOV_GR8:
7756   case X86::CMOV_V1I64:
7757   case X86::CMOV_FR32:
7758   case X86::CMOV_FR64:
7759   case X86::CMOV_V4F32:
7760   case X86::CMOV_V2F64:
7761   case X86::CMOV_V2I64: {
7762     // To "insert" a SELECT_CC instruction, we actually have to insert the
7763     // diamond control-flow pattern.  The incoming instruction knows the
7764     // destination vreg to set, the condition code register to branch on, the
7765     // true/false values to select between, and a branch opcode to use.
7766     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7767     MachineFunction::iterator It = BB;
7768     ++It;
7769
7770     //  thisMBB:
7771     //  ...
7772     //   TrueVal = ...
7773     //   cmpTY ccX, r1, r2
7774     //   bCC copy1MBB
7775     //   fallthrough --> copy0MBB
7776     MachineBasicBlock *thisMBB = BB;
7777     MachineFunction *F = BB->getParent();
7778     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7779     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7780     unsigned Opc =
7781       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7782     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7783     F->insert(It, copy0MBB);
7784     F->insert(It, sinkMBB);
7785     // Update machine-CFG edges by transferring all successors of the current
7786     // block to the new block which will contain the Phi node for the select.
7787     sinkMBB->transferSuccessors(BB);
7788
7789     // Add the true and fallthrough blocks as its successors.
7790     BB->addSuccessor(copy0MBB);
7791     BB->addSuccessor(sinkMBB);
7792
7793     //  copy0MBB:
7794     //   %FalseValue = ...
7795     //   # fallthrough to sinkMBB
7796     BB = copy0MBB;
7797
7798     // Update machine-CFG edges
7799     BB->addSuccessor(sinkMBB);
7800
7801     //  sinkMBB:
7802     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7803     //  ...
7804     BB = sinkMBB;
7805     BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7806       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7807       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7808
7809     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7810     return BB;
7811   }
7812
7813   case X86::FP32_TO_INT16_IN_MEM:
7814   case X86::FP32_TO_INT32_IN_MEM:
7815   case X86::FP32_TO_INT64_IN_MEM:
7816   case X86::FP64_TO_INT16_IN_MEM:
7817   case X86::FP64_TO_INT32_IN_MEM:
7818   case X86::FP64_TO_INT64_IN_MEM:
7819   case X86::FP80_TO_INT16_IN_MEM:
7820   case X86::FP80_TO_INT32_IN_MEM:
7821   case X86::FP80_TO_INT64_IN_MEM: {
7822     // Change the floating point control register to use "round towards zero"
7823     // mode when truncating to an integer value.
7824     MachineFunction *F = BB->getParent();
7825     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7826     addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7827
7828     // Load the old value of the high byte of the control word...
7829     unsigned OldCW =
7830       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7831     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7832                       CWFrameIdx);
7833
7834     // Set the high part to be round to zero...
7835     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7836       .addImm(0xC7F);
7837
7838     // Reload the modified control word now...
7839     addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7840
7841     // Restore the memory image of control word to original value
7842     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7843       .addReg(OldCW);
7844
7845     // Get the X86 opcode to use.
7846     unsigned Opc;
7847     switch (MI->getOpcode()) {
7848     default: llvm_unreachable("illegal opcode!");
7849     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7850     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7851     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7852     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7853     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7854     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7855     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7856     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7857     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7858     }
7859
7860     X86AddressMode AM;
7861     MachineOperand &Op = MI->getOperand(0);
7862     if (Op.isReg()) {
7863       AM.BaseType = X86AddressMode::RegBase;
7864       AM.Base.Reg = Op.getReg();
7865     } else {
7866       AM.BaseType = X86AddressMode::FrameIndexBase;
7867       AM.Base.FrameIndex = Op.getIndex();
7868     }
7869     Op = MI->getOperand(1);
7870     if (Op.isImm())
7871       AM.Scale = Op.getImm();
7872     Op = MI->getOperand(2);
7873     if (Op.isImm())
7874       AM.IndexReg = Op.getImm();
7875     Op = MI->getOperand(3);
7876     if (Op.isGlobal()) {
7877       AM.GV = Op.getGlobal();
7878     } else {
7879       AM.Disp = Op.getImm();
7880     }
7881     addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7882                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7883
7884     // Reload the original control word now.
7885     addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7886
7887     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7888     return BB;
7889   }
7890     // String/text processing lowering.
7891   case X86::PCMPISTRM128REG:
7892     return EmitPCMP(MI, BB, 3, false /* in-mem */);
7893   case X86::PCMPISTRM128MEM:
7894     return EmitPCMP(MI, BB, 3, true /* in-mem */);
7895   case X86::PCMPESTRM128REG:
7896     return EmitPCMP(MI, BB, 5, false /* in mem */);
7897   case X86::PCMPESTRM128MEM:
7898     return EmitPCMP(MI, BB, 5, true /* in mem */);
7899
7900     // Atomic Lowering.
7901   case X86::ATOMAND32:
7902     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7903                                                X86::AND32ri, X86::MOV32rm,
7904                                                X86::LCMPXCHG32, X86::MOV32rr,
7905                                                X86::NOT32r, X86::EAX,
7906                                                X86::GR32RegisterClass);
7907   case X86::ATOMOR32:
7908     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7909                                                X86::OR32ri, X86::MOV32rm,
7910                                                X86::LCMPXCHG32, X86::MOV32rr,
7911                                                X86::NOT32r, X86::EAX,
7912                                                X86::GR32RegisterClass);
7913   case X86::ATOMXOR32:
7914     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7915                                                X86::XOR32ri, X86::MOV32rm,
7916                                                X86::LCMPXCHG32, X86::MOV32rr,
7917                                                X86::NOT32r, X86::EAX,
7918                                                X86::GR32RegisterClass);
7919   case X86::ATOMNAND32:
7920     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7921                                                X86::AND32ri, X86::MOV32rm,
7922                                                X86::LCMPXCHG32, X86::MOV32rr,
7923                                                X86::NOT32r, X86::EAX,
7924                                                X86::GR32RegisterClass, true);
7925   case X86::ATOMMIN32:
7926     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7927   case X86::ATOMMAX32:
7928     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7929   case X86::ATOMUMIN32:
7930     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7931   case X86::ATOMUMAX32:
7932     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7933
7934   case X86::ATOMAND16:
7935     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7936                                                X86::AND16ri, X86::MOV16rm,
7937                                                X86::LCMPXCHG16, X86::MOV16rr,
7938                                                X86::NOT16r, X86::AX,
7939                                                X86::GR16RegisterClass);
7940   case X86::ATOMOR16:
7941     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7942                                                X86::OR16ri, X86::MOV16rm,
7943                                                X86::LCMPXCHG16, X86::MOV16rr,
7944                                                X86::NOT16r, X86::AX,
7945                                                X86::GR16RegisterClass);
7946   case X86::ATOMXOR16:
7947     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7948                                                X86::XOR16ri, X86::MOV16rm,
7949                                                X86::LCMPXCHG16, X86::MOV16rr,
7950                                                X86::NOT16r, X86::AX,
7951                                                X86::GR16RegisterClass);
7952   case X86::ATOMNAND16:
7953     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7954                                                X86::AND16ri, X86::MOV16rm,
7955                                                X86::LCMPXCHG16, X86::MOV16rr,
7956                                                X86::NOT16r, X86::AX,
7957                                                X86::GR16RegisterClass, true);
7958   case X86::ATOMMIN16:
7959     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7960   case X86::ATOMMAX16:
7961     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7962   case X86::ATOMUMIN16:
7963     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7964   case X86::ATOMUMAX16:
7965     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7966
7967   case X86::ATOMAND8:
7968     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7969                                                X86::AND8ri, X86::MOV8rm,
7970                                                X86::LCMPXCHG8, X86::MOV8rr,
7971                                                X86::NOT8r, X86::AL,
7972                                                X86::GR8RegisterClass);
7973   case X86::ATOMOR8:
7974     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7975                                                X86::OR8ri, X86::MOV8rm,
7976                                                X86::LCMPXCHG8, X86::MOV8rr,
7977                                                X86::NOT8r, X86::AL,
7978                                                X86::GR8RegisterClass);
7979   case X86::ATOMXOR8:
7980     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7981                                                X86::XOR8ri, X86::MOV8rm,
7982                                                X86::LCMPXCHG8, X86::MOV8rr,
7983                                                X86::NOT8r, X86::AL,
7984                                                X86::GR8RegisterClass);
7985   case X86::ATOMNAND8:
7986     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7987                                                X86::AND8ri, X86::MOV8rm,
7988                                                X86::LCMPXCHG8, X86::MOV8rr,
7989                                                X86::NOT8r, X86::AL,
7990                                                X86::GR8RegisterClass, true);
7991   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7992   // This group is for 64-bit host.
7993   case X86::ATOMAND64:
7994     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7995                                                X86::AND64ri32, X86::MOV64rm,
7996                                                X86::LCMPXCHG64, X86::MOV64rr,
7997                                                X86::NOT64r, X86::RAX,
7998                                                X86::GR64RegisterClass);
7999   case X86::ATOMOR64:
8000     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8001                                                X86::OR64ri32, X86::MOV64rm,
8002                                                X86::LCMPXCHG64, X86::MOV64rr,
8003                                                X86::NOT64r, X86::RAX,
8004                                                X86::GR64RegisterClass);
8005   case X86::ATOMXOR64:
8006     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8007                                                X86::XOR64ri32, X86::MOV64rm,
8008                                                X86::LCMPXCHG64, X86::MOV64rr,
8009                                                X86::NOT64r, X86::RAX,
8010                                                X86::GR64RegisterClass);
8011   case X86::ATOMNAND64:
8012     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8013                                                X86::AND64ri32, X86::MOV64rm,
8014                                                X86::LCMPXCHG64, X86::MOV64rr,
8015                                                X86::NOT64r, X86::RAX,
8016                                                X86::GR64RegisterClass, true);
8017   case X86::ATOMMIN64:
8018     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8019   case X86::ATOMMAX64:
8020     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8021   case X86::ATOMUMIN64:
8022     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8023   case X86::ATOMUMAX64:
8024     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8025
8026   // This group does 64-bit operations on a 32-bit host.
8027   case X86::ATOMAND6432:
8028     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8029                                                X86::AND32rr, X86::AND32rr,
8030                                                X86::AND32ri, X86::AND32ri,
8031                                                false);
8032   case X86::ATOMOR6432:
8033     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8034                                                X86::OR32rr, X86::OR32rr,
8035                                                X86::OR32ri, X86::OR32ri,
8036                                                false);
8037   case X86::ATOMXOR6432:
8038     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8039                                                X86::XOR32rr, X86::XOR32rr,
8040                                                X86::XOR32ri, X86::XOR32ri,
8041                                                false);
8042   case X86::ATOMNAND6432:
8043     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8044                                                X86::AND32rr, X86::AND32rr,
8045                                                X86::AND32ri, X86::AND32ri,
8046                                                true);
8047   case X86::ATOMADD6432:
8048     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8049                                                X86::ADD32rr, X86::ADC32rr,
8050                                                X86::ADD32ri, X86::ADC32ri,
8051                                                false);
8052   case X86::ATOMSUB6432:
8053     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8054                                                X86::SUB32rr, X86::SBB32rr,
8055                                                X86::SUB32ri, X86::SBB32ri,
8056                                                false);
8057   case X86::ATOMSWAP6432:
8058     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8059                                                X86::MOV32rr, X86::MOV32rr,
8060                                                X86::MOV32ri, X86::MOV32ri,
8061                                                false);
8062   case X86::VASTART_SAVE_XMM_REGS:
8063     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8064   }
8065 }
8066
8067 //===----------------------------------------------------------------------===//
8068 //                           X86 Optimization Hooks
8069 //===----------------------------------------------------------------------===//
8070
8071 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8072                                                        const APInt &Mask,
8073                                                        APInt &KnownZero,
8074                                                        APInt &KnownOne,
8075                                                        const SelectionDAG &DAG,
8076                                                        unsigned Depth) const {
8077   unsigned Opc = Op.getOpcode();
8078   assert((Opc >= ISD::BUILTIN_OP_END ||
8079           Opc == ISD::INTRINSIC_WO_CHAIN ||
8080           Opc == ISD::INTRINSIC_W_CHAIN ||
8081           Opc == ISD::INTRINSIC_VOID) &&
8082          "Should use MaskedValueIsZero if you don't know whether Op"
8083          " is a target node!");
8084
8085   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8086   switch (Opc) {
8087   default: break;
8088   case X86ISD::ADD:
8089   case X86ISD::SUB:
8090   case X86ISD::SMUL:
8091   case X86ISD::UMUL:
8092   case X86ISD::INC:
8093   case X86ISD::DEC:
8094     // These nodes' second result is a boolean.
8095     if (Op.getResNo() == 0)
8096       break;
8097     // Fallthrough
8098   case X86ISD::SETCC:
8099     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8100                                        Mask.getBitWidth() - 1);
8101     break;
8102   }
8103 }
8104
8105 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8106 /// node is a GlobalAddress + offset.
8107 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8108                                        GlobalValue* &GA, int64_t &Offset) const{
8109   if (N->getOpcode() == X86ISD::Wrapper) {
8110     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8111       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8112       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8113       return true;
8114     }
8115   }
8116   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8117 }
8118
8119 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8120                                const TargetLowering &TLI) {
8121   GlobalValue *GV;
8122   int64_t Offset = 0;
8123   if (TLI.isGAPlusOffset(Base, GV, Offset))
8124     return (GV->getAlignment() >= N && (Offset % N) == 0);
8125   // DAG combine handles the stack object case.
8126   return false;
8127 }
8128
8129 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8130                                      EVT EVT, LoadSDNode *&LDBase,
8131                                      unsigned &LastLoadedElt,
8132                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8133                                      const TargetLowering &TLI) {
8134   LDBase = NULL;
8135   LastLoadedElt = -1U;
8136   for (unsigned i = 0; i < NumElems; ++i) {
8137     if (N->getMaskElt(i) < 0) {
8138       if (!LDBase)
8139         return false;
8140       continue;
8141     }
8142
8143     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8144     if (!Elt.getNode() ||
8145         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8146       return false;
8147     if (!LDBase) {
8148       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8149         return false;
8150       LDBase = cast<LoadSDNode>(Elt.getNode());
8151       LastLoadedElt = i;
8152       continue;
8153     }
8154     if (Elt.getOpcode() == ISD::UNDEF)
8155       continue;
8156
8157     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8158     if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
8159       return false;
8160     LastLoadedElt = i;
8161   }
8162   return true;
8163 }
8164
8165 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8166 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8167 /// if the load addresses are consecutive, non-overlapping, and in the right
8168 /// order.  In the case of v2i64, it will see if it can rewrite the
8169 /// shuffle to be an appropriate build vector so it can take advantage of
8170 // performBuildVectorCombine.
8171 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8172                                      const TargetLowering &TLI) {
8173   DebugLoc dl = N->getDebugLoc();
8174   EVT VT = N->getValueType(0);
8175   EVT EVT = VT.getVectorElementType();
8176   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8177   unsigned NumElems = VT.getVectorNumElements();
8178
8179   if (VT.getSizeInBits() != 128)
8180     return SDValue();
8181
8182   // Try to combine a vector_shuffle into a 128-bit load.
8183   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8184   LoadSDNode *LD = NULL;
8185   unsigned LastLoadedElt;
8186   if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
8187                                 MFI, TLI))
8188     return SDValue();
8189
8190   if (LastLoadedElt == NumElems - 1) {
8191     if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
8192       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8193                          LD->getSrcValue(), LD->getSrcValueOffset(),
8194                          LD->isVolatile());
8195     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8196                        LD->getSrcValue(), LD->getSrcValueOffset(),
8197                        LD->isVolatile(), LD->getAlignment());
8198   } else if (NumElems == 4 && LastLoadedElt == 1) {
8199     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8200     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8201     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8202     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8203   }
8204   return SDValue();
8205 }
8206
8207 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8208 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8209                                     const X86Subtarget *Subtarget) {
8210   DebugLoc DL = N->getDebugLoc();
8211   SDValue Cond = N->getOperand(0);
8212   // Get the LHS/RHS of the select.
8213   SDValue LHS = N->getOperand(1);
8214   SDValue RHS = N->getOperand(2);
8215
8216   // If we have SSE[12] support, try to form min/max nodes.
8217   if (Subtarget->hasSSE2() &&
8218       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8219       Cond.getOpcode() == ISD::SETCC) {
8220     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8221
8222     unsigned Opcode = 0;
8223     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8224       switch (CC) {
8225       default: break;
8226       case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8227       case ISD::SETULE:
8228       case ISD::SETLE:
8229         if (!UnsafeFPMath) break;
8230         // FALL THROUGH.
8231       case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
8232       case ISD::SETLT:
8233         Opcode = X86ISD::FMIN;
8234         break;
8235
8236       case ISD::SETOGT: // (X > Y) ? X : Y -> max
8237       case ISD::SETUGT:
8238       case ISD::SETGT:
8239         if (!UnsafeFPMath) break;
8240         // FALL THROUGH.
8241       case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
8242       case ISD::SETGE:
8243         Opcode = X86ISD::FMAX;
8244         break;
8245       }
8246     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8247       switch (CC) {
8248       default: break;
8249       case ISD::SETOGT: // (X > Y) ? Y : X -> min
8250       case ISD::SETUGT:
8251       case ISD::SETGT:
8252         if (!UnsafeFPMath) break;
8253         // FALL THROUGH.
8254       case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
8255       case ISD::SETGE:
8256         Opcode = X86ISD::FMIN;
8257         break;
8258
8259       case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
8260       case ISD::SETULE:
8261       case ISD::SETLE:
8262         if (!UnsafeFPMath) break;
8263         // FALL THROUGH.
8264       case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
8265       case ISD::SETLT:
8266         Opcode = X86ISD::FMAX;
8267         break;
8268       }
8269     }
8270
8271     if (Opcode)
8272       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8273   }
8274
8275   // If this is a select between two integer constants, try to do some
8276   // optimizations.
8277   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8278     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8279       // Don't do this for crazy integer types.
8280       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8281         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8282         // so that TrueC (the true value) is larger than FalseC.
8283         bool NeedsCondInvert = false;
8284
8285         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8286             // Efficiently invertible.
8287             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8288              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8289               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8290           NeedsCondInvert = true;
8291           std::swap(TrueC, FalseC);
8292         }
8293
8294         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8295         if (FalseC->getAPIntValue() == 0 &&
8296             TrueC->getAPIntValue().isPowerOf2()) {
8297           if (NeedsCondInvert) // Invert the condition if needed.
8298             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8299                                DAG.getConstant(1, Cond.getValueType()));
8300
8301           // Zero extend the condition if needed.
8302           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8303
8304           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8305           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8306                              DAG.getConstant(ShAmt, MVT::i8));
8307         }
8308
8309         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8310         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8311           if (NeedsCondInvert) // Invert the condition if needed.
8312             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8313                                DAG.getConstant(1, Cond.getValueType()));
8314
8315           // Zero extend the condition if needed.
8316           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8317                              FalseC->getValueType(0), Cond);
8318           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8319                              SDValue(FalseC, 0));
8320         }
8321
8322         // Optimize cases that will turn into an LEA instruction.  This requires
8323         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8324         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8325           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8326           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8327
8328           bool isFastMultiplier = false;
8329           if (Diff < 10) {
8330             switch ((unsigned char)Diff) {
8331               default: break;
8332               case 1:  // result = add base, cond
8333               case 2:  // result = lea base(    , cond*2)
8334               case 3:  // result = lea base(cond, cond*2)
8335               case 4:  // result = lea base(    , cond*4)
8336               case 5:  // result = lea base(cond, cond*4)
8337               case 8:  // result = lea base(    , cond*8)
8338               case 9:  // result = lea base(cond, cond*8)
8339                 isFastMultiplier = true;
8340                 break;
8341             }
8342           }
8343
8344           if (isFastMultiplier) {
8345             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8346             if (NeedsCondInvert) // Invert the condition if needed.
8347               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8348                                  DAG.getConstant(1, Cond.getValueType()));
8349
8350             // Zero extend the condition if needed.
8351             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8352                                Cond);
8353             // Scale the condition by the difference.
8354             if (Diff != 1)
8355               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8356                                  DAG.getConstant(Diff, Cond.getValueType()));
8357
8358             // Add the base if non-zero.
8359             if (FalseC->getAPIntValue() != 0)
8360               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8361                                  SDValue(FalseC, 0));
8362             return Cond;
8363           }
8364         }
8365       }
8366   }
8367
8368   return SDValue();
8369 }
8370
8371 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8372 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8373                                   TargetLowering::DAGCombinerInfo &DCI) {
8374   DebugLoc DL = N->getDebugLoc();
8375
8376   // If the flag operand isn't dead, don't touch this CMOV.
8377   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8378     return SDValue();
8379
8380   // If this is a select between two integer constants, try to do some
8381   // optimizations.  Note that the operands are ordered the opposite of SELECT
8382   // operands.
8383   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8384     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8385       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8386       // larger than FalseC (the false value).
8387       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8388
8389       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8390         CC = X86::GetOppositeBranchCondition(CC);
8391         std::swap(TrueC, FalseC);
8392       }
8393
8394       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
8395       // This is efficient for any integer data type (including i8/i16) and
8396       // shift amount.
8397       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8398         SDValue Cond = N->getOperand(3);
8399         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8400                            DAG.getConstant(CC, MVT::i8), Cond);
8401
8402         // Zero extend the condition if needed.
8403         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8404
8405         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8406         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8407                            DAG.getConstant(ShAmt, MVT::i8));
8408         if (N->getNumValues() == 2)  // Dead flag value?
8409           return DCI.CombineTo(N, Cond, SDValue());
8410         return Cond;
8411       }
8412
8413       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
8414       // for any integer data type, including i8/i16.
8415       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8416         SDValue Cond = N->getOperand(3);
8417         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8418                            DAG.getConstant(CC, MVT::i8), Cond);
8419
8420         // Zero extend the condition if needed.
8421         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8422                            FalseC->getValueType(0), Cond);
8423         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8424                            SDValue(FalseC, 0));
8425
8426         if (N->getNumValues() == 2)  // Dead flag value?
8427           return DCI.CombineTo(N, Cond, SDValue());
8428         return Cond;
8429       }
8430
8431       // Optimize cases that will turn into an LEA instruction.  This requires
8432       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8433       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8434         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8435         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8436
8437         bool isFastMultiplier = false;
8438         if (Diff < 10) {
8439           switch ((unsigned char)Diff) {
8440           default: break;
8441           case 1:  // result = add base, cond
8442           case 2:  // result = lea base(    , cond*2)
8443           case 3:  // result = lea base(cond, cond*2)
8444           case 4:  // result = lea base(    , cond*4)
8445           case 5:  // result = lea base(cond, cond*4)
8446           case 8:  // result = lea base(    , cond*8)
8447           case 9:  // result = lea base(cond, cond*8)
8448             isFastMultiplier = true;
8449             break;
8450           }
8451         }
8452
8453         if (isFastMultiplier) {
8454           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8455           SDValue Cond = N->getOperand(3);
8456           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8457                              DAG.getConstant(CC, MVT::i8), Cond);
8458           // Zero extend the condition if needed.
8459           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8460                              Cond);
8461           // Scale the condition by the difference.
8462           if (Diff != 1)
8463             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8464                                DAG.getConstant(Diff, Cond.getValueType()));
8465
8466           // Add the base if non-zero.
8467           if (FalseC->getAPIntValue() != 0)
8468             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8469                                SDValue(FalseC, 0));
8470           if (N->getNumValues() == 2)  // Dead flag value?
8471             return DCI.CombineTo(N, Cond, SDValue());
8472           return Cond;
8473         }
8474       }
8475     }
8476   }
8477   return SDValue();
8478 }
8479
8480
8481 /// PerformMulCombine - Optimize a single multiply with constant into two
8482 /// in order to implement it with two cheaper instructions, e.g.
8483 /// LEA + SHL, LEA + LEA.
8484 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8485                                  TargetLowering::DAGCombinerInfo &DCI) {
8486   if (DAG.getMachineFunction().
8487       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8488     return SDValue();
8489
8490   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8491     return SDValue();
8492
8493   EVT VT = N->getValueType(0);
8494   if (VT != MVT::i64)
8495     return SDValue();
8496
8497   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8498   if (!C)
8499     return SDValue();
8500   uint64_t MulAmt = C->getZExtValue();
8501   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8502     return SDValue();
8503
8504   uint64_t MulAmt1 = 0;
8505   uint64_t MulAmt2 = 0;
8506   if ((MulAmt % 9) == 0) {
8507     MulAmt1 = 9;
8508     MulAmt2 = MulAmt / 9;
8509   } else if ((MulAmt % 5) == 0) {
8510     MulAmt1 = 5;
8511     MulAmt2 = MulAmt / 5;
8512   } else if ((MulAmt % 3) == 0) {
8513     MulAmt1 = 3;
8514     MulAmt2 = MulAmt / 3;
8515   }
8516   if (MulAmt2 &&
8517       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8518     DebugLoc DL = N->getDebugLoc();
8519
8520     if (isPowerOf2_64(MulAmt2) &&
8521         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8522       // If second multiplifer is pow2, issue it first. We want the multiply by
8523       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8524       // is an add.
8525       std::swap(MulAmt1, MulAmt2);
8526
8527     SDValue NewMul;
8528     if (isPowerOf2_64(MulAmt1))
8529       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8530                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8531     else
8532       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8533                            DAG.getConstant(MulAmt1, VT));
8534
8535     if (isPowerOf2_64(MulAmt2))
8536       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8537                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8538     else
8539       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8540                            DAG.getConstant(MulAmt2, VT));
8541
8542     // Do not add new nodes to DAG combiner worklist.
8543     DCI.CombineTo(N, NewMul, false);
8544   }
8545   return SDValue();
8546 }
8547
8548
8549 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8550 ///                       when possible.
8551 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8552                                    const X86Subtarget *Subtarget) {
8553   // On X86 with SSE2 support, we can transform this to a vector shift if
8554   // all elements are shifted by the same amount.  We can't do this in legalize
8555   // because the a constant vector is typically transformed to a constant pool
8556   // so we have no knowledge of the shift amount.
8557   if (!Subtarget->hasSSE2())
8558     return SDValue();
8559
8560   EVT VT = N->getValueType(0);
8561   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8562     return SDValue();
8563
8564   SDValue ShAmtOp = N->getOperand(1);
8565   EVT EltVT = VT.getVectorElementType();
8566   DebugLoc DL = N->getDebugLoc();
8567   SDValue BaseShAmt;
8568   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8569     unsigned NumElts = VT.getVectorNumElements();
8570     unsigned i = 0;
8571     for (; i != NumElts; ++i) {
8572       SDValue Arg = ShAmtOp.getOperand(i);
8573       if (Arg.getOpcode() == ISD::UNDEF) continue;
8574       BaseShAmt = Arg;
8575       break;
8576     }
8577     for (; i != NumElts; ++i) {
8578       SDValue Arg = ShAmtOp.getOperand(i);
8579       if (Arg.getOpcode() == ISD::UNDEF) continue;
8580       if (Arg != BaseShAmt) {
8581         return SDValue();
8582       }
8583     }
8584   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8585              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8586     BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8587                             DAG.getIntPtrConstant(0));
8588   } else
8589     return SDValue();
8590
8591   if (EltVT.bitsGT(MVT::i32))
8592     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8593   else if (EltVT.bitsLT(MVT::i32))
8594     BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8595
8596   // The shift amount is identical so we can do a vector shift.
8597   SDValue  ValOp = N->getOperand(0);
8598   switch (N->getOpcode()) {
8599   default:
8600     llvm_unreachable("Unknown shift opcode!");
8601     break;
8602   case ISD::SHL:
8603     if (VT == MVT::v2i64)
8604       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8605                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8606                          ValOp, BaseShAmt);
8607     if (VT == MVT::v4i32)
8608       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8609                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8610                          ValOp, BaseShAmt);
8611     if (VT == MVT::v8i16)
8612       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8613                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8614                          ValOp, BaseShAmt);
8615     break;
8616   case ISD::SRA:
8617     if (VT == MVT::v4i32)
8618       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8619                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8620                          ValOp, BaseShAmt);
8621     if (VT == MVT::v8i16)
8622       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8623                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8624                          ValOp, BaseShAmt);
8625     break;
8626   case ISD::SRL:
8627     if (VT == MVT::v2i64)
8628       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8629                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8630                          ValOp, BaseShAmt);
8631     if (VT == MVT::v4i32)
8632       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8633                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8634                          ValOp, BaseShAmt);
8635     if (VT ==  MVT::v8i16)
8636       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8637                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8638                          ValOp, BaseShAmt);
8639     break;
8640   }
8641   return SDValue();
8642 }
8643
8644 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8645 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8646                                    const X86Subtarget *Subtarget) {
8647   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
8648   // the FP state in cases where an emms may be missing.
8649   // A preferable solution to the general problem is to figure out the right
8650   // places to insert EMMS.  This qualifies as a quick hack.
8651
8652   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8653   StoreSDNode *St = cast<StoreSDNode>(N);
8654   EVT VT = St->getValue().getValueType();
8655   if (VT.getSizeInBits() != 64)
8656     return SDValue();
8657
8658   const Function *F = DAG.getMachineFunction().getFunction();
8659   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8660   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8661     && Subtarget->hasSSE2();
8662   if ((VT.isVector() ||
8663        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8664       isa<LoadSDNode>(St->getValue()) &&
8665       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8666       St->getChain().hasOneUse() && !St->isVolatile()) {
8667     SDNode* LdVal = St->getValue().getNode();
8668     LoadSDNode *Ld = 0;
8669     int TokenFactorIndex = -1;
8670     SmallVector<SDValue, 8> Ops;
8671     SDNode* ChainVal = St->getChain().getNode();
8672     // Must be a store of a load.  We currently handle two cases:  the load
8673     // is a direct child, and it's under an intervening TokenFactor.  It is
8674     // possible to dig deeper under nested TokenFactors.
8675     if (ChainVal == LdVal)
8676       Ld = cast<LoadSDNode>(St->getChain());
8677     else if (St->getValue().hasOneUse() &&
8678              ChainVal->getOpcode() == ISD::TokenFactor) {
8679       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8680         if (ChainVal->getOperand(i).getNode() == LdVal) {
8681           TokenFactorIndex = i;
8682           Ld = cast<LoadSDNode>(St->getValue());
8683         } else
8684           Ops.push_back(ChainVal->getOperand(i));
8685       }
8686     }
8687
8688     if (!Ld || !ISD::isNormalLoad(Ld))
8689       return SDValue();
8690
8691     // If this is not the MMX case, i.e. we are just turning i64 load/store
8692     // into f64 load/store, avoid the transformation if there are multiple
8693     // uses of the loaded value.
8694     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8695       return SDValue();
8696
8697     DebugLoc LdDL = Ld->getDebugLoc();
8698     DebugLoc StDL = N->getDebugLoc();
8699     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8700     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8701     // pair instead.
8702     if (Subtarget->is64Bit() || F64IsLegal) {
8703       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8704       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8705                                   Ld->getBasePtr(), Ld->getSrcValue(),
8706                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
8707                                   Ld->getAlignment());
8708       SDValue NewChain = NewLd.getValue(1);
8709       if (TokenFactorIndex != -1) {
8710         Ops.push_back(NewChain);
8711         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8712                                Ops.size());
8713       }
8714       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8715                           St->getSrcValue(), St->getSrcValueOffset(),
8716                           St->isVolatile(), St->getAlignment());
8717     }
8718
8719     // Otherwise, lower to two pairs of 32-bit loads / stores.
8720     SDValue LoAddr = Ld->getBasePtr();
8721     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8722                                  DAG.getConstant(4, MVT::i32));
8723
8724     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8725                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
8726                                Ld->isVolatile(), Ld->getAlignment());
8727     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8728                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8729                                Ld->isVolatile(),
8730                                MinAlign(Ld->getAlignment(), 4));
8731
8732     SDValue NewChain = LoLd.getValue(1);
8733     if (TokenFactorIndex != -1) {
8734       Ops.push_back(LoLd);
8735       Ops.push_back(HiLd);
8736       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8737                              Ops.size());
8738     }
8739
8740     LoAddr = St->getBasePtr();
8741     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8742                          DAG.getConstant(4, MVT::i32));
8743
8744     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8745                                 St->getSrcValue(), St->getSrcValueOffset(),
8746                                 St->isVolatile(), St->getAlignment());
8747     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8748                                 St->getSrcValue(),
8749                                 St->getSrcValueOffset() + 4,
8750                                 St->isVolatile(),
8751                                 MinAlign(St->getAlignment(), 4));
8752     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8753   }
8754   return SDValue();
8755 }
8756
8757 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8758 /// X86ISD::FXOR nodes.
8759 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8760   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8761   // F[X]OR(0.0, x) -> x
8762   // F[X]OR(x, 0.0) -> x
8763   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8764     if (C->getValueAPF().isPosZero())
8765       return N->getOperand(1);
8766   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8767     if (C->getValueAPF().isPosZero())
8768       return N->getOperand(0);
8769   return SDValue();
8770 }
8771
8772 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8773 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8774   // FAND(0.0, x) -> 0.0
8775   // FAND(x, 0.0) -> 0.0
8776   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8777     if (C->getValueAPF().isPosZero())
8778       return N->getOperand(0);
8779   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8780     if (C->getValueAPF().isPosZero())
8781       return N->getOperand(1);
8782   return SDValue();
8783 }
8784
8785 static SDValue PerformBTCombine(SDNode *N,
8786                                 SelectionDAG &DAG,
8787                                 TargetLowering::DAGCombinerInfo &DCI) {
8788   // BT ignores high bits in the bit index operand.
8789   SDValue Op1 = N->getOperand(1);
8790   if (Op1.hasOneUse()) {
8791     unsigned BitWidth = Op1.getValueSizeInBits();
8792     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8793     APInt KnownZero, KnownOne;
8794     TargetLowering::TargetLoweringOpt TLO(DAG);
8795     TargetLowering &TLI = DAG.getTargetLoweringInfo();
8796     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8797         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8798       DCI.CommitTargetLoweringOpt(TLO);
8799   }
8800   return SDValue();
8801 }
8802
8803 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8804   SDValue Op = N->getOperand(0);
8805   if (Op.getOpcode() == ISD::BIT_CONVERT)
8806     Op = Op.getOperand(0);
8807   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
8808   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8809       VT.getVectorElementType().getSizeInBits() ==
8810       OpVT.getVectorElementType().getSizeInBits()) {
8811     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8812   }
8813   return SDValue();
8814 }
8815
8816 // On X86 and X86-64, atomic operations are lowered to locked instructions.
8817 // Locked instructions, in turn, have implicit fence semantics (all memory
8818 // operations are flushed before issuing the locked instruction, and the
8819 // are not buffered), so we can fold away the common pattern of
8820 // fence-atomic-fence.
8821 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
8822   SDValue atomic = N->getOperand(0);
8823   switch (atomic.getOpcode()) {
8824     case ISD::ATOMIC_CMP_SWAP:
8825     case ISD::ATOMIC_SWAP:
8826     case ISD::ATOMIC_LOAD_ADD:
8827     case ISD::ATOMIC_LOAD_SUB:
8828     case ISD::ATOMIC_LOAD_AND:
8829     case ISD::ATOMIC_LOAD_OR:
8830     case ISD::ATOMIC_LOAD_XOR:
8831     case ISD::ATOMIC_LOAD_NAND:
8832     case ISD::ATOMIC_LOAD_MIN:
8833     case ISD::ATOMIC_LOAD_MAX:
8834     case ISD::ATOMIC_LOAD_UMIN:
8835     case ISD::ATOMIC_LOAD_UMAX:
8836       break;
8837     default:
8838       return SDValue();
8839   }
8840
8841   SDValue fence = atomic.getOperand(0);
8842   if (fence.getOpcode() != ISD::MEMBARRIER)
8843     return SDValue();
8844
8845   switch (atomic.getOpcode()) {
8846     case ISD::ATOMIC_CMP_SWAP:
8847       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8848                                     atomic.getOperand(1), atomic.getOperand(2),
8849                                     atomic.getOperand(3));
8850     case ISD::ATOMIC_SWAP:
8851     case ISD::ATOMIC_LOAD_ADD:
8852     case ISD::ATOMIC_LOAD_SUB:
8853     case ISD::ATOMIC_LOAD_AND:
8854     case ISD::ATOMIC_LOAD_OR:
8855     case ISD::ATOMIC_LOAD_XOR:
8856     case ISD::ATOMIC_LOAD_NAND:
8857     case ISD::ATOMIC_LOAD_MIN:
8858     case ISD::ATOMIC_LOAD_MAX:
8859     case ISD::ATOMIC_LOAD_UMIN:
8860     case ISD::ATOMIC_LOAD_UMAX:
8861       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8862                                     atomic.getOperand(1), atomic.getOperand(2));
8863     default:
8864       return SDValue();
8865   }
8866 }
8867
8868 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8869                                              DAGCombinerInfo &DCI) const {
8870   SelectionDAG &DAG = DCI.DAG;
8871   switch (N->getOpcode()) {
8872   default: break;
8873   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8874   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
8875   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
8876   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
8877   case ISD::SHL:
8878   case ISD::SRA:
8879   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
8880   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
8881   case X86ISD::FXOR:
8882   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
8883   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
8884   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
8885   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
8886   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
8887   }
8888
8889   return SDValue();
8890 }
8891
8892 //===----------------------------------------------------------------------===//
8893 //                           X86 Inline Assembly Support
8894 //===----------------------------------------------------------------------===//
8895
8896 static bool LowerToBSwap(CallInst *CI) {
8897   // FIXME: this should verify that we are targetting a 486 or better.  If not,
8898   // we will turn this bswap into something that will be lowered to logical ops
8899   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
8900   // so don't worry about this.
8901
8902   // Verify this is a simple bswap.
8903   if (CI->getNumOperands() != 2 ||
8904       CI->getType() != CI->getOperand(1)->getType() ||
8905       !CI->getType()->isInteger())
8906     return false;
8907
8908   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8909   if (!Ty || Ty->getBitWidth() % 16 != 0)
8910     return false;
8911
8912   // Okay, we can do this xform, do so now.
8913   const Type *Tys[] = { Ty };
8914   Module *M = CI->getParent()->getParent()->getParent();
8915   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
8916
8917   Value *Op = CI->getOperand(1);
8918   Op = CallInst::Create(Int, Op, CI->getName(), CI);
8919
8920   CI->replaceAllUsesWith(Op);
8921   CI->eraseFromParent();
8922   return true;
8923 }
8924
8925 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
8926   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8927   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
8928
8929   std::string AsmStr = IA->getAsmString();
8930
8931   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
8932   std::vector<std::string> AsmPieces;
8933   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
8934
8935   switch (AsmPieces.size()) {
8936   default: return false;
8937   case 1:
8938     AsmStr = AsmPieces[0];
8939     AsmPieces.clear();
8940     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
8941
8942     // bswap $0
8943     if (AsmPieces.size() == 2 &&
8944         (AsmPieces[0] == "bswap" ||
8945          AsmPieces[0] == "bswapq" ||
8946          AsmPieces[0] == "bswapl") &&
8947         (AsmPieces[1] == "$0" ||
8948          AsmPieces[1] == "${0:q}")) {
8949       // No need to check constraints, nothing other than the equivalent of
8950       // "=r,0" would be valid here.
8951       return LowerToBSwap(CI);
8952     }
8953     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
8954     if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
8955         AsmPieces.size() == 3 &&
8956         AsmPieces[0] == "rorw" &&
8957         AsmPieces[1] == "$$8," &&
8958         AsmPieces[2] == "${0:w}" &&
8959         IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
8960       return LowerToBSwap(CI);
8961     }
8962     break;
8963   case 3:
8964     if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
8965         Constraints.size() >= 2 &&
8966         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
8967         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
8968       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
8969       std::vector<std::string> Words;
8970       SplitString(AsmPieces[0], Words, " \t");
8971       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
8972         Words.clear();
8973         SplitString(AsmPieces[1], Words, " \t");
8974         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
8975           Words.clear();
8976           SplitString(AsmPieces[2], Words, " \t,");
8977           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
8978               Words[2] == "%edx") {
8979             return LowerToBSwap(CI);
8980           }
8981         }
8982       }
8983     }
8984     break;
8985   }
8986   return false;
8987 }
8988
8989
8990
8991 /// getConstraintType - Given a constraint letter, return the type of
8992 /// constraint it is for this target.
8993 X86TargetLowering::ConstraintType
8994 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8995   if (Constraint.size() == 1) {
8996     switch (Constraint[0]) {
8997     case 'A':
8998       return C_Register;
8999     case 'f':
9000     case 'r':
9001     case 'R':
9002     case 'l':
9003     case 'q':
9004     case 'Q':
9005     case 'x':
9006     case 'y':
9007     case 'Y':
9008       return C_RegisterClass;
9009     case 'e':
9010     case 'Z':
9011       return C_Other;
9012     default:
9013       break;
9014     }
9015   }
9016   return TargetLowering::getConstraintType(Constraint);
9017 }
9018
9019 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9020 /// with another that has more specific requirements based on the type of the
9021 /// corresponding operand.
9022 const char *X86TargetLowering::
9023 LowerXConstraint(EVT ConstraintVT) const {
9024   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9025   // 'f' like normal targets.
9026   if (ConstraintVT.isFloatingPoint()) {
9027     if (Subtarget->hasSSE2())
9028       return "Y";
9029     if (Subtarget->hasSSE1())
9030       return "x";
9031   }
9032
9033   return TargetLowering::LowerXConstraint(ConstraintVT);
9034 }
9035
9036 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9037 /// vector.  If it is invalid, don't add anything to Ops.
9038 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9039                                                      char Constraint,
9040                                                      bool hasMemory,
9041                                                      std::vector<SDValue>&Ops,
9042                                                      SelectionDAG &DAG) const {
9043   SDValue Result(0, 0);
9044
9045   switch (Constraint) {
9046   default: break;
9047   case 'I':
9048     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9049       if (C->getZExtValue() <= 31) {
9050         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9051         break;
9052       }
9053     }
9054     return;
9055   case 'J':
9056     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9057       if (C->getZExtValue() <= 63) {
9058         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9059         break;
9060       }
9061     }
9062     return;
9063   case 'K':
9064     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9065       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9066         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9067         break;
9068       }
9069     }
9070     return;
9071   case 'N':
9072     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9073       if (C->getZExtValue() <= 255) {
9074         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9075         break;
9076       }
9077     }
9078     return;
9079   case 'e': {
9080     // 32-bit signed value
9081     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9082       const ConstantInt *CI = C->getConstantIntValue();
9083       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9084                                   C->getSExtValue())) {
9085         // Widen to 64 bits here to get it sign extended.
9086         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9087         break;
9088       }
9089     // FIXME gcc accepts some relocatable values here too, but only in certain
9090     // memory models; it's complicated.
9091     }
9092     return;
9093   }
9094   case 'Z': {
9095     // 32-bit unsigned value
9096     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9097       const ConstantInt *CI = C->getConstantIntValue();
9098       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9099                                   C->getZExtValue())) {
9100         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9101         break;
9102       }
9103     }
9104     // FIXME gcc accepts some relocatable values here too, but only in certain
9105     // memory models; it's complicated.
9106     return;
9107   }
9108   case 'i': {
9109     // Literal immediates are always ok.
9110     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9111       // Widen to 64 bits here to get it sign extended.
9112       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9113       break;
9114     }
9115
9116     // If we are in non-pic codegen mode, we allow the address of a global (with
9117     // an optional displacement) to be used with 'i'.
9118     GlobalAddressSDNode *GA = 0;
9119     int64_t Offset = 0;
9120
9121     // Match either (GA), (GA+C), (GA+C1+C2), etc.
9122     while (1) {
9123       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9124         Offset += GA->getOffset();
9125         break;
9126       } else if (Op.getOpcode() == ISD::ADD) {
9127         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9128           Offset += C->getZExtValue();
9129           Op = Op.getOperand(0);
9130           continue;
9131         }
9132       } else if (Op.getOpcode() == ISD::SUB) {
9133         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9134           Offset += -C->getZExtValue();
9135           Op = Op.getOperand(0);
9136           continue;
9137         }
9138       }
9139
9140       // Otherwise, this isn't something we can handle, reject it.
9141       return;
9142     }
9143
9144     GlobalValue *GV = GA->getGlobal();
9145     // If we require an extra load to get this address, as in PIC mode, we
9146     // can't accept it.
9147     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9148                                                         getTargetMachine())))
9149       return;
9150
9151     if (hasMemory)
9152       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9153     else
9154       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9155     Result = Op;
9156     break;
9157   }
9158   }
9159
9160   if (Result.getNode()) {
9161     Ops.push_back(Result);
9162     return;
9163   }
9164   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9165                                                       Ops, DAG);
9166 }
9167
9168 std::vector<unsigned> X86TargetLowering::
9169 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9170                                   EVT VT) const {
9171   if (Constraint.size() == 1) {
9172     // FIXME: not handling fp-stack yet!
9173     switch (Constraint[0]) {      // GCC X86 Constraint Letters
9174     default: break;  // Unknown constraint letter
9175     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9176       if (Subtarget->is64Bit()) {
9177         if (VT == MVT::i32)
9178           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9179                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9180                                        X86::R10D,X86::R11D,X86::R12D,
9181                                        X86::R13D,X86::R14D,X86::R15D,
9182                                        X86::EBP, X86::ESP, 0);
9183         else if (VT == MVT::i16)
9184           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
9185                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
9186                                        X86::R10W,X86::R11W,X86::R12W,
9187                                        X86::R13W,X86::R14W,X86::R15W,
9188                                        X86::BP,  X86::SP, 0);
9189         else if (VT == MVT::i8)
9190           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
9191                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9192                                        X86::R10B,X86::R11B,X86::R12B,
9193                                        X86::R13B,X86::R14B,X86::R15B,
9194                                        X86::BPL, X86::SPL, 0);
9195
9196         else if (VT == MVT::i64)
9197           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9198                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
9199                                        X86::R10, X86::R11, X86::R12,
9200                                        X86::R13, X86::R14, X86::R15,
9201                                        X86::RBP, X86::RSP, 0);
9202
9203         break;
9204       }
9205       // 32-bit fallthrough
9206     case 'Q':   // Q_REGS
9207       if (VT == MVT::i32)
9208         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9209       else if (VT == MVT::i16)
9210         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9211       else if (VT == MVT::i8)
9212         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9213       else if (VT == MVT::i64)
9214         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9215       break;
9216     }
9217   }
9218
9219   return std::vector<unsigned>();
9220 }
9221
9222 std::pair<unsigned, const TargetRegisterClass*>
9223 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9224                                                 EVT VT) const {
9225   // First, see if this is a constraint that directly corresponds to an LLVM
9226   // register class.
9227   if (Constraint.size() == 1) {
9228     // GCC Constraint Letters
9229     switch (Constraint[0]) {
9230     default: break;
9231     case 'r':   // GENERAL_REGS
9232     case 'R':   // LEGACY_REGS
9233     case 'l':   // INDEX_REGS
9234       if (VT == MVT::i8)
9235         return std::make_pair(0U, X86::GR8RegisterClass);
9236       if (VT == MVT::i16)
9237         return std::make_pair(0U, X86::GR16RegisterClass);
9238       if (VT == MVT::i32 || !Subtarget->is64Bit())
9239         return std::make_pair(0U, X86::GR32RegisterClass);
9240       return std::make_pair(0U, X86::GR64RegisterClass);
9241     case 'f':  // FP Stack registers.
9242       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9243       // value to the correct fpstack register class.
9244       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9245         return std::make_pair(0U, X86::RFP32RegisterClass);
9246       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9247         return std::make_pair(0U, X86::RFP64RegisterClass);
9248       return std::make_pair(0U, X86::RFP80RegisterClass);
9249     case 'y':   // MMX_REGS if MMX allowed.
9250       if (!Subtarget->hasMMX()) break;
9251       return std::make_pair(0U, X86::VR64RegisterClass);
9252     case 'Y':   // SSE_REGS if SSE2 allowed
9253       if (!Subtarget->hasSSE2()) break;
9254       // FALL THROUGH.
9255     case 'x':   // SSE_REGS if SSE1 allowed
9256       if (!Subtarget->hasSSE1()) break;
9257
9258       switch (VT.getSimpleVT().SimpleTy) {
9259       default: break;
9260       // Scalar SSE types.
9261       case MVT::f32:
9262       case MVT::i32:
9263         return std::make_pair(0U, X86::FR32RegisterClass);
9264       case MVT::f64:
9265       case MVT::i64:
9266         return std::make_pair(0U, X86::FR64RegisterClass);
9267       // Vector types.
9268       case MVT::v16i8:
9269       case MVT::v8i16:
9270       case MVT::v4i32:
9271       case MVT::v2i64:
9272       case MVT::v4f32:
9273       case MVT::v2f64:
9274         return std::make_pair(0U, X86::VR128RegisterClass);
9275       }
9276       break;
9277     }
9278   }
9279
9280   // Use the default implementation in TargetLowering to convert the register
9281   // constraint into a member of a register class.
9282   std::pair<unsigned, const TargetRegisterClass*> Res;
9283   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9284
9285   // Not found as a standard register?
9286   if (Res.second == 0) {
9287     // GCC calls "st(0)" just plain "st".
9288     if (StringsEqualNoCase("{st}", Constraint)) {
9289       Res.first = X86::ST0;
9290       Res.second = X86::RFP80RegisterClass;
9291     }
9292     // 'A' means EAX + EDX.
9293     if (Constraint == "A") {
9294       Res.first = X86::EAX;
9295       Res.second = X86::GR32_ADRegisterClass;
9296     }
9297     return Res;
9298   }
9299
9300   // Otherwise, check to see if this is a register class of the wrong value
9301   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9302   // turn into {ax},{dx}.
9303   if (Res.second->hasType(VT))
9304     return Res;   // Correct type already, nothing to do.
9305
9306   // All of the single-register GCC register classes map their values onto
9307   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
9308   // really want an 8-bit or 32-bit register, map to the appropriate register
9309   // class and return the appropriate register.
9310   if (Res.second == X86::GR16RegisterClass) {
9311     if (VT == MVT::i8) {
9312       unsigned DestReg = 0;
9313       switch (Res.first) {
9314       default: break;
9315       case X86::AX: DestReg = X86::AL; break;
9316       case X86::DX: DestReg = X86::DL; break;
9317       case X86::CX: DestReg = X86::CL; break;
9318       case X86::BX: DestReg = X86::BL; break;
9319       }
9320       if (DestReg) {
9321         Res.first = DestReg;
9322         Res.second = X86::GR8RegisterClass;
9323       }
9324     } else if (VT == MVT::i32) {
9325       unsigned DestReg = 0;
9326       switch (Res.first) {
9327       default: break;
9328       case X86::AX: DestReg = X86::EAX; break;
9329       case X86::DX: DestReg = X86::EDX; break;
9330       case X86::CX: DestReg = X86::ECX; break;
9331       case X86::BX: DestReg = X86::EBX; break;
9332       case X86::SI: DestReg = X86::ESI; break;
9333       case X86::DI: DestReg = X86::EDI; break;
9334       case X86::BP: DestReg = X86::EBP; break;
9335       case X86::SP: DestReg = X86::ESP; break;
9336       }
9337       if (DestReg) {
9338         Res.first = DestReg;
9339         Res.second = X86::GR32RegisterClass;
9340       }
9341     } else if (VT == MVT::i64) {
9342       unsigned DestReg = 0;
9343       switch (Res.first) {
9344       default: break;
9345       case X86::AX: DestReg = X86::RAX; break;
9346       case X86::DX: DestReg = X86::RDX; break;
9347       case X86::CX: DestReg = X86::RCX; break;
9348       case X86::BX: DestReg = X86::RBX; break;
9349       case X86::SI: DestReg = X86::RSI; break;
9350       case X86::DI: DestReg = X86::RDI; break;
9351       case X86::BP: DestReg = X86::RBP; break;
9352       case X86::SP: DestReg = X86::RSP; break;
9353       }
9354       if (DestReg) {
9355         Res.first = DestReg;
9356         Res.second = X86::GR64RegisterClass;
9357       }
9358     }
9359   } else if (Res.second == X86::FR32RegisterClass ||
9360              Res.second == X86::FR64RegisterClass ||
9361              Res.second == X86::VR128RegisterClass) {
9362     // Handle references to XMM physical registers that got mapped into the
9363     // wrong class.  This can happen with constraints like {xmm0} where the
9364     // target independent register mapper will just pick the first match it can
9365     // find, ignoring the required type.
9366     if (VT == MVT::f32)
9367       Res.second = X86::FR32RegisterClass;
9368     else if (VT == MVT::f64)
9369       Res.second = X86::FR64RegisterClass;
9370     else if (X86::VR128RegisterClass->hasType(VT))
9371       Res.second = X86::VR128RegisterClass;
9372   }
9373
9374   return Res;
9375 }
9376
9377 //===----------------------------------------------------------------------===//
9378 //                           X86 Widen vector type
9379 //===----------------------------------------------------------------------===//
9380
9381 /// getWidenVectorType: given a vector type, returns the type to widen
9382 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9383 /// If there is no vector type that we want to widen to, returns MVT::Other
9384 /// When and where to widen is target dependent based on the cost of
9385 /// scalarizing vs using the wider vector type.
9386
9387 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9388   assert(VT.isVector());
9389   if (isTypeLegal(VT))
9390     return VT;
9391
9392   // TODO: In computeRegisterProperty, we can compute the list of legal vector
9393   //       type based on element type.  This would speed up our search (though
9394   //       it may not be worth it since the size of the list is relatively
9395   //       small).
9396   EVT EltVT = VT.getVectorElementType();
9397   unsigned NElts = VT.getVectorNumElements();
9398
9399   // On X86, it make sense to widen any vector wider than 1
9400   if (NElts <= 1)
9401     return MVT::Other;
9402
9403   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9404        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9405     EVT SVT = (MVT::SimpleValueType)nVT;
9406
9407     if (isTypeLegal(SVT) &&
9408         SVT.getVectorElementType() == EltVT &&
9409         SVT.getVectorNumElements() > NElts)
9410       return SVT;
9411   }
9412   return MVT::Other;
9413 }