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