implement X86 @GOTOFF jump table entries with the new EK_Custom32
[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 "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/VectorExtras.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 using namespace llvm;
50
51 static cl::opt<bool>
52 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
53
54 // Disable16Bit - 16-bit operations typically have a larger encoding than
55 // corresponding 32-bit instructions, and 16-bit code is slow on some
56 // processors. This is an experimental flag to disable 16-bit operations
57 // (which forces them to be Legalized to 32-bit operations).
58 static cl::opt<bool>
59 Disable16Bit("disable-16bit", cl::Hidden,
60              cl::desc("Disable use of 16-bit instructions"));
61
62 // Forward declarations.
63 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64                        SDValue V2);
65
66 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
68   default: llvm_unreachable("unknown subtarget type");
69   case X86Subtarget::isDarwin:
70     if (TM.getSubtarget<X86Subtarget>().is64Bit())
71       return new X8664_MachoTargetObjectFile();
72     return new X8632_MachoTargetObjectFile();
73   case X86Subtarget::isELF:
74     return new TargetLoweringObjectFileELF();
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80
81 }
82
83 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
84   : TargetLowering(TM, createTLOF(TM)) {
85   Subtarget = &TM.getSubtarget<X86Subtarget>();
86   X86ScalarSSEf64 = Subtarget->hasSSE2();
87   X86ScalarSSEf32 = Subtarget->hasSSE1();
88   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89
90   RegInfo = TM.getRegisterInfo();
91   TD = getTargetData();
92
93   // Set up the TargetLowering object.
94
95   // X86 is weird, it always uses i8 for shift amounts and setcc results.
96   setShiftAmountType(MVT::i8);
97   setBooleanContents(ZeroOrOneBooleanContent);
98   setSchedulingPreference(SchedulingForRegPressure);
99   setStackPointerRegisterToSaveRestore(X86StackPtr);
100
101   if (Subtarget->isTargetDarwin()) {
102     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
103     setUseUnderscoreSetJmp(false);
104     setUseUnderscoreLongJmp(false);
105   } else if (Subtarget->isTargetMingw()) {
106     // MS runtime is weird: it exports _setjmp, but longjmp!
107     setUseUnderscoreSetJmp(true);
108     setUseUnderscoreLongJmp(false);
109   } else {
110     setUseUnderscoreSetJmp(true);
111     setUseUnderscoreLongJmp(true);
112   }
113
114   // Set up the register classes.
115   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
116   if (!Disable16Bit)
117     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
118   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
119   if (Subtarget->is64Bit())
120     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
121
122   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
123
124   // We don't accept any truncstore of integer registers.
125   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
126   if (!Disable16Bit)
127     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
128   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
129   if (!Disable16Bit)
130     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
131   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
132   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
133
134   // SETOEQ and SETUNE require checking two conditions.
135   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
136   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
137   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
138   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
139   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
140   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
141
142   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
143   // operation.
144   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
145   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
146   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
147
148   if (Subtarget->is64Bit()) {
149     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
150     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
151   } else if (!UseSoftFloat) {
152     if (X86ScalarSSEf64) {
153       // We have an impenetrably clever algorithm for ui64->double only.
154       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
155     }
156     // We have an algorithm for SSE2, and we turn this into a 64-bit
157     // FILD for other targets.
158     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
159   }
160
161   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
162   // this operation.
163   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
164   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
165
166   if (!UseSoftFloat) {
167     // SSE has no i16 to fp conversion, only i32
168     if (X86ScalarSSEf32) {
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
170       // f32 and f64 cases are Legal, f80 case is not
171       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
172     } else {
173       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
174       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
175     }
176   } else {
177     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
178     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
179   }
180
181   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
182   // are Legal, f80 is custom lowered.
183   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
184   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
185
186   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
187   // this operation.
188   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
189   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
190
191   if (X86ScalarSSEf32) {
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
193     // f32 and f64 cases are Legal, f80 case is not
194     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
195   } else {
196     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
197     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
198   }
199
200   // Handle FP_TO_UINT by promoting the destination to a larger signed
201   // conversion.
202   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
203   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
204   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
205
206   if (Subtarget->is64Bit()) {
207     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
208     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
209   } else if (!UseSoftFloat) {
210     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
211       // Expand FP_TO_UINT into a select.
212       // FIXME: We would like to use a Custom expander here eventually to do
213       // the optimal thing for SSE vs. the default expansion in the legalizer.
214       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
215     else
216       // With SSE3 we can use fisttpll to convert to a signed i64; without
217       // SSE, we're stuck with a fistpll.
218       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
219   }
220
221   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
222   if (!X86ScalarSSEf64) {
223     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
224     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
225   }
226
227   // Scalar integer divide and remainder are lowered to use operations that
228   // produce two results, to match the available instructions. This exposes
229   // the two-result form to trivial CSE, which is able to combine x/y and x%y
230   // into a single instruction.
231   //
232   // Scalar integer multiply-high is also lowered to use two-result
233   // operations, to match the available instructions. However, plain multiply
234   // (low) operations are left as Legal, as there are single-result
235   // instructions for this in x86. Using the two-result multiply instructions
236   // when both high and low results are needed must be arranged by dagcombine.
237   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
238   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
239   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
240   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
241   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
242   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
243   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
244   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
245   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
246   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
247   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
248   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
249   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
250   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
251   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
252   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
253   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
254   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
255   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
256   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
257   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
258   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
259   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
260   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
261
262   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
263   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
264   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
265   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
266   if (Subtarget->is64Bit())
267     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
268   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
270   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
271   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
272   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
273   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
274   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
275   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
276
277   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
278   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
279   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
280   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
281   if (Disable16Bit) {
282     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
283     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
284   } else {
285     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
286     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
287   }
288   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
289   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
290   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
291   if (Subtarget->is64Bit()) {
292     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
293     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
294     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
295   }
296
297   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
298   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
299
300   // These should be promoted to a larger select which is supported.
301   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
302   // X86 wants to expand cmov itself.
303   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
304   if (Disable16Bit)
305     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
306   else
307     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
308   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
309   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
310   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
311   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
312   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
313   if (Disable16Bit)
314     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
315   else
316     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
317   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
318   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
320   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
323     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
324   }
325   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
326
327   // Darwin ABI issue.
328   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
329   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
330   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
331   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
332   if (Subtarget->is64Bit())
333     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
335   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
338     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
339     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
340     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
341     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
342   }
343   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
345   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
346   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
349     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
350     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasSSE1())
354     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
355
356   if (!Subtarget->hasSSE2())
357     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
358
359   // Expand certain atomics
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
361   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
362   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
363   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
364
365   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
366   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
367   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
368   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
369
370   if (!Subtarget->is64Bit()) {
371     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
375     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
376     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
377     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
378   }
379
380   // FIXME - use subtarget debug flags
381   if (!Subtarget->isTargetDarwin() &&
382       !Subtarget->isTargetELF() &&
383       !Subtarget->isTargetCygMing()) {
384     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
385   }
386
387   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
388   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
389   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
390   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
391   if (Subtarget->is64Bit()) {
392     setExceptionPointerRegister(X86::RAX);
393     setExceptionSelectorRegister(X86::RDX);
394   } else {
395     setExceptionPointerRegister(X86::EAX);
396     setExceptionSelectorRegister(X86::EDX);
397   }
398   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
399   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
400
401   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
402
403   setOperationAction(ISD::TRAP, MVT::Other, Legal);
404
405   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
406   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
407   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
408   if (Subtarget->is64Bit()) {
409     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
410     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
411   } else {
412     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
413     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
414   }
415
416   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
417   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
418   if (Subtarget->is64Bit())
419     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
420   if (Subtarget->isTargetCygMing())
421     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
422   else
423     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
424
425   if (!UseSoftFloat && X86ScalarSSEf64) {
426     // f32 and f64 use SSE.
427     // Set up the FP register classes.
428     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
429     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
430
431     // Use ANDPD to simulate FABS.
432     setOperationAction(ISD::FABS , MVT::f64, Custom);
433     setOperationAction(ISD::FABS , MVT::f32, Custom);
434
435     // Use XORP to simulate FNEG.
436     setOperationAction(ISD::FNEG , MVT::f64, Custom);
437     setOperationAction(ISD::FNEG , MVT::f32, Custom);
438
439     // Use ANDPD and ORPD to simulate FCOPYSIGN.
440     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
441     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
442
443     // We don't support sin/cos/fmod
444     setOperationAction(ISD::FSIN , MVT::f64, Expand);
445     setOperationAction(ISD::FCOS , MVT::f64, Expand);
446     setOperationAction(ISD::FSIN , MVT::f32, Expand);
447     setOperationAction(ISD::FCOS , MVT::f32, Expand);
448
449     // Expand FP immediates into loads from the stack, except for the special
450     // cases we handle.
451     addLegalFPImmediate(APFloat(+0.0)); // xorpd
452     addLegalFPImmediate(APFloat(+0.0f)); // xorps
453   } else if (!UseSoftFloat && X86ScalarSSEf32) {
454     // Use SSE for f32, x87 for f64.
455     // Set up the FP register classes.
456     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
457     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
458
459     // Use ANDPS to simulate FABS.
460     setOperationAction(ISD::FABS , MVT::f32, Custom);
461
462     // Use XORP to simulate FNEG.
463     setOperationAction(ISD::FNEG , MVT::f32, Custom);
464
465     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
466
467     // Use ANDPS and ORPS to simulate FCOPYSIGN.
468     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
469     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
470
471     // We don't support sin/cos/fmod
472     setOperationAction(ISD::FSIN , MVT::f32, Expand);
473     setOperationAction(ISD::FCOS , MVT::f32, Expand);
474
475     // Special cases we handle for FP constants.
476     addLegalFPImmediate(APFloat(+0.0f)); // xorps
477     addLegalFPImmediate(APFloat(+0.0)); // FLD0
478     addLegalFPImmediate(APFloat(+1.0)); // FLD1
479     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
480     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
481
482     if (!UnsafeFPMath) {
483       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
484       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
485     }
486   } else if (!UseSoftFloat) {
487     // f32 and f64 in x87.
488     // Set up the FP register classes.
489     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
490     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
491
492     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
493     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
494     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
495     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
496
497     if (!UnsafeFPMath) {
498       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
499       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
500     }
501     addLegalFPImmediate(APFloat(+0.0)); // FLD0
502     addLegalFPImmediate(APFloat(+1.0)); // FLD1
503     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
504     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
505     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
506     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
507     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
508     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
509   }
510
511   // Long double always uses X87.
512   if (!UseSoftFloat) {
513     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
514     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
515     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
516     {
517       bool ignored;
518       APFloat TmpFlt(+0.0);
519       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
520                      &ignored);
521       addLegalFPImmediate(TmpFlt);  // FLD0
522       TmpFlt.changeSign();
523       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
524       APFloat TmpFlt2(+1.0);
525       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
526                       &ignored);
527       addLegalFPImmediate(TmpFlt2);  // FLD1
528       TmpFlt2.changeSign();
529       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
530     }
531
532     if (!UnsafeFPMath) {
533       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
534       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
535     }
536   }
537
538   // Always use a library call for pow.
539   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
540   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
541   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
542
543   setOperationAction(ISD::FLOG, MVT::f80, Expand);
544   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
545   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
546   setOperationAction(ISD::FEXP, MVT::f80, Expand);
547   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
548
549   // First set operation action for all vector types to either promote
550   // (for widening) or expand (for scalarization). Then we will selectively
551   // turn on ones that can be effectively codegen'd.
552   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
553        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
554     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
569     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
570     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
603     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
607     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
608          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
609       setTruncStoreAction((MVT::SimpleValueType)VT,
610                           (MVT::SimpleValueType)InnerVT, Expand);
611     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
612     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
613     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
614   }
615
616   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
617   // with -msoft-float, disable use of MMX as well.
618   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
619     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
620     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
621     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
622     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
623     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
624
625     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
626     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
627     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
628     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
629
630     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
631     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
632     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
633     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
634
635     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
636     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
637
638     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
639     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
640     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
641     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
642     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
643     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
644     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
645
646     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
647     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
648     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
649     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
650     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
651     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
652     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
653
654     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
655     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
656     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
657     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
658     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
659     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
660     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
661
662     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
663     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
664     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
665     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
666     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
667     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
668     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
669     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
670     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
671
672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
673     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
674     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
675     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
676     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
677
678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
679     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
680     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
681     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
682
683     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
684     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
685     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
686     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
687
688     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
689
690     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
691     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
692     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
693     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
694     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
695     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
696     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
697   }
698
699   if (!UseSoftFloat && Subtarget->hasSSE1()) {
700     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
701
702     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
703     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
704     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
705     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
706     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
707     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
708     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
709     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
710     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
711     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
712     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
713     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
714   }
715
716   if (!UseSoftFloat && Subtarget->hasSSE2()) {
717     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
718
719     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
720     // registers cannot be used even for integer operations.
721     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
722     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
723     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
724     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
725
726     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
727     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
728     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
729     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
730     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
731     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
732     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
733     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
734     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
735     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
736     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
737     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
738     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
739     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
740     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
741     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
742
743     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
744     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
745     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
747
748     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
749     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
753
754     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
755     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
756     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
757     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
759
760     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
761     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
762       EVT VT = (MVT::SimpleValueType)i;
763       // Do not attempt to custom lower non-power-of-2 vectors
764       if (!isPowerOf2_32(VT.getVectorNumElements()))
765         continue;
766       // Do not attempt to custom lower non-128-bit vectors
767       if (!VT.is128BitVector())
768         continue;
769       setOperationAction(ISD::BUILD_VECTOR,
770                          VT.getSimpleVT().SimpleTy, Custom);
771       setOperationAction(ISD::VECTOR_SHUFFLE,
772                          VT.getSimpleVT().SimpleTy, Custom);
773       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
774                          VT.getSimpleVT().SimpleTy, Custom);
775     }
776
777     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
780     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
781     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
782     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
783
784     if (Subtarget->is64Bit()) {
785       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
786       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
787     }
788
789     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
790     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
791       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
792       EVT VT = SVT;
793
794       // Do not attempt to promote non-128-bit vectors
795       if (!VT.is128BitVector()) {
796         continue;
797       }
798       setOperationAction(ISD::AND,    SVT, Promote);
799       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
800       setOperationAction(ISD::OR,     SVT, Promote);
801       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
802       setOperationAction(ISD::XOR,    SVT, Promote);
803       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
804       setOperationAction(ISD::LOAD,   SVT, Promote);
805       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
806       setOperationAction(ISD::SELECT, SVT, Promote);
807       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
808     }
809
810     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
811
812     // Custom lower v2i64 and v2f64 selects.
813     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
814     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
815     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
816     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
817
818     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
819     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
820     if (!DisableMMX && Subtarget->hasMMX()) {
821       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
822       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
823     }
824   }
825
826   if (Subtarget->hasSSE41()) {
827     // FIXME: Do we need to handle scalar-to-vector here?
828     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
829
830     // i8 and i16 vectors are custom , because the source register and source
831     // source memory operand types are not the same width.  f32 vectors are
832     // custom since the immediate controlling the insert encodes additional
833     // information.
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
835     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
838
839     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
840     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
841     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
842     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
843
844     if (Subtarget->is64Bit()) {
845       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
846       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
847     }
848   }
849
850   if (Subtarget->hasSSE42()) {
851     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
852   }
853
854   if (!UseSoftFloat && Subtarget->hasAVX()) {
855     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
856     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
857     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
858     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
859
860     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
861     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
862     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
863     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
864     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
865     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
866     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
867     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
868     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
869     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
870     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
871     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
872     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
873     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
874     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
875
876     // Operations to consider commented out -v16i16 v32i8
877     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
878     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
879     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
880     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
881     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
882     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
883     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
884     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
885     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
886     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
887     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
888     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
889     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
890     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
891
892     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
893     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
894     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
895     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
896
897     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
898     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
899     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
900     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
901     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
902
903     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
904     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
905     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
906     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
907     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
908     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
909
910 #if 0
911     // Not sure we want to do this since there are no 256-bit integer
912     // operations in AVX
913
914     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
915     // This includes 256-bit vectors
916     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
917       EVT VT = (MVT::SimpleValueType)i;
918
919       // Do not attempt to custom lower non-power-of-2 vectors
920       if (!isPowerOf2_32(VT.getVectorNumElements()))
921         continue;
922
923       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
924       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
925       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
926     }
927
928     if (Subtarget->is64Bit()) {
929       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
930       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
931     }
932 #endif
933
934 #if 0
935     // Not sure we want to do this since there are no 256-bit integer
936     // operations in AVX
937
938     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
939     // Including 256-bit vectors
940     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
941       EVT VT = (MVT::SimpleValueType)i;
942
943       if (!VT.is256BitVector()) {
944         continue;
945       }
946       setOperationAction(ISD::AND,    VT, Promote);
947       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
948       setOperationAction(ISD::OR,     VT, Promote);
949       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
950       setOperationAction(ISD::XOR,    VT, Promote);
951       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
952       setOperationAction(ISD::LOAD,   VT, Promote);
953       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
954       setOperationAction(ISD::SELECT, VT, Promote);
955       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
956     }
957
958     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
959 #endif
960   }
961
962   // We want to custom lower some of our intrinsics.
963   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
964
965   // Add/Sub/Mul with overflow operations are custom lowered.
966   setOperationAction(ISD::SADDO, MVT::i32, Custom);
967   setOperationAction(ISD::SADDO, MVT::i64, Custom);
968   setOperationAction(ISD::UADDO, MVT::i32, Custom);
969   setOperationAction(ISD::UADDO, MVT::i64, Custom);
970   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
971   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
972   setOperationAction(ISD::USUBO, MVT::i32, Custom);
973   setOperationAction(ISD::USUBO, MVT::i64, Custom);
974   setOperationAction(ISD::SMULO, MVT::i32, Custom);
975   setOperationAction(ISD::SMULO, MVT::i64, Custom);
976
977   if (!Subtarget->is64Bit()) {
978     // These libcalls are not available in 32-bit.
979     setLibcallName(RTLIB::SHL_I128, 0);
980     setLibcallName(RTLIB::SRL_I128, 0);
981     setLibcallName(RTLIB::SRA_I128, 0);
982   }
983
984   // We have target-specific dag combine patterns for the following nodes:
985   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
986   setTargetDAGCombine(ISD::BUILD_VECTOR);
987   setTargetDAGCombine(ISD::SELECT);
988   setTargetDAGCombine(ISD::SHL);
989   setTargetDAGCombine(ISD::SRA);
990   setTargetDAGCombine(ISD::SRL);
991   setTargetDAGCombine(ISD::OR);
992   setTargetDAGCombine(ISD::STORE);
993   setTargetDAGCombine(ISD::MEMBARRIER);
994   setTargetDAGCombine(ISD::ZERO_EXTEND);
995   if (Subtarget->is64Bit())
996     setTargetDAGCombine(ISD::MUL);
997
998   computeRegisterProperties();
999
1000   // Divide and reminder operations have no vector equivalent and can
1001   // trap. Do a custom widening for these operations in which we never
1002   // generate more divides/remainder than the original vector width.
1003   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1004        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1005     if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1006       setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1007       setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1008       setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1009       setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1010     }
1011   }
1012
1013   // FIXME: These should be based on subtarget info. Plus, the values should
1014   // be smaller when we are in optimizing for size mode.
1015   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1016   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1017   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1018   setPrefLoopAlignment(16);
1019   benefitFromCodePlacementOpt = true;
1020 }
1021
1022
1023 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1024   return MVT::i8;
1025 }
1026
1027
1028 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1029 /// the desired ByVal argument alignment.
1030 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1031   if (MaxAlign == 16)
1032     return;
1033   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1034     if (VTy->getBitWidth() == 128)
1035       MaxAlign = 16;
1036   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1037     unsigned EltAlign = 0;
1038     getMaxByValAlign(ATy->getElementType(), EltAlign);
1039     if (EltAlign > MaxAlign)
1040       MaxAlign = EltAlign;
1041   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1042     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1043       unsigned EltAlign = 0;
1044       getMaxByValAlign(STy->getElementType(i), EltAlign);
1045       if (EltAlign > MaxAlign)
1046         MaxAlign = EltAlign;
1047       if (MaxAlign == 16)
1048         break;
1049     }
1050   }
1051   return;
1052 }
1053
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area. For X86, aggregates
1056 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1057 /// are at 4-byte boundaries.
1058 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1059   if (Subtarget->is64Bit()) {
1060     // Max of 8 and alignment of type.
1061     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1062     if (TyAlign > 8)
1063       return TyAlign;
1064     return 8;
1065   }
1066
1067   unsigned Align = 4;
1068   if (Subtarget->hasSSE1())
1069     getMaxByValAlign(Ty, Align);
1070   return Align;
1071 }
1072
1073 /// getOptimalMemOpType - Returns the target specific optimal type for load
1074 /// and store operations as a result of memset, memcpy, and memmove
1075 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1076 /// determining it.
1077 EVT
1078 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1079                                        bool isSrcConst, bool isSrcStr,
1080                                        SelectionDAG &DAG) const {
1081   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1082   // linux.  This is because the stack realignment code can't handle certain
1083   // cases like PR2962.  This should be removed when PR2962 is fixed.
1084   const Function *F = DAG.getMachineFunction().getFunction();
1085   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1086   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1087     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1088       return MVT::v4i32;
1089     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1090       return MVT::v4f32;
1091   }
1092   if (Subtarget->is64Bit() && Size >= 8)
1093     return MVT::i64;
1094   return MVT::i32;
1095 }
1096
1097 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1098 /// current function.  The returned value is a member of the
1099 /// MachineJumpTableInfo::JTEntryKind enum.
1100 unsigned X86TargetLowering::getJumpTableEncoding() const {
1101   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1102   // symbol.
1103   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1104       Subtarget->isPICStyleGOT())
1105     return MachineJumpTableInfo::EK_Custom32;
1106   
1107   // Otherwise, use the normal jump table encoding heuristics.
1108   return TargetLowering::getJumpTableEncoding();
1109 }
1110
1111 const MCExpr *
1112 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1113                                              const MachineBasicBlock *MBB,
1114                                              unsigned uid,MCContext &Ctx) const{
1115   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1116          Subtarget->isPICStyleGOT());
1117   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1118   // entries.
1119
1120   // FIXME: @GOTOFF should be a property of MCSymbolRefExpr not in the MCSymbol.
1121   std::string Name = MBB->getSymbol(Ctx)->getName() + "@GOTOFF";
1122   return MCSymbolRefExpr::Create(Ctx.GetOrCreateSymbol(StringRef(Name)), Ctx);
1123 }
1124
1125 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1126 /// jumptable.
1127 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1128                                                       SelectionDAG &DAG) const {
1129   if (!Subtarget->is64Bit())
1130     // This doesn't have DebugLoc associated with it, but is not really the
1131     // same as a Register.
1132     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1133                        getPointerTy());
1134   return Table;
1135 }
1136
1137 /// getFunctionAlignment - Return the Log2 alignment of this function.
1138 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1139   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1140 }
1141
1142 //===----------------------------------------------------------------------===//
1143 //               Return Value Calling Convention Implementation
1144 //===----------------------------------------------------------------------===//
1145
1146 #include "X86GenCallingConv.inc"
1147
1148 bool 
1149 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1150                         const SmallVectorImpl<EVT> &OutTys,
1151                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1152                         SelectionDAG &DAG) {
1153   SmallVector<CCValAssign, 16> RVLocs;
1154   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1155                  RVLocs, *DAG.getContext());
1156   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1157 }
1158
1159 SDValue
1160 X86TargetLowering::LowerReturn(SDValue Chain,
1161                                CallingConv::ID CallConv, bool isVarArg,
1162                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1163                                DebugLoc dl, SelectionDAG &DAG) {
1164
1165   SmallVector<CCValAssign, 16> RVLocs;
1166   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1167                  RVLocs, *DAG.getContext());
1168   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1169
1170   // If this is the first return lowered for this function, add the regs to the
1171   // liveout set for the function.
1172   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1173     for (unsigned i = 0; i != RVLocs.size(); ++i)
1174       if (RVLocs[i].isRegLoc())
1175         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1176   }
1177
1178   SDValue Flag;
1179
1180   SmallVector<SDValue, 6> RetOps;
1181   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1182   // Operand #1 = Bytes To Pop
1183   RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1184
1185   // Copy the result values into the output registers.
1186   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1187     CCValAssign &VA = RVLocs[i];
1188     assert(VA.isRegLoc() && "Can only return in registers!");
1189     SDValue ValToCopy = Outs[i].Val;
1190
1191     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1192     // the RET instruction and handled by the FP Stackifier.
1193     if (VA.getLocReg() == X86::ST0 ||
1194         VA.getLocReg() == X86::ST1) {
1195       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1196       // change the value to the FP stack register class.
1197       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1198         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1199       RetOps.push_back(ValToCopy);
1200       // Don't emit a copytoreg.
1201       continue;
1202     }
1203
1204     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1205     // which is returned in RAX / RDX.
1206     if (Subtarget->is64Bit()) {
1207       EVT ValVT = ValToCopy.getValueType();
1208       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1209         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1210         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1211           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1212       }
1213     }
1214
1215     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1216     Flag = Chain.getValue(1);
1217   }
1218
1219   // The x86-64 ABI for returning structs by value requires that we copy
1220   // the sret argument into %rax for the return. We saved the argument into
1221   // a virtual register in the entry block, so now we copy the value out
1222   // and into %rax.
1223   if (Subtarget->is64Bit() &&
1224       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1225     MachineFunction &MF = DAG.getMachineFunction();
1226     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1227     unsigned Reg = FuncInfo->getSRetReturnReg();
1228     if (!Reg) {
1229       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1230       FuncInfo->setSRetReturnReg(Reg);
1231     }
1232     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1233
1234     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1235     Flag = Chain.getValue(1);
1236
1237     // RAX now acts like a return value.
1238     MF.getRegInfo().addLiveOut(X86::RAX);
1239   }
1240
1241   RetOps[0] = Chain;  // Update chain.
1242
1243   // Add the flag if we have it.
1244   if (Flag.getNode())
1245     RetOps.push_back(Flag);
1246
1247   return DAG.getNode(X86ISD::RET_FLAG, dl,
1248                      MVT::Other, &RetOps[0], RetOps.size());
1249 }
1250
1251 /// LowerCallResult - Lower the result values of a call into the
1252 /// appropriate copies out of appropriate physical registers.
1253 ///
1254 SDValue
1255 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1256                                    CallingConv::ID CallConv, bool isVarArg,
1257                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1258                                    DebugLoc dl, SelectionDAG &DAG,
1259                                    SmallVectorImpl<SDValue> &InVals) {
1260
1261   // Assign locations to each value returned by this call.
1262   SmallVector<CCValAssign, 16> RVLocs;
1263   bool Is64Bit = Subtarget->is64Bit();
1264   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1265                  RVLocs, *DAG.getContext());
1266   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1267
1268   // Copy all of the result registers out of their specified physreg.
1269   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1270     CCValAssign &VA = RVLocs[i];
1271     EVT CopyVT = VA.getValVT();
1272
1273     // If this is x86-64, and we disabled SSE, we can't return FP values
1274     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1275         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1276       llvm_report_error("SSE register return with SSE disabled");
1277     }
1278
1279     // If this is a call to a function that returns an fp value on the floating
1280     // point stack, but where we prefer to use the value in xmm registers, copy
1281     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1282     if ((VA.getLocReg() == X86::ST0 ||
1283          VA.getLocReg() == X86::ST1) &&
1284         isScalarFPTypeInSSEReg(VA.getValVT())) {
1285       CopyVT = MVT::f80;
1286     }
1287
1288     SDValue Val;
1289     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1290       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1291       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1292         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1293                                    MVT::v2i64, InFlag).getValue(1);
1294         Val = Chain.getValue(0);
1295         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1296                           Val, DAG.getConstant(0, MVT::i64));
1297       } else {
1298         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1299                                    MVT::i64, InFlag).getValue(1);
1300         Val = Chain.getValue(0);
1301       }
1302       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1303     } else {
1304       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1305                                  CopyVT, InFlag).getValue(1);
1306       Val = Chain.getValue(0);
1307     }
1308     InFlag = Chain.getValue(2);
1309
1310     if (CopyVT != VA.getValVT()) {
1311       // Round the F80 the right size, which also moves to the appropriate xmm
1312       // register.
1313       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1314                         // This truncation won't change the value.
1315                         DAG.getIntPtrConstant(1));
1316     }
1317
1318     InVals.push_back(Val);
1319   }
1320
1321   return Chain;
1322 }
1323
1324
1325 //===----------------------------------------------------------------------===//
1326 //                C & StdCall & Fast Calling Convention implementation
1327 //===----------------------------------------------------------------------===//
1328 //  StdCall calling convention seems to be standard for many Windows' API
1329 //  routines and around. It differs from C calling convention just a little:
1330 //  callee should clean up the stack, not caller. Symbols should be also
1331 //  decorated in some fancy way :) It doesn't support any vector arguments.
1332 //  For info on fast calling convention see Fast Calling Convention (tail call)
1333 //  implementation LowerX86_32FastCCCallTo.
1334
1335 /// CallIsStructReturn - Determines whether a call uses struct return
1336 /// semantics.
1337 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1338   if (Outs.empty())
1339     return false;
1340
1341   return Outs[0].Flags.isSRet();
1342 }
1343
1344 /// ArgsAreStructReturn - Determines whether a function uses struct
1345 /// return semantics.
1346 static bool
1347 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1348   if (Ins.empty())
1349     return false;
1350
1351   return Ins[0].Flags.isSRet();
1352 }
1353
1354 /// IsCalleePop - Determines whether the callee is required to pop its
1355 /// own arguments. Callee pop is necessary to support tail calls.
1356 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1357   if (IsVarArg)
1358     return false;
1359
1360   switch (CallingConv) {
1361   default:
1362     return false;
1363   case CallingConv::X86_StdCall:
1364     return !Subtarget->is64Bit();
1365   case CallingConv::X86_FastCall:
1366     return !Subtarget->is64Bit();
1367   case CallingConv::Fast:
1368     return PerformTailCallOpt;
1369   }
1370 }
1371
1372 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1373 /// given CallingConvention value.
1374 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1375   if (Subtarget->is64Bit()) {
1376     if (Subtarget->isTargetWin64())
1377       return CC_X86_Win64_C;
1378     else
1379       return CC_X86_64_C;
1380   }
1381
1382   if (CC == CallingConv::X86_FastCall)
1383     return CC_X86_32_FastCall;
1384   else if (CC == CallingConv::Fast)
1385     return CC_X86_32_FastCC;
1386   else
1387     return CC_X86_32_C;
1388 }
1389
1390 /// NameDecorationForCallConv - Selects the appropriate decoration to
1391 /// apply to a MachineFunction containing a given calling convention.
1392 NameDecorationStyle
1393 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1394   if (CallConv == CallingConv::X86_FastCall)
1395     return FastCall;
1396   else if (CallConv == CallingConv::X86_StdCall)
1397     return StdCall;
1398   return None;
1399 }
1400
1401
1402 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1403 /// by "Src" to address "Dst" with size and alignment information specified by
1404 /// the specific parameter attribute. The copy will be passed as a byval
1405 /// function parameter.
1406 static SDValue
1407 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1408                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1409                           DebugLoc dl) {
1410   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1411   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1412                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1413 }
1414
1415 SDValue
1416 X86TargetLowering::LowerMemArgument(SDValue Chain,
1417                                     CallingConv::ID CallConv,
1418                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1419                                     DebugLoc dl, SelectionDAG &DAG,
1420                                     const CCValAssign &VA,
1421                                     MachineFrameInfo *MFI,
1422                                     unsigned i) {
1423
1424   // Create the nodes corresponding to a load from this parameter slot.
1425   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1426   bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1427   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1428   EVT ValVT;
1429
1430   // If value is passed by pointer we have address passed instead of the value
1431   // itself.
1432   if (VA.getLocInfo() == CCValAssign::Indirect)
1433     ValVT = VA.getLocVT();
1434   else
1435     ValVT = VA.getValVT();
1436
1437   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1438   // changed with more analysis.
1439   // In case of tail call optimization mark all arguments mutable. Since they
1440   // could be overwritten by lowering of arguments in case of a tail call.
1441   int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1442                                   VA.getLocMemOffset(), isImmutable, false);
1443   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1444   if (Flags.isByVal())
1445     return FIN;
1446   return DAG.getLoad(ValVT, dl, Chain, FIN,
1447                      PseudoSourceValue::getFixedStack(FI), 0);
1448 }
1449
1450 SDValue
1451 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1452                                         CallingConv::ID CallConv,
1453                                         bool isVarArg,
1454                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1455                                         DebugLoc dl,
1456                                         SelectionDAG &DAG,
1457                                         SmallVectorImpl<SDValue> &InVals) {
1458
1459   MachineFunction &MF = DAG.getMachineFunction();
1460   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1461
1462   const Function* Fn = MF.getFunction();
1463   if (Fn->hasExternalLinkage() &&
1464       Subtarget->isTargetCygMing() &&
1465       Fn->getName() == "main")
1466     FuncInfo->setForceFramePointer(true);
1467
1468   // Decorate the function name.
1469   FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1470
1471   MachineFrameInfo *MFI = MF.getFrameInfo();
1472   bool Is64Bit = Subtarget->is64Bit();
1473   bool IsWin64 = Subtarget->isTargetWin64();
1474
1475   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1476          "Var args not supported with calling convention fastcc");
1477
1478   // Assign locations to all of the incoming arguments.
1479   SmallVector<CCValAssign, 16> ArgLocs;
1480   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1481                  ArgLocs, *DAG.getContext());
1482   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1483
1484   unsigned LastVal = ~0U;
1485   SDValue ArgValue;
1486   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1487     CCValAssign &VA = ArgLocs[i];
1488     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1489     // places.
1490     assert(VA.getValNo() != LastVal &&
1491            "Don't support value assigned to multiple locs yet");
1492     LastVal = VA.getValNo();
1493
1494     if (VA.isRegLoc()) {
1495       EVT RegVT = VA.getLocVT();
1496       TargetRegisterClass *RC = NULL;
1497       if (RegVT == MVT::i32)
1498         RC = X86::GR32RegisterClass;
1499       else if (Is64Bit && RegVT == MVT::i64)
1500         RC = X86::GR64RegisterClass;
1501       else if (RegVT == MVT::f32)
1502         RC = X86::FR32RegisterClass;
1503       else if (RegVT == MVT::f64)
1504         RC = X86::FR64RegisterClass;
1505       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1506         RC = X86::VR128RegisterClass;
1507       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1508         RC = X86::VR64RegisterClass;
1509       else
1510         llvm_unreachable("Unknown argument type!");
1511
1512       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1513       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1514
1515       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1516       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1517       // right size.
1518       if (VA.getLocInfo() == CCValAssign::SExt)
1519         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1520                                DAG.getValueType(VA.getValVT()));
1521       else if (VA.getLocInfo() == CCValAssign::ZExt)
1522         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1523                                DAG.getValueType(VA.getValVT()));
1524       else if (VA.getLocInfo() == CCValAssign::BCvt)
1525         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1526
1527       if (VA.isExtInLoc()) {
1528         // Handle MMX values passed in XMM regs.
1529         if (RegVT.isVector()) {
1530           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1531                                  ArgValue, DAG.getConstant(0, MVT::i64));
1532           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1533         } else
1534           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1535       }
1536     } else {
1537       assert(VA.isMemLoc());
1538       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1539     }
1540
1541     // If value is passed via pointer - do a load.
1542     if (VA.getLocInfo() == CCValAssign::Indirect)
1543       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1544
1545     InVals.push_back(ArgValue);
1546   }
1547
1548   // The x86-64 ABI for returning structs by value requires that we copy
1549   // the sret argument into %rax for the return. Save the argument into
1550   // a virtual register so that we can access it from the return points.
1551   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1552     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1553     unsigned Reg = FuncInfo->getSRetReturnReg();
1554     if (!Reg) {
1555       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1556       FuncInfo->setSRetReturnReg(Reg);
1557     }
1558     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1559     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1560   }
1561
1562   unsigned StackSize = CCInfo.getNextStackOffset();
1563   // align stack specially for tail calls
1564   if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1565     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1566
1567   // If the function takes variable number of arguments, make a frame index for
1568   // the start of the first vararg value... for expansion of llvm.va_start.
1569   if (isVarArg) {
1570     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1571       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1572     }
1573     if (Is64Bit) {
1574       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1575
1576       // FIXME: We should really autogenerate these arrays
1577       static const unsigned GPR64ArgRegsWin64[] = {
1578         X86::RCX, X86::RDX, X86::R8,  X86::R9
1579       };
1580       static const unsigned XMMArgRegsWin64[] = {
1581         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1582       };
1583       static const unsigned GPR64ArgRegs64Bit[] = {
1584         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1585       };
1586       static const unsigned XMMArgRegs64Bit[] = {
1587         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1588         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1589       };
1590       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1591
1592       if (IsWin64) {
1593         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1594         GPR64ArgRegs = GPR64ArgRegsWin64;
1595         XMMArgRegs = XMMArgRegsWin64;
1596       } else {
1597         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1598         GPR64ArgRegs = GPR64ArgRegs64Bit;
1599         XMMArgRegs = XMMArgRegs64Bit;
1600       }
1601       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1602                                                        TotalNumIntRegs);
1603       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1604                                                        TotalNumXMMRegs);
1605
1606       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1607       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1608              "SSE register cannot be used when SSE is disabled!");
1609       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1610              "SSE register cannot be used when SSE is disabled!");
1611       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1612         // Kernel mode asks for SSE to be disabled, so don't push them
1613         // on the stack.
1614         TotalNumXMMRegs = 0;
1615
1616       // For X86-64, if there are vararg parameters that are passed via
1617       // registers, then we must store them to their spots on the stack so they
1618       // may be loaded by deferencing the result of va_next.
1619       VarArgsGPOffset = NumIntRegs * 8;
1620       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1621       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1622                                                  TotalNumXMMRegs * 16, 16,
1623                                                  false);
1624
1625       // Store the integer parameter registers.
1626       SmallVector<SDValue, 8> MemOps;
1627       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1628       unsigned Offset = VarArgsGPOffset;
1629       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1630         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1631                                   DAG.getIntPtrConstant(Offset));
1632         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1633                                      X86::GR64RegisterClass);
1634         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1635         SDValue Store =
1636           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1637                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1638                        Offset);
1639         MemOps.push_back(Store);
1640         Offset += 8;
1641       }
1642
1643       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1644         // Now store the XMM (fp + vector) parameter registers.
1645         SmallVector<SDValue, 11> SaveXMMOps;
1646         SaveXMMOps.push_back(Chain);
1647
1648         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1649         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1650         SaveXMMOps.push_back(ALVal);
1651
1652         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1653         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1654
1655         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1656           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1657                                        X86::VR128RegisterClass);
1658           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1659           SaveXMMOps.push_back(Val);
1660         }
1661         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1662                                      MVT::Other,
1663                                      &SaveXMMOps[0], SaveXMMOps.size()));
1664       }
1665
1666       if (!MemOps.empty())
1667         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1668                             &MemOps[0], MemOps.size());
1669     }
1670   }
1671
1672   // Some CCs need callee pop.
1673   if (IsCalleePop(isVarArg, CallConv)) {
1674     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1675     BytesCallerReserves = 0;
1676   } else {
1677     BytesToPopOnReturn  = 0; // Callee pops nothing.
1678     // If this is an sret function, the return should pop the hidden pointer.
1679     if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1680       BytesToPopOnReturn = 4;
1681     BytesCallerReserves = StackSize;
1682   }
1683
1684   if (!Is64Bit) {
1685     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1686     if (CallConv == CallingConv::X86_FastCall)
1687       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1688   }
1689
1690   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1691
1692   return Chain;
1693 }
1694
1695 SDValue
1696 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1697                                     SDValue StackPtr, SDValue Arg,
1698                                     DebugLoc dl, SelectionDAG &DAG,
1699                                     const CCValAssign &VA,
1700                                     ISD::ArgFlagsTy Flags) {
1701   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1702   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1703   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1704   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1705   if (Flags.isByVal()) {
1706     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1707   }
1708   return DAG.getStore(Chain, dl, Arg, PtrOff,
1709                       PseudoSourceValue::getStack(), LocMemOffset);
1710 }
1711
1712 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1713 /// optimization is performed and it is required.
1714 SDValue
1715 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1716                                            SDValue &OutRetAddr,
1717                                            SDValue Chain,
1718                                            bool IsTailCall,
1719                                            bool Is64Bit,
1720                                            int FPDiff,
1721                                            DebugLoc dl) {
1722   if (!IsTailCall || FPDiff==0) return Chain;
1723
1724   // Adjust the Return address stack slot.
1725   EVT VT = getPointerTy();
1726   OutRetAddr = getReturnAddressFrameIndex(DAG);
1727
1728   // Load the "old" Return address.
1729   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1730   return SDValue(OutRetAddr.getNode(), 1);
1731 }
1732
1733 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1734 /// optimization is performed and it is required (FPDiff!=0).
1735 static SDValue
1736 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1737                          SDValue Chain, SDValue RetAddrFrIdx,
1738                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1739   // Store the return address to the appropriate stack slot.
1740   if (!FPDiff) return Chain;
1741   // Calculate the new stack slot for the return address.
1742   int SlotSize = Is64Bit ? 8 : 4;
1743   int NewReturnAddrFI =
1744     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1745                                          true, false);
1746   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1747   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1748   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1749                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1750   return Chain;
1751 }
1752
1753 SDValue
1754 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1755                              CallingConv::ID CallConv, bool isVarArg,
1756                              bool isTailCall,
1757                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1758                              const SmallVectorImpl<ISD::InputArg> &Ins,
1759                              DebugLoc dl, SelectionDAG &DAG,
1760                              SmallVectorImpl<SDValue> &InVals) {
1761
1762   MachineFunction &MF = DAG.getMachineFunction();
1763   bool Is64Bit        = Subtarget->is64Bit();
1764   bool IsStructRet    = CallIsStructReturn(Outs);
1765
1766   assert((!isTailCall ||
1767           (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1768          "IsEligibleForTailCallOptimization missed a case!");
1769   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1770          "Var args not supported with calling convention fastcc");
1771
1772   // Analyze operands of the call, assigning locations to each operand.
1773   SmallVector<CCValAssign, 16> ArgLocs;
1774   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1775                  ArgLocs, *DAG.getContext());
1776   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1777
1778   // Get a count of how many bytes are to be pushed on the stack.
1779   unsigned NumBytes = CCInfo.getNextStackOffset();
1780   if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1781     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1782
1783   int FPDiff = 0;
1784   if (isTailCall) {
1785     // Lower arguments at fp - stackoffset + fpdiff.
1786     unsigned NumBytesCallerPushed =
1787       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1788     FPDiff = NumBytesCallerPushed - NumBytes;
1789
1790     // Set the delta of movement of the returnaddr stackslot.
1791     // But only set if delta is greater than previous delta.
1792     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1793       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1794   }
1795
1796   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1797
1798   SDValue RetAddrFrIdx;
1799   // Load return adress for tail calls.
1800   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1801                                   FPDiff, dl);
1802
1803   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1804   SmallVector<SDValue, 8> MemOpChains;
1805   SDValue StackPtr;
1806
1807   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1808   // of tail call optimization arguments are handle later.
1809   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1810     CCValAssign &VA = ArgLocs[i];
1811     EVT RegVT = VA.getLocVT();
1812     SDValue Arg = Outs[i].Val;
1813     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1814     bool isByVal = Flags.isByVal();
1815
1816     // Promote the value if needed.
1817     switch (VA.getLocInfo()) {
1818     default: llvm_unreachable("Unknown loc info!");
1819     case CCValAssign::Full: break;
1820     case CCValAssign::SExt:
1821       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1822       break;
1823     case CCValAssign::ZExt:
1824       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1825       break;
1826     case CCValAssign::AExt:
1827       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1828         // Special case: passing MMX values in XMM registers.
1829         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1830         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1831         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1832       } else
1833         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1834       break;
1835     case CCValAssign::BCvt:
1836       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1837       break;
1838     case CCValAssign::Indirect: {
1839       // Store the argument.
1840       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1841       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1842       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1843                            PseudoSourceValue::getFixedStack(FI), 0);
1844       Arg = SpillSlot;
1845       break;
1846     }
1847     }
1848
1849     if (VA.isRegLoc()) {
1850       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1851     } else {
1852       if (!isTailCall || (isTailCall && isByVal)) {
1853         assert(VA.isMemLoc());
1854         if (StackPtr.getNode() == 0)
1855           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1856
1857         MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1858                                                dl, DAG, VA, Flags));
1859       }
1860     }
1861   }
1862
1863   if (!MemOpChains.empty())
1864     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1865                         &MemOpChains[0], MemOpChains.size());
1866
1867   // Build a sequence of copy-to-reg nodes chained together with token chain
1868   // and flag operands which copy the outgoing args into registers.
1869   SDValue InFlag;
1870   // Tail call byval lowering might overwrite argument registers so in case of
1871   // tail call optimization the copies to registers are lowered later.
1872   if (!isTailCall)
1873     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1874       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1875                                RegsToPass[i].second, InFlag);
1876       InFlag = Chain.getValue(1);
1877     }
1878
1879
1880   if (Subtarget->isPICStyleGOT()) {
1881     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1882     // GOT pointer.
1883     if (!isTailCall) {
1884       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1885                                DAG.getNode(X86ISD::GlobalBaseReg,
1886                                            DebugLoc::getUnknownLoc(),
1887                                            getPointerTy()),
1888                                InFlag);
1889       InFlag = Chain.getValue(1);
1890     } else {
1891       // If we are tail calling and generating PIC/GOT style code load the
1892       // address of the callee into ECX. The value in ecx is used as target of
1893       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1894       // for tail calls on PIC/GOT architectures. Normally we would just put the
1895       // address of GOT into ebx and then call target@PLT. But for tail calls
1896       // ebx would be restored (since ebx is callee saved) before jumping to the
1897       // target@PLT.
1898
1899       // Note: The actual moving to ECX is done further down.
1900       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1901       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1902           !G->getGlobal()->hasProtectedVisibility())
1903         Callee = LowerGlobalAddress(Callee, DAG);
1904       else if (isa<ExternalSymbolSDNode>(Callee))
1905         Callee = LowerExternalSymbol(Callee, DAG);
1906     }
1907   }
1908
1909   if (Is64Bit && isVarArg) {
1910     // From AMD64 ABI document:
1911     // For calls that may call functions that use varargs or stdargs
1912     // (prototype-less calls or calls to functions containing ellipsis (...) in
1913     // the declaration) %al is used as hidden argument to specify the number
1914     // of SSE registers used. The contents of %al do not need to match exactly
1915     // the number of registers, but must be an ubound on the number of SSE
1916     // registers used and is in the range 0 - 8 inclusive.
1917
1918     // FIXME: Verify this on Win64
1919     // Count the number of XMM registers allocated.
1920     static const unsigned XMMArgRegs[] = {
1921       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1922       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1923     };
1924     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1925     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1926            && "SSE registers cannot be used when SSE is disabled");
1927
1928     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1929                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1930     InFlag = Chain.getValue(1);
1931   }
1932
1933
1934   // For tail calls lower the arguments to the 'real' stack slot.
1935   if (isTailCall) {
1936     // Force all the incoming stack arguments to be loaded from the stack
1937     // before any new outgoing arguments are stored to the stack, because the
1938     // outgoing stack slots may alias the incoming argument stack slots, and
1939     // the alias isn't otherwise explicit. This is slightly more conservative
1940     // than necessary, because it means that each store effectively depends
1941     // on every argument instead of just those arguments it would clobber.
1942     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1943
1944     SmallVector<SDValue, 8> MemOpChains2;
1945     SDValue FIN;
1946     int FI = 0;
1947     // Do not flag preceeding copytoreg stuff together with the following stuff.
1948     InFlag = SDValue();
1949     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1950       CCValAssign &VA = ArgLocs[i];
1951       if (!VA.isRegLoc()) {
1952         assert(VA.isMemLoc());
1953         SDValue Arg = Outs[i].Val;
1954         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1955         // Create frame index.
1956         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1957         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1958         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1959         FIN = DAG.getFrameIndex(FI, getPointerTy());
1960
1961         if (Flags.isByVal()) {
1962           // Copy relative to framepointer.
1963           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1964           if (StackPtr.getNode() == 0)
1965             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1966                                           getPointerTy());
1967           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1968
1969           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1970                                                            ArgChain,
1971                                                            Flags, DAG, dl));
1972         } else {
1973           // Store relative to framepointer.
1974           MemOpChains2.push_back(
1975             DAG.getStore(ArgChain, dl, Arg, FIN,
1976                          PseudoSourceValue::getFixedStack(FI), 0));
1977         }
1978       }
1979     }
1980
1981     if (!MemOpChains2.empty())
1982       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1983                           &MemOpChains2[0], MemOpChains2.size());
1984
1985     // Copy arguments to their registers.
1986     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1987       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1988                                RegsToPass[i].second, InFlag);
1989       InFlag = Chain.getValue(1);
1990     }
1991     InFlag =SDValue();
1992
1993     // Store the return address to the appropriate stack slot.
1994     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1995                                      FPDiff, dl);
1996   }
1997
1998   bool WasGlobalOrExternal = false;
1999   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2000     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2001     // In the 64-bit large code model, we have to make all calls
2002     // through a register, since the call instruction's 32-bit
2003     // pc-relative offset may not be large enough to hold the whole
2004     // address.
2005   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2006     WasGlobalOrExternal = true;
2007     // If the callee is a GlobalAddress node (quite common, every direct call
2008     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2009     // it.
2010
2011     // We should use extra load for direct calls to dllimported functions in
2012     // non-JIT mode.
2013     GlobalValue *GV = G->getGlobal();
2014     if (!GV->hasDLLImportLinkage()) {
2015       unsigned char OpFlags = 0;
2016
2017       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2018       // external symbols most go through the PLT in PIC mode.  If the symbol
2019       // has hidden or protected visibility, or if it is static or local, then
2020       // we don't need to use the PLT - we can directly call it.
2021       if (Subtarget->isTargetELF() &&
2022           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2023           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2024         OpFlags = X86II::MO_PLT;
2025       } else if (Subtarget->isPICStyleStubAny() &&
2026                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2027                Subtarget->getDarwinVers() < 9) {
2028         // PC-relative references to external symbols should go through $stub,
2029         // unless we're building with the leopard linker or later, which
2030         // automatically synthesizes these stubs.
2031         OpFlags = X86II::MO_DARWIN_STUB;
2032       }
2033
2034       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2035                                           G->getOffset(), OpFlags);
2036     }
2037   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2038     WasGlobalOrExternal = true;
2039     unsigned char OpFlags = 0;
2040
2041     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2042     // symbols should go through the PLT.
2043     if (Subtarget->isTargetELF() &&
2044         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2045       OpFlags = X86II::MO_PLT;
2046     } else if (Subtarget->isPICStyleStubAny() &&
2047              Subtarget->getDarwinVers() < 9) {
2048       // PC-relative references to external symbols should go through $stub,
2049       // unless we're building with the leopard linker or later, which
2050       // automatically synthesizes these stubs.
2051       OpFlags = X86II::MO_DARWIN_STUB;
2052     }
2053
2054     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2055                                          OpFlags);
2056   }
2057
2058   if (isTailCall && !WasGlobalOrExternal) {
2059     unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2060
2061     Chain = DAG.getCopyToReg(Chain,  dl,
2062                              DAG.getRegister(Opc, getPointerTy()),
2063                              Callee,InFlag);
2064     Callee = DAG.getRegister(Opc, getPointerTy());
2065     // Add register as live out.
2066     MF.getRegInfo().addLiveOut(Opc);
2067   }
2068
2069   // Returns a chain & a flag for retval copy to use.
2070   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2071   SmallVector<SDValue, 8> Ops;
2072
2073   if (isTailCall) {
2074     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2075                            DAG.getIntPtrConstant(0, true), InFlag);
2076     InFlag = Chain.getValue(1);
2077   }
2078
2079   Ops.push_back(Chain);
2080   Ops.push_back(Callee);
2081
2082   if (isTailCall)
2083     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2084
2085   // Add argument registers to the end of the list so that they are known live
2086   // into the call.
2087   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2088     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2089                                   RegsToPass[i].second.getValueType()));
2090
2091   // Add an implicit use GOT pointer in EBX.
2092   if (!isTailCall && Subtarget->isPICStyleGOT())
2093     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2094
2095   // Add an implicit use of AL for x86 vararg functions.
2096   if (Is64Bit && isVarArg)
2097     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2098
2099   if (InFlag.getNode())
2100     Ops.push_back(InFlag);
2101
2102   if (isTailCall) {
2103     // If this is the first return lowered for this function, add the regs
2104     // to the liveout set for the function.
2105     if (MF.getRegInfo().liveout_empty()) {
2106       SmallVector<CCValAssign, 16> RVLocs;
2107       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2108                      *DAG.getContext());
2109       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2110       for (unsigned i = 0; i != RVLocs.size(); ++i)
2111         if (RVLocs[i].isRegLoc())
2112           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2113     }
2114
2115     assert(((Callee.getOpcode() == ISD::Register &&
2116                (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2117                 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2118               Callee.getOpcode() == ISD::TargetExternalSymbol ||
2119               Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2120            "Expecting a global address, external symbol, or scratch register");
2121
2122     return DAG.getNode(X86ISD::TC_RETURN, dl,
2123                        NodeTys, &Ops[0], Ops.size());
2124   }
2125
2126   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2127   InFlag = Chain.getValue(1);
2128
2129   // Create the CALLSEQ_END node.
2130   unsigned NumBytesForCalleeToPush;
2131   if (IsCalleePop(isVarArg, CallConv))
2132     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2133   else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2134     // If this is is a call to a struct-return function, the callee
2135     // pops the hidden struct pointer, so we have to push it back.
2136     // This is common for Darwin/X86, Linux & Mingw32 targets.
2137     NumBytesForCalleeToPush = 4;
2138   else
2139     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2140
2141   // Returns a flag for retval copy to use.
2142   Chain = DAG.getCALLSEQ_END(Chain,
2143                              DAG.getIntPtrConstant(NumBytes, true),
2144                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2145                                                    true),
2146                              InFlag);
2147   InFlag = Chain.getValue(1);
2148
2149   // Handle result values, copying them out of physregs into vregs that we
2150   // return.
2151   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2152                          Ins, dl, DAG, InVals);
2153 }
2154
2155
2156 //===----------------------------------------------------------------------===//
2157 //                Fast Calling Convention (tail call) implementation
2158 //===----------------------------------------------------------------------===//
2159
2160 //  Like std call, callee cleans arguments, convention except that ECX is
2161 //  reserved for storing the tail called function address. Only 2 registers are
2162 //  free for argument passing (inreg). Tail call optimization is performed
2163 //  provided:
2164 //                * tailcallopt is enabled
2165 //                * caller/callee are fastcc
2166 //  On X86_64 architecture with GOT-style position independent code only local
2167 //  (within module) calls are supported at the moment.
2168 //  To keep the stack aligned according to platform abi the function
2169 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2170 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2171 //  If a tail called function callee has more arguments than the caller the
2172 //  caller needs to make sure that there is room to move the RETADDR to. This is
2173 //  achieved by reserving an area the size of the argument delta right after the
2174 //  original REtADDR, but before the saved framepointer or the spilled registers
2175 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2176 //  stack layout:
2177 //    arg1
2178 //    arg2
2179 //    RETADDR
2180 //    [ new RETADDR
2181 //      move area ]
2182 //    (possible EBP)
2183 //    ESI
2184 //    EDI
2185 //    local1 ..
2186
2187 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2188 /// for a 16 byte align requirement.
2189 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2190                                                         SelectionDAG& DAG) {
2191   MachineFunction &MF = DAG.getMachineFunction();
2192   const TargetMachine &TM = MF.getTarget();
2193   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2194   unsigned StackAlignment = TFI.getStackAlignment();
2195   uint64_t AlignMask = StackAlignment - 1;
2196   int64_t Offset = StackSize;
2197   uint64_t SlotSize = TD->getPointerSize();
2198   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2199     // Number smaller than 12 so just add the difference.
2200     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2201   } else {
2202     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2203     Offset = ((~AlignMask) & Offset) + StackAlignment +
2204       (StackAlignment-SlotSize);
2205   }
2206   return Offset;
2207 }
2208
2209 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2210 /// for tail call optimization. Targets which want to do tail call
2211 /// optimization should implement this function.
2212 bool
2213 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2214                                                      CallingConv::ID CalleeCC,
2215                                                      bool isVarArg,
2216                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2217                                                      SelectionDAG& DAG) const {
2218   MachineFunction &MF = DAG.getMachineFunction();
2219   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2220   return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2221 }
2222
2223 FastISel *
2224 X86TargetLowering::createFastISel(MachineFunction &mf,
2225                                   MachineModuleInfo *mmo,
2226                                   DwarfWriter *dw,
2227                                   DenseMap<const Value *, unsigned> &vm,
2228                                   DenseMap<const BasicBlock *,
2229                                            MachineBasicBlock *> &bm,
2230                                   DenseMap<const AllocaInst *, int> &am
2231 #ifndef NDEBUG
2232                                   , SmallSet<Instruction*, 8> &cil
2233 #endif
2234                                   ) {
2235   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2236 #ifndef NDEBUG
2237                              , cil
2238 #endif
2239                              );
2240 }
2241
2242
2243 //===----------------------------------------------------------------------===//
2244 //                           Other Lowering Hooks
2245 //===----------------------------------------------------------------------===//
2246
2247
2248 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2249   MachineFunction &MF = DAG.getMachineFunction();
2250   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2251   int ReturnAddrIndex = FuncInfo->getRAIndex();
2252
2253   if (ReturnAddrIndex == 0) {
2254     // Set up a frame object for the return address.
2255     uint64_t SlotSize = TD->getPointerSize();
2256     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2257                                                            true, false);
2258     FuncInfo->setRAIndex(ReturnAddrIndex);
2259   }
2260
2261   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2262 }
2263
2264
2265 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2266                                        bool hasSymbolicDisplacement) {
2267   // Offset should fit into 32 bit immediate field.
2268   if (!isInt32(Offset))
2269     return false;
2270
2271   // If we don't have a symbolic displacement - we don't have any extra
2272   // restrictions.
2273   if (!hasSymbolicDisplacement)
2274     return true;
2275
2276   // FIXME: Some tweaks might be needed for medium code model.
2277   if (M != CodeModel::Small && M != CodeModel::Kernel)
2278     return false;
2279
2280   // For small code model we assume that latest object is 16MB before end of 31
2281   // bits boundary. We may also accept pretty large negative constants knowing
2282   // that all objects are in the positive half of address space.
2283   if (M == CodeModel::Small && Offset < 16*1024*1024)
2284     return true;
2285
2286   // For kernel code model we know that all object resist in the negative half
2287   // of 32bits address space. We may not accept negative offsets, since they may
2288   // be just off and we may accept pretty large positive ones.
2289   if (M == CodeModel::Kernel && Offset > 0)
2290     return true;
2291
2292   return false;
2293 }
2294
2295 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2296 /// specific condition code, returning the condition code and the LHS/RHS of the
2297 /// comparison to make.
2298 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2299                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2300   if (!isFP) {
2301     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2302       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2303         // X > -1   -> X == 0, jump !sign.
2304         RHS = DAG.getConstant(0, RHS.getValueType());
2305         return X86::COND_NS;
2306       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2307         // X < 0   -> X == 0, jump on sign.
2308         return X86::COND_S;
2309       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2310         // X < 1   -> X <= 0
2311         RHS = DAG.getConstant(0, RHS.getValueType());
2312         return X86::COND_LE;
2313       }
2314     }
2315
2316     switch (SetCCOpcode) {
2317     default: llvm_unreachable("Invalid integer condition!");
2318     case ISD::SETEQ:  return X86::COND_E;
2319     case ISD::SETGT:  return X86::COND_G;
2320     case ISD::SETGE:  return X86::COND_GE;
2321     case ISD::SETLT:  return X86::COND_L;
2322     case ISD::SETLE:  return X86::COND_LE;
2323     case ISD::SETNE:  return X86::COND_NE;
2324     case ISD::SETULT: return X86::COND_B;
2325     case ISD::SETUGT: return X86::COND_A;
2326     case ISD::SETULE: return X86::COND_BE;
2327     case ISD::SETUGE: return X86::COND_AE;
2328     }
2329   }
2330
2331   // First determine if it is required or is profitable to flip the operands.
2332
2333   // If LHS is a foldable load, but RHS is not, flip the condition.
2334   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2335       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2336     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2337     std::swap(LHS, RHS);
2338   }
2339
2340   switch (SetCCOpcode) {
2341   default: break;
2342   case ISD::SETOLT:
2343   case ISD::SETOLE:
2344   case ISD::SETUGT:
2345   case ISD::SETUGE:
2346     std::swap(LHS, RHS);
2347     break;
2348   }
2349
2350   // On a floating point condition, the flags are set as follows:
2351   // ZF  PF  CF   op
2352   //  0 | 0 | 0 | X > Y
2353   //  0 | 0 | 1 | X < Y
2354   //  1 | 0 | 0 | X == Y
2355   //  1 | 1 | 1 | unordered
2356   switch (SetCCOpcode) {
2357   default: llvm_unreachable("Condcode should be pre-legalized away");
2358   case ISD::SETUEQ:
2359   case ISD::SETEQ:   return X86::COND_E;
2360   case ISD::SETOLT:              // flipped
2361   case ISD::SETOGT:
2362   case ISD::SETGT:   return X86::COND_A;
2363   case ISD::SETOLE:              // flipped
2364   case ISD::SETOGE:
2365   case ISD::SETGE:   return X86::COND_AE;
2366   case ISD::SETUGT:              // flipped
2367   case ISD::SETULT:
2368   case ISD::SETLT:   return X86::COND_B;
2369   case ISD::SETUGE:              // flipped
2370   case ISD::SETULE:
2371   case ISD::SETLE:   return X86::COND_BE;
2372   case ISD::SETONE:
2373   case ISD::SETNE:   return X86::COND_NE;
2374   case ISD::SETUO:   return X86::COND_P;
2375   case ISD::SETO:    return X86::COND_NP;
2376   case ISD::SETOEQ:
2377   case ISD::SETUNE:  return X86::COND_INVALID;
2378   }
2379 }
2380
2381 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2382 /// code. Current x86 isa includes the following FP cmov instructions:
2383 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2384 static bool hasFPCMov(unsigned X86CC) {
2385   switch (X86CC) {
2386   default:
2387     return false;
2388   case X86::COND_B:
2389   case X86::COND_BE:
2390   case X86::COND_E:
2391   case X86::COND_P:
2392   case X86::COND_A:
2393   case X86::COND_AE:
2394   case X86::COND_NE:
2395   case X86::COND_NP:
2396     return true;
2397   }
2398 }
2399
2400 /// isFPImmLegal - Returns true if the target can instruction select the
2401 /// specified FP immediate natively. If false, the legalizer will
2402 /// materialize the FP immediate as a load from a constant pool.
2403 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2404   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2405     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2406       return true;
2407   }
2408   return false;
2409 }
2410
2411 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2412 /// the specified range (L, H].
2413 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2414   return (Val < 0) || (Val >= Low && Val < Hi);
2415 }
2416
2417 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2418 /// specified value.
2419 static bool isUndefOrEqual(int Val, int CmpVal) {
2420   if (Val < 0 || Val == CmpVal)
2421     return true;
2422   return false;
2423 }
2424
2425 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2426 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2427 /// the second operand.
2428 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2429   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2430     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2431   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2432     return (Mask[0] < 2 && Mask[1] < 2);
2433   return false;
2434 }
2435
2436 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2437   SmallVector<int, 8> M;
2438   N->getMask(M);
2439   return ::isPSHUFDMask(M, N->getValueType(0));
2440 }
2441
2442 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2443 /// is suitable for input to PSHUFHW.
2444 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2445   if (VT != MVT::v8i16)
2446     return false;
2447
2448   // Lower quadword copied in order or undef.
2449   for (int i = 0; i != 4; ++i)
2450     if (Mask[i] >= 0 && Mask[i] != i)
2451       return false;
2452
2453   // Upper quadword shuffled.
2454   for (int i = 4; i != 8; ++i)
2455     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2456       return false;
2457
2458   return true;
2459 }
2460
2461 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2462   SmallVector<int, 8> M;
2463   N->getMask(M);
2464   return ::isPSHUFHWMask(M, N->getValueType(0));
2465 }
2466
2467 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2468 /// is suitable for input to PSHUFLW.
2469 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2470   if (VT != MVT::v8i16)
2471     return false;
2472
2473   // Upper quadword copied in order.
2474   for (int i = 4; i != 8; ++i)
2475     if (Mask[i] >= 0 && Mask[i] != i)
2476       return false;
2477
2478   // Lower quadword shuffled.
2479   for (int i = 0; i != 4; ++i)
2480     if (Mask[i] >= 4)
2481       return false;
2482
2483   return true;
2484 }
2485
2486 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2487   SmallVector<int, 8> M;
2488   N->getMask(M);
2489   return ::isPSHUFLWMask(M, N->getValueType(0));
2490 }
2491
2492 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2493 /// is suitable for input to PALIGNR.
2494 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2495                           bool hasSSSE3) {
2496   int i, e = VT.getVectorNumElements();
2497   
2498   // Do not handle v2i64 / v2f64 shuffles with palignr.
2499   if (e < 4 || !hasSSSE3)
2500     return false;
2501   
2502   for (i = 0; i != e; ++i)
2503     if (Mask[i] >= 0)
2504       break;
2505   
2506   // All undef, not a palignr.
2507   if (i == e)
2508     return false;
2509
2510   // Determine if it's ok to perform a palignr with only the LHS, since we
2511   // don't have access to the actual shuffle elements to see if RHS is undef.
2512   bool Unary = Mask[i] < (int)e;
2513   bool NeedsUnary = false;
2514
2515   int s = Mask[i] - i;
2516   
2517   // Check the rest of the elements to see if they are consecutive.
2518   for (++i; i != e; ++i) {
2519     int m = Mask[i];
2520     if (m < 0) 
2521       continue;
2522     
2523     Unary = Unary && (m < (int)e);
2524     NeedsUnary = NeedsUnary || (m < s);
2525
2526     if (NeedsUnary && !Unary)
2527       return false;
2528     if (Unary && m != ((s+i) & (e-1)))
2529       return false;
2530     if (!Unary && m != (s+i))
2531       return false;
2532   }
2533   return true;
2534 }
2535
2536 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2537   SmallVector<int, 8> M;
2538   N->getMask(M);
2539   return ::isPALIGNRMask(M, N->getValueType(0), true);
2540 }
2541
2542 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2543 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2544 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2545   int NumElems = VT.getVectorNumElements();
2546   if (NumElems != 2 && NumElems != 4)
2547     return false;
2548
2549   int Half = NumElems / 2;
2550   for (int i = 0; i < Half; ++i)
2551     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2552       return false;
2553   for (int i = Half; i < NumElems; ++i)
2554     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2555       return false;
2556
2557   return true;
2558 }
2559
2560 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2561   SmallVector<int, 8> M;
2562   N->getMask(M);
2563   return ::isSHUFPMask(M, N->getValueType(0));
2564 }
2565
2566 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2567 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2568 /// half elements to come from vector 1 (which would equal the dest.) and
2569 /// the upper half to come from vector 2.
2570 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2571   int NumElems = VT.getVectorNumElements();
2572
2573   if (NumElems != 2 && NumElems != 4)
2574     return false;
2575
2576   int Half = NumElems / 2;
2577   for (int i = 0; i < Half; ++i)
2578     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2579       return false;
2580   for (int i = Half; i < NumElems; ++i)
2581     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2582       return false;
2583   return true;
2584 }
2585
2586 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2587   SmallVector<int, 8> M;
2588   N->getMask(M);
2589   return isCommutedSHUFPMask(M, N->getValueType(0));
2590 }
2591
2592 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2593 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2594 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2595   if (N->getValueType(0).getVectorNumElements() != 4)
2596     return false;
2597
2598   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2599   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2600          isUndefOrEqual(N->getMaskElt(1), 7) &&
2601          isUndefOrEqual(N->getMaskElt(2), 2) &&
2602          isUndefOrEqual(N->getMaskElt(3), 3);
2603 }
2604
2605 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2606 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2607 /// <2, 3, 2, 3>
2608 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2609   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2610   
2611   if (NumElems != 4)
2612     return false;
2613   
2614   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2615   isUndefOrEqual(N->getMaskElt(1), 3) &&
2616   isUndefOrEqual(N->getMaskElt(2), 2) &&
2617   isUndefOrEqual(N->getMaskElt(3), 3);
2618 }
2619
2620 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2621 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2622 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2623   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2624
2625   if (NumElems != 2 && NumElems != 4)
2626     return false;
2627
2628   for (unsigned i = 0; i < NumElems/2; ++i)
2629     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2630       return false;
2631
2632   for (unsigned i = NumElems/2; i < NumElems; ++i)
2633     if (!isUndefOrEqual(N->getMaskElt(i), i))
2634       return false;
2635
2636   return true;
2637 }
2638
2639 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2640 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2641 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2642   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2643
2644   if (NumElems != 2 && NumElems != 4)
2645     return false;
2646
2647   for (unsigned i = 0; i < NumElems/2; ++i)
2648     if (!isUndefOrEqual(N->getMaskElt(i), i))
2649       return false;
2650
2651   for (unsigned i = 0; i < NumElems/2; ++i)
2652     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2653       return false;
2654
2655   return true;
2656 }
2657
2658 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2659 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2660 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2661                          bool V2IsSplat = false) {
2662   int NumElts = VT.getVectorNumElements();
2663   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2664     return false;
2665
2666   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2667     int BitI  = Mask[i];
2668     int BitI1 = Mask[i+1];
2669     if (!isUndefOrEqual(BitI, j))
2670       return false;
2671     if (V2IsSplat) {
2672       if (!isUndefOrEqual(BitI1, NumElts))
2673         return false;
2674     } else {
2675       if (!isUndefOrEqual(BitI1, j + NumElts))
2676         return false;
2677     }
2678   }
2679   return true;
2680 }
2681
2682 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2683   SmallVector<int, 8> M;
2684   N->getMask(M);
2685   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2686 }
2687
2688 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2689 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2690 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2691                          bool V2IsSplat = false) {
2692   int NumElts = VT.getVectorNumElements();
2693   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2694     return false;
2695
2696   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2697     int BitI  = Mask[i];
2698     int BitI1 = Mask[i+1];
2699     if (!isUndefOrEqual(BitI, j + NumElts/2))
2700       return false;
2701     if (V2IsSplat) {
2702       if (isUndefOrEqual(BitI1, NumElts))
2703         return false;
2704     } else {
2705       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2706         return false;
2707     }
2708   }
2709   return true;
2710 }
2711
2712 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2713   SmallVector<int, 8> M;
2714   N->getMask(M);
2715   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2716 }
2717
2718 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2719 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2720 /// <0, 0, 1, 1>
2721 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2722   int NumElems = VT.getVectorNumElements();
2723   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2724     return false;
2725
2726   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2727     int BitI  = Mask[i];
2728     int BitI1 = Mask[i+1];
2729     if (!isUndefOrEqual(BitI, j))
2730       return false;
2731     if (!isUndefOrEqual(BitI1, j))
2732       return false;
2733   }
2734   return true;
2735 }
2736
2737 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2738   SmallVector<int, 8> M;
2739   N->getMask(M);
2740   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2741 }
2742
2743 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2744 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2745 /// <2, 2, 3, 3>
2746 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2747   int NumElems = VT.getVectorNumElements();
2748   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2749     return false;
2750
2751   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2752     int BitI  = Mask[i];
2753     int BitI1 = Mask[i+1];
2754     if (!isUndefOrEqual(BitI, j))
2755       return false;
2756     if (!isUndefOrEqual(BitI1, j))
2757       return false;
2758   }
2759   return true;
2760 }
2761
2762 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2763   SmallVector<int, 8> M;
2764   N->getMask(M);
2765   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2766 }
2767
2768 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2769 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2770 /// MOVSD, and MOVD, i.e. setting the lowest element.
2771 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2772   if (VT.getVectorElementType().getSizeInBits() < 32)
2773     return false;
2774
2775   int NumElts = VT.getVectorNumElements();
2776
2777   if (!isUndefOrEqual(Mask[0], NumElts))
2778     return false;
2779
2780   for (int i = 1; i < NumElts; ++i)
2781     if (!isUndefOrEqual(Mask[i], i))
2782       return false;
2783
2784   return true;
2785 }
2786
2787 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2788   SmallVector<int, 8> M;
2789   N->getMask(M);
2790   return ::isMOVLMask(M, N->getValueType(0));
2791 }
2792
2793 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2794 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2795 /// element of vector 2 and the other elements to come from vector 1 in order.
2796 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2797                                bool V2IsSplat = false, bool V2IsUndef = false) {
2798   int NumOps = VT.getVectorNumElements();
2799   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2800     return false;
2801
2802   if (!isUndefOrEqual(Mask[0], 0))
2803     return false;
2804
2805   for (int i = 1; i < NumOps; ++i)
2806     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2807           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2808           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2809       return false;
2810
2811   return true;
2812 }
2813
2814 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2815                            bool V2IsUndef = false) {
2816   SmallVector<int, 8> M;
2817   N->getMask(M);
2818   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2819 }
2820
2821 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2822 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2823 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2824   if (N->getValueType(0).getVectorNumElements() != 4)
2825     return false;
2826
2827   // Expect 1, 1, 3, 3
2828   for (unsigned i = 0; i < 2; ++i) {
2829     int Elt = N->getMaskElt(i);
2830     if (Elt >= 0 && Elt != 1)
2831       return false;
2832   }
2833
2834   bool HasHi = false;
2835   for (unsigned i = 2; i < 4; ++i) {
2836     int Elt = N->getMaskElt(i);
2837     if (Elt >= 0 && Elt != 3)
2838       return false;
2839     if (Elt == 3)
2840       HasHi = true;
2841   }
2842   // Don't use movshdup if it can be done with a shufps.
2843   // FIXME: verify that matching u, u, 3, 3 is what we want.
2844   return HasHi;
2845 }
2846
2847 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2848 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2849 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2850   if (N->getValueType(0).getVectorNumElements() != 4)
2851     return false;
2852
2853   // Expect 0, 0, 2, 2
2854   for (unsigned i = 0; i < 2; ++i)
2855     if (N->getMaskElt(i) > 0)
2856       return false;
2857
2858   bool HasHi = false;
2859   for (unsigned i = 2; i < 4; ++i) {
2860     int Elt = N->getMaskElt(i);
2861     if (Elt >= 0 && Elt != 2)
2862       return false;
2863     if (Elt == 2)
2864       HasHi = true;
2865   }
2866   // Don't use movsldup if it can be done with a shufps.
2867   return HasHi;
2868 }
2869
2870 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2871 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2872 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2873   int e = N->getValueType(0).getVectorNumElements() / 2;
2874
2875   for (int i = 0; i < e; ++i)
2876     if (!isUndefOrEqual(N->getMaskElt(i), i))
2877       return false;
2878   for (int i = 0; i < e; ++i)
2879     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2880       return false;
2881   return true;
2882 }
2883
2884 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2885 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2886 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2887   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2888   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2889
2890   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2891   unsigned Mask = 0;
2892   for (int i = 0; i < NumOperands; ++i) {
2893     int Val = SVOp->getMaskElt(NumOperands-i-1);
2894     if (Val < 0) Val = 0;
2895     if (Val >= NumOperands) Val -= NumOperands;
2896     Mask |= Val;
2897     if (i != NumOperands - 1)
2898       Mask <<= Shift;
2899   }
2900   return Mask;
2901 }
2902
2903 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2904 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2905 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2906   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2907   unsigned Mask = 0;
2908   // 8 nodes, but we only care about the last 4.
2909   for (unsigned i = 7; i >= 4; --i) {
2910     int Val = SVOp->getMaskElt(i);
2911     if (Val >= 0)
2912       Mask |= (Val - 4);
2913     if (i != 4)
2914       Mask <<= 2;
2915   }
2916   return Mask;
2917 }
2918
2919 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2920 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2921 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2922   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2923   unsigned Mask = 0;
2924   // 8 nodes, but we only care about the first 4.
2925   for (int i = 3; i >= 0; --i) {
2926     int Val = SVOp->getMaskElt(i);
2927     if (Val >= 0)
2928       Mask |= Val;
2929     if (i != 0)
2930       Mask <<= 2;
2931   }
2932   return Mask;
2933 }
2934
2935 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2936 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2937 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2938   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2939   EVT VVT = N->getValueType(0);
2940   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2941   int Val = 0;
2942
2943   unsigned i, e;
2944   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2945     Val = SVOp->getMaskElt(i);
2946     if (Val >= 0)
2947       break;
2948   }
2949   return (Val - i) * EltSize;
2950 }
2951
2952 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2953 /// constant +0.0.
2954 bool X86::isZeroNode(SDValue Elt) {
2955   return ((isa<ConstantSDNode>(Elt) &&
2956            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2957           (isa<ConstantFPSDNode>(Elt) &&
2958            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2959 }
2960
2961 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2962 /// their permute mask.
2963 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2964                                     SelectionDAG &DAG) {
2965   EVT VT = SVOp->getValueType(0);
2966   unsigned NumElems = VT.getVectorNumElements();
2967   SmallVector<int, 8> MaskVec;
2968
2969   for (unsigned i = 0; i != NumElems; ++i) {
2970     int idx = SVOp->getMaskElt(i);
2971     if (idx < 0)
2972       MaskVec.push_back(idx);
2973     else if (idx < (int)NumElems)
2974       MaskVec.push_back(idx + NumElems);
2975     else
2976       MaskVec.push_back(idx - NumElems);
2977   }
2978   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2979                               SVOp->getOperand(0), &MaskVec[0]);
2980 }
2981
2982 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2983 /// the two vector operands have swapped position.
2984 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2985   unsigned NumElems = VT.getVectorNumElements();
2986   for (unsigned i = 0; i != NumElems; ++i) {
2987     int idx = Mask[i];
2988     if (idx < 0)
2989       continue;
2990     else if (idx < (int)NumElems)
2991       Mask[i] = idx + NumElems;
2992     else
2993       Mask[i] = idx - NumElems;
2994   }
2995 }
2996
2997 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2998 /// match movhlps. The lower half elements should come from upper half of
2999 /// V1 (and in order), and the upper half elements should come from the upper
3000 /// half of V2 (and in order).
3001 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3002   if (Op->getValueType(0).getVectorNumElements() != 4)
3003     return false;
3004   for (unsigned i = 0, e = 2; i != e; ++i)
3005     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3006       return false;
3007   for (unsigned i = 2; i != 4; ++i)
3008     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3009       return false;
3010   return true;
3011 }
3012
3013 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3014 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3015 /// required.
3016 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3017   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3018     return false;
3019   N = N->getOperand(0).getNode();
3020   if (!ISD::isNON_EXTLoad(N))
3021     return false;
3022   if (LD)
3023     *LD = cast<LoadSDNode>(N);
3024   return true;
3025 }
3026
3027 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3028 /// match movlp{s|d}. The lower half elements should come from lower half of
3029 /// V1 (and in order), and the upper half elements should come from the upper
3030 /// half of V2 (and in order). And since V1 will become the source of the
3031 /// MOVLP, it must be either a vector load or a scalar load to vector.
3032 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3033                                ShuffleVectorSDNode *Op) {
3034   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3035     return false;
3036   // Is V2 is a vector load, don't do this transformation. We will try to use
3037   // load folding shufps op.
3038   if (ISD::isNON_EXTLoad(V2))
3039     return false;
3040
3041   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3042
3043   if (NumElems != 2 && NumElems != 4)
3044     return false;
3045   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3046     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3047       return false;
3048   for (unsigned i = NumElems/2; i != NumElems; ++i)
3049     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3050       return false;
3051   return true;
3052 }
3053
3054 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3055 /// all the same.
3056 static bool isSplatVector(SDNode *N) {
3057   if (N->getOpcode() != ISD::BUILD_VECTOR)
3058     return false;
3059
3060   SDValue SplatValue = N->getOperand(0);
3061   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3062     if (N->getOperand(i) != SplatValue)
3063       return false;
3064   return true;
3065 }
3066
3067 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3068 /// to an zero vector.
3069 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3070 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3071   SDValue V1 = N->getOperand(0);
3072   SDValue V2 = N->getOperand(1);
3073   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3074   for (unsigned i = 0; i != NumElems; ++i) {
3075     int Idx = N->getMaskElt(i);
3076     if (Idx >= (int)NumElems) {
3077       unsigned Opc = V2.getOpcode();
3078       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3079         continue;
3080       if (Opc != ISD::BUILD_VECTOR ||
3081           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3082         return false;
3083     } else if (Idx >= 0) {
3084       unsigned Opc = V1.getOpcode();
3085       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3086         continue;
3087       if (Opc != ISD::BUILD_VECTOR ||
3088           !X86::isZeroNode(V1.getOperand(Idx)))
3089         return false;
3090     }
3091   }
3092   return true;
3093 }
3094
3095 /// getZeroVector - Returns a vector of specified type with all zero elements.
3096 ///
3097 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3098                              DebugLoc dl) {
3099   assert(VT.isVector() && "Expected a vector type");
3100
3101   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3102   // type.  This ensures they get CSE'd.
3103   SDValue Vec;
3104   if (VT.getSizeInBits() == 64) { // MMX
3105     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3106     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3107   } else if (HasSSE2) {  // SSE2
3108     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3109     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3110   } else { // SSE1
3111     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3112     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3113   }
3114   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3115 }
3116
3117 /// getOnesVector - Returns a vector of specified type with all bits set.
3118 ///
3119 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3120   assert(VT.isVector() && "Expected a vector type");
3121
3122   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3123   // type.  This ensures they get CSE'd.
3124   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3125   SDValue Vec;
3126   if (VT.getSizeInBits() == 64)  // MMX
3127     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3128   else                                              // SSE
3129     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3130   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3131 }
3132
3133
3134 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3135 /// that point to V2 points to its first element.
3136 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3137   EVT VT = SVOp->getValueType(0);
3138   unsigned NumElems = VT.getVectorNumElements();
3139
3140   bool Changed = false;
3141   SmallVector<int, 8> MaskVec;
3142   SVOp->getMask(MaskVec);
3143
3144   for (unsigned i = 0; i != NumElems; ++i) {
3145     if (MaskVec[i] > (int)NumElems) {
3146       MaskVec[i] = NumElems;
3147       Changed = true;
3148     }
3149   }
3150   if (Changed)
3151     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3152                                 SVOp->getOperand(1), &MaskVec[0]);
3153   return SDValue(SVOp, 0);
3154 }
3155
3156 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3157 /// operation of specified width.
3158 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3159                        SDValue V2) {
3160   unsigned NumElems = VT.getVectorNumElements();
3161   SmallVector<int, 8> Mask;
3162   Mask.push_back(NumElems);
3163   for (unsigned i = 1; i != NumElems; ++i)
3164     Mask.push_back(i);
3165   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3166 }
3167
3168 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3169 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3170                           SDValue V2) {
3171   unsigned NumElems = VT.getVectorNumElements();
3172   SmallVector<int, 8> Mask;
3173   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3174     Mask.push_back(i);
3175     Mask.push_back(i + NumElems);
3176   }
3177   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3178 }
3179
3180 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3181 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3182                           SDValue V2) {
3183   unsigned NumElems = VT.getVectorNumElements();
3184   unsigned Half = NumElems/2;
3185   SmallVector<int, 8> Mask;
3186   for (unsigned i = 0; i != Half; ++i) {
3187     Mask.push_back(i + Half);
3188     Mask.push_back(i + NumElems + Half);
3189   }
3190   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3191 }
3192
3193 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3194 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3195                             bool HasSSE2) {
3196   if (SV->getValueType(0).getVectorNumElements() <= 4)
3197     return SDValue(SV, 0);
3198
3199   EVT PVT = MVT::v4f32;
3200   EVT VT = SV->getValueType(0);
3201   DebugLoc dl = SV->getDebugLoc();
3202   SDValue V1 = SV->getOperand(0);
3203   int NumElems = VT.getVectorNumElements();
3204   int EltNo = SV->getSplatIndex();
3205
3206   // unpack elements to the correct location
3207   while (NumElems > 4) {
3208     if (EltNo < NumElems/2) {
3209       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3210     } else {
3211       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3212       EltNo -= NumElems/2;
3213     }
3214     NumElems >>= 1;
3215   }
3216
3217   // Perform the splat.
3218   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3219   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3220   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3221   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3222 }
3223
3224 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3225 /// vector of zero or undef vector.  This produces a shuffle where the low
3226 /// element of V2 is swizzled into the zero/undef vector, landing at element
3227 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3228 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3229                                              bool isZero, bool HasSSE2,
3230                                              SelectionDAG &DAG) {
3231   EVT VT = V2.getValueType();
3232   SDValue V1 = isZero
3233     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3234   unsigned NumElems = VT.getVectorNumElements();
3235   SmallVector<int, 16> MaskVec;
3236   for (unsigned i = 0; i != NumElems; ++i)
3237     // If this is the insertion idx, put the low elt of V2 here.
3238     MaskVec.push_back(i == Idx ? NumElems : i);
3239   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3240 }
3241
3242 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3243 /// a shuffle that is zero.
3244 static
3245 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3246                                   bool Low, SelectionDAG &DAG) {
3247   unsigned NumZeros = 0;
3248   for (int i = 0; i < NumElems; ++i) {
3249     unsigned Index = Low ? i : NumElems-i-1;
3250     int Idx = SVOp->getMaskElt(Index);
3251     if (Idx < 0) {
3252       ++NumZeros;
3253       continue;
3254     }
3255     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3256     if (Elt.getNode() && X86::isZeroNode(Elt))
3257       ++NumZeros;
3258     else
3259       break;
3260   }
3261   return NumZeros;
3262 }
3263
3264 /// isVectorShift - Returns true if the shuffle can be implemented as a
3265 /// logical left or right shift of a vector.
3266 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3267 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3268                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3269   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3270
3271   isLeft = true;
3272   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3273   if (!NumZeros) {
3274     isLeft = false;
3275     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3276     if (!NumZeros)
3277       return false;
3278   }
3279   bool SeenV1 = false;
3280   bool SeenV2 = false;
3281   for (int i = NumZeros; i < NumElems; ++i) {
3282     int Val = isLeft ? (i - NumZeros) : i;
3283     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3284     if (Idx < 0)
3285       continue;
3286     if (Idx < NumElems)
3287       SeenV1 = true;
3288     else {
3289       Idx -= NumElems;
3290       SeenV2 = true;
3291     }
3292     if (Idx != Val)
3293       return false;
3294   }
3295   if (SeenV1 && SeenV2)
3296     return false;
3297
3298   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3299   ShAmt = NumZeros;
3300   return true;
3301 }
3302
3303
3304 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3305 ///
3306 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3307                                        unsigned NumNonZero, unsigned NumZero,
3308                                        SelectionDAG &DAG, TargetLowering &TLI) {
3309   if (NumNonZero > 8)
3310     return SDValue();
3311
3312   DebugLoc dl = Op.getDebugLoc();
3313   SDValue V(0, 0);
3314   bool First = true;
3315   for (unsigned i = 0; i < 16; ++i) {
3316     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3317     if (ThisIsNonZero && First) {
3318       if (NumZero)
3319         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3320       else
3321         V = DAG.getUNDEF(MVT::v8i16);
3322       First = false;
3323     }
3324
3325     if ((i & 1) != 0) {
3326       SDValue ThisElt(0, 0), LastElt(0, 0);
3327       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3328       if (LastIsNonZero) {
3329         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3330                               MVT::i16, Op.getOperand(i-1));
3331       }
3332       if (ThisIsNonZero) {
3333         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3334         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3335                               ThisElt, DAG.getConstant(8, MVT::i8));
3336         if (LastIsNonZero)
3337           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3338       } else
3339         ThisElt = LastElt;
3340
3341       if (ThisElt.getNode())
3342         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3343                         DAG.getIntPtrConstant(i/2));
3344     }
3345   }
3346
3347   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3348 }
3349
3350 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3351 ///
3352 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3353                                        unsigned NumNonZero, unsigned NumZero,
3354                                        SelectionDAG &DAG, TargetLowering &TLI) {
3355   if (NumNonZero > 4)
3356     return SDValue();
3357
3358   DebugLoc dl = Op.getDebugLoc();
3359   SDValue V(0, 0);
3360   bool First = true;
3361   for (unsigned i = 0; i < 8; ++i) {
3362     bool isNonZero = (NonZeros & (1 << i)) != 0;
3363     if (isNonZero) {
3364       if (First) {
3365         if (NumZero)
3366           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3367         else
3368           V = DAG.getUNDEF(MVT::v8i16);
3369         First = false;
3370       }
3371       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3372                       MVT::v8i16, V, Op.getOperand(i),
3373                       DAG.getIntPtrConstant(i));
3374     }
3375   }
3376
3377   return V;
3378 }
3379
3380 /// getVShift - Return a vector logical shift node.
3381 ///
3382 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3383                          unsigned NumBits, SelectionDAG &DAG,
3384                          const TargetLowering &TLI, DebugLoc dl) {
3385   bool isMMX = VT.getSizeInBits() == 64;
3386   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3387   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3388   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3389   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3390                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3391                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3392 }
3393
3394 SDValue
3395 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3396                                           SelectionDAG &DAG) {
3397   
3398   // Check if the scalar load can be widened into a vector load. And if
3399   // the address is "base + cst" see if the cst can be "absorbed" into
3400   // the shuffle mask.
3401   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3402     SDValue Ptr = LD->getBasePtr();
3403     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3404       return SDValue();
3405     EVT PVT = LD->getValueType(0);
3406     if (PVT != MVT::i32 && PVT != MVT::f32)
3407       return SDValue();
3408
3409     int FI = -1;
3410     int64_t Offset = 0;
3411     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3412       FI = FINode->getIndex();
3413       Offset = 0;
3414     } else if (Ptr.getOpcode() == ISD::ADD &&
3415                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3416                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3417       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3418       Offset = Ptr.getConstantOperandVal(1);
3419       Ptr = Ptr.getOperand(0);
3420     } else {
3421       return SDValue();
3422     }
3423
3424     SDValue Chain = LD->getChain();
3425     // Make sure the stack object alignment is at least 16.
3426     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3427     if (DAG.InferPtrAlignment(Ptr) < 16) {
3428       if (MFI->isFixedObjectIndex(FI)) {
3429         // Can't change the alignment. FIXME: It's possible to compute
3430         // the exact stack offset and reference FI + adjust offset instead.
3431         // If someone *really* cares about this. That's the way to implement it.
3432         return SDValue();
3433       } else {
3434         MFI->setObjectAlignment(FI, 16);
3435       }
3436     }
3437
3438     // (Offset % 16) must be multiple of 4. Then address is then
3439     // Ptr + (Offset & ~15).
3440     if (Offset < 0)
3441       return SDValue();
3442     if ((Offset % 16) & 3)
3443       return SDValue();
3444     int64_t StartOffset = Offset & ~15;
3445     if (StartOffset)
3446       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3447                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3448
3449     int EltNo = (Offset - StartOffset) >> 2;
3450     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3451     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3452     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3453     // Canonicalize it to a v4i32 shuffle.
3454     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3455     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3456                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3457                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3458   }
3459
3460   return SDValue();
3461 }
3462
3463 SDValue
3464 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3465   DebugLoc dl = Op.getDebugLoc();
3466   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3467   if (ISD::isBuildVectorAllZeros(Op.getNode())
3468       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3469     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3470     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3471     // eliminated on x86-32 hosts.
3472     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3473       return Op;
3474
3475     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3476       return getOnesVector(Op.getValueType(), DAG, dl);
3477     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3478   }
3479
3480   EVT VT = Op.getValueType();
3481   EVT ExtVT = VT.getVectorElementType();
3482   unsigned EVTBits = ExtVT.getSizeInBits();
3483
3484   unsigned NumElems = Op.getNumOperands();
3485   unsigned NumZero  = 0;
3486   unsigned NumNonZero = 0;
3487   unsigned NonZeros = 0;
3488   bool IsAllConstants = true;
3489   SmallSet<SDValue, 8> Values;
3490   for (unsigned i = 0; i < NumElems; ++i) {
3491     SDValue Elt = Op.getOperand(i);
3492     if (Elt.getOpcode() == ISD::UNDEF)
3493       continue;
3494     Values.insert(Elt);
3495     if (Elt.getOpcode() != ISD::Constant &&
3496         Elt.getOpcode() != ISD::ConstantFP)
3497       IsAllConstants = false;
3498     if (X86::isZeroNode(Elt))
3499       NumZero++;
3500     else {
3501       NonZeros |= (1 << i);
3502       NumNonZero++;
3503     }
3504   }
3505
3506   if (NumNonZero == 0) {
3507     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3508     return DAG.getUNDEF(VT);
3509   }
3510
3511   // Special case for single non-zero, non-undef, element.
3512   if (NumNonZero == 1) {
3513     unsigned Idx = CountTrailingZeros_32(NonZeros);
3514     SDValue Item = Op.getOperand(Idx);
3515
3516     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3517     // the value are obviously zero, truncate the value to i32 and do the
3518     // insertion that way.  Only do this if the value is non-constant or if the
3519     // value is a constant being inserted into element 0.  It is cheaper to do
3520     // a constant pool load than it is to do a movd + shuffle.
3521     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3522         (!IsAllConstants || Idx == 0)) {
3523       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3524         // Handle MMX and SSE both.
3525         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3526         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3527
3528         // Truncate the value (which may itself be a constant) to i32, and
3529         // convert it to a vector with movd (S2V+shuffle to zero extend).
3530         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3531         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3532         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3533                                            Subtarget->hasSSE2(), DAG);
3534
3535         // Now we have our 32-bit value zero extended in the low element of
3536         // a vector.  If Idx != 0, swizzle it into place.
3537         if (Idx != 0) {
3538           SmallVector<int, 4> Mask;
3539           Mask.push_back(Idx);
3540           for (unsigned i = 1; i != VecElts; ++i)
3541             Mask.push_back(i);
3542           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3543                                       DAG.getUNDEF(Item.getValueType()),
3544                                       &Mask[0]);
3545         }
3546         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3547       }
3548     }
3549
3550     // If we have a constant or non-constant insertion into the low element of
3551     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3552     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3553     // depending on what the source datatype is.
3554     if (Idx == 0) {
3555       if (NumZero == 0) {
3556         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3557       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3558           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3559         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3560         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3561         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3562                                            DAG);
3563       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3564         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3565         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3566         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3567         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3568                                            Subtarget->hasSSE2(), DAG);
3569         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3570       }
3571     }
3572
3573     // Is it a vector logical left shift?
3574     if (NumElems == 2 && Idx == 1 &&
3575         X86::isZeroNode(Op.getOperand(0)) &&
3576         !X86::isZeroNode(Op.getOperand(1))) {
3577       unsigned NumBits = VT.getSizeInBits();
3578       return getVShift(true, VT,
3579                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3580                                    VT, Op.getOperand(1)),
3581                        NumBits/2, DAG, *this, dl);
3582     }
3583
3584     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3585       return SDValue();
3586
3587     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3588     // is a non-constant being inserted into an element other than the low one,
3589     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3590     // movd/movss) to move this into the low element, then shuffle it into
3591     // place.
3592     if (EVTBits == 32) {
3593       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3594
3595       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3596       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3597                                          Subtarget->hasSSE2(), DAG);
3598       SmallVector<int, 8> MaskVec;
3599       for (unsigned i = 0; i < NumElems; i++)
3600         MaskVec.push_back(i == Idx ? 0 : 1);
3601       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3602     }
3603   }
3604
3605   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3606   if (Values.size() == 1) {
3607     if (EVTBits == 32) {
3608       // Instead of a shuffle like this:
3609       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3610       // Check if it's possible to issue this instead.
3611       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3612       unsigned Idx = CountTrailingZeros_32(NonZeros);
3613       SDValue Item = Op.getOperand(Idx);
3614       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3615         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3616     }
3617     return SDValue();
3618   }
3619
3620   // A vector full of immediates; various special cases are already
3621   // handled, so this is best done with a single constant-pool load.
3622   if (IsAllConstants)
3623     return SDValue();
3624
3625   // Let legalizer expand 2-wide build_vectors.
3626   if (EVTBits == 64) {
3627     if (NumNonZero == 1) {
3628       // One half is zero or undef.
3629       unsigned Idx = CountTrailingZeros_32(NonZeros);
3630       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3631                                  Op.getOperand(Idx));
3632       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3633                                          Subtarget->hasSSE2(), DAG);
3634     }
3635     return SDValue();
3636   }
3637
3638   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3639   if (EVTBits == 8 && NumElems == 16) {
3640     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3641                                         *this);
3642     if (V.getNode()) return V;
3643   }
3644
3645   if (EVTBits == 16 && NumElems == 8) {
3646     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3647                                         *this);
3648     if (V.getNode()) return V;
3649   }
3650
3651   // If element VT is == 32 bits, turn it into a number of shuffles.
3652   SmallVector<SDValue, 8> V;
3653   V.resize(NumElems);
3654   if (NumElems == 4 && NumZero > 0) {
3655     for (unsigned i = 0; i < 4; ++i) {
3656       bool isZero = !(NonZeros & (1 << i));
3657       if (isZero)
3658         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3659       else
3660         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3661     }
3662
3663     for (unsigned i = 0; i < 2; ++i) {
3664       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3665         default: break;
3666         case 0:
3667           V[i] = V[i*2];  // Must be a zero vector.
3668           break;
3669         case 1:
3670           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3671           break;
3672         case 2:
3673           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3674           break;
3675         case 3:
3676           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3677           break;
3678       }
3679     }
3680
3681     SmallVector<int, 8> MaskVec;
3682     bool Reverse = (NonZeros & 0x3) == 2;
3683     for (unsigned i = 0; i < 2; ++i)
3684       MaskVec.push_back(Reverse ? 1-i : i);
3685     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3686     for (unsigned i = 0; i < 2; ++i)
3687       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3688     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3689   }
3690
3691   if (Values.size() > 2) {
3692     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3693     // values to be inserted is equal to the number of elements, in which case
3694     // use the unpack code below in the hopes of matching the consecutive elts
3695     // load merge pattern for shuffles.
3696     // FIXME: We could probably just check that here directly.
3697     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3698         getSubtarget()->hasSSE41()) {
3699       V[0] = DAG.getUNDEF(VT);
3700       for (unsigned i = 0; i < NumElems; ++i)
3701         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3702           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3703                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3704       return V[0];
3705     }
3706     // Expand into a number of unpckl*.
3707     // e.g. for v4f32
3708     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3709     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3710     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3711     for (unsigned i = 0; i < NumElems; ++i)
3712       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3713     NumElems >>= 1;
3714     while (NumElems != 0) {
3715       for (unsigned i = 0; i < NumElems; ++i)
3716         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3717       NumElems >>= 1;
3718     }
3719     return V[0];
3720   }
3721
3722   return SDValue();
3723 }
3724
3725 SDValue
3726 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3727   // We support concatenate two MMX registers and place them in a MMX
3728   // register.  This is better than doing a stack convert.
3729   DebugLoc dl = Op.getDebugLoc();
3730   EVT ResVT = Op.getValueType();
3731   assert(Op.getNumOperands() == 2);
3732   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3733          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3734   int Mask[2];
3735   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3736   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3737   InVec = Op.getOperand(1);
3738   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3739     unsigned NumElts = ResVT.getVectorNumElements();
3740     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3741     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3742                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3743   } else {
3744     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3745     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3746     Mask[0] = 0; Mask[1] = 2;
3747     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3748   }
3749   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3750 }
3751
3752 // v8i16 shuffles - Prefer shuffles in the following order:
3753 // 1. [all]   pshuflw, pshufhw, optional move
3754 // 2. [ssse3] 1 x pshufb
3755 // 3. [ssse3] 2 x pshufb + 1 x por
3756 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3757 static
3758 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3759                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3760   SDValue V1 = SVOp->getOperand(0);
3761   SDValue V2 = SVOp->getOperand(1);
3762   DebugLoc dl = SVOp->getDebugLoc();
3763   SmallVector<int, 8> MaskVals;
3764
3765   // Determine if more than 1 of the words in each of the low and high quadwords
3766   // of the result come from the same quadword of one of the two inputs.  Undef
3767   // mask values count as coming from any quadword, for better codegen.
3768   SmallVector<unsigned, 4> LoQuad(4);
3769   SmallVector<unsigned, 4> HiQuad(4);
3770   BitVector InputQuads(4);
3771   for (unsigned i = 0; i < 8; ++i) {
3772     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3773     int EltIdx = SVOp->getMaskElt(i);
3774     MaskVals.push_back(EltIdx);
3775     if (EltIdx < 0) {
3776       ++Quad[0];
3777       ++Quad[1];
3778       ++Quad[2];
3779       ++Quad[3];
3780       continue;
3781     }
3782     ++Quad[EltIdx / 4];
3783     InputQuads.set(EltIdx / 4);
3784   }
3785
3786   int BestLoQuad = -1;
3787   unsigned MaxQuad = 1;
3788   for (unsigned i = 0; i < 4; ++i) {
3789     if (LoQuad[i] > MaxQuad) {
3790       BestLoQuad = i;
3791       MaxQuad = LoQuad[i];
3792     }
3793   }
3794
3795   int BestHiQuad = -1;
3796   MaxQuad = 1;
3797   for (unsigned i = 0; i < 4; ++i) {
3798     if (HiQuad[i] > MaxQuad) {
3799       BestHiQuad = i;
3800       MaxQuad = HiQuad[i];
3801     }
3802   }
3803
3804   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3805   // of the two input vectors, shuffle them into one input vector so only a
3806   // single pshufb instruction is necessary. If There are more than 2 input
3807   // quads, disable the next transformation since it does not help SSSE3.
3808   bool V1Used = InputQuads[0] || InputQuads[1];
3809   bool V2Used = InputQuads[2] || InputQuads[3];
3810   if (TLI.getSubtarget()->hasSSSE3()) {
3811     if (InputQuads.count() == 2 && V1Used && V2Used) {
3812       BestLoQuad = InputQuads.find_first();
3813       BestHiQuad = InputQuads.find_next(BestLoQuad);
3814     }
3815     if (InputQuads.count() > 2) {
3816       BestLoQuad = -1;
3817       BestHiQuad = -1;
3818     }
3819   }
3820
3821   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3822   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3823   // words from all 4 input quadwords.
3824   SDValue NewV;
3825   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3826     SmallVector<int, 8> MaskV;
3827     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3828     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3829     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3830                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3831                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3832     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3833
3834     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3835     // source words for the shuffle, to aid later transformations.
3836     bool AllWordsInNewV = true;
3837     bool InOrder[2] = { true, true };
3838     for (unsigned i = 0; i != 8; ++i) {
3839       int idx = MaskVals[i];
3840       if (idx != (int)i)
3841         InOrder[i/4] = false;
3842       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3843         continue;
3844       AllWordsInNewV = false;
3845       break;
3846     }
3847
3848     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3849     if (AllWordsInNewV) {
3850       for (int i = 0; i != 8; ++i) {
3851         int idx = MaskVals[i];
3852         if (idx < 0)
3853           continue;
3854         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3855         if ((idx != i) && idx < 4)
3856           pshufhw = false;
3857         if ((idx != i) && idx > 3)
3858           pshuflw = false;
3859       }
3860       V1 = NewV;
3861       V2Used = false;
3862       BestLoQuad = 0;
3863       BestHiQuad = 1;
3864     }
3865
3866     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3867     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3868     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3869       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3870                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3871     }
3872   }
3873
3874   // If we have SSSE3, and all words of the result are from 1 input vector,
3875   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3876   // is present, fall back to case 4.
3877   if (TLI.getSubtarget()->hasSSSE3()) {
3878     SmallVector<SDValue,16> pshufbMask;
3879
3880     // If we have elements from both input vectors, set the high bit of the
3881     // shuffle mask element to zero out elements that come from V2 in the V1
3882     // mask, and elements that come from V1 in the V2 mask, so that the two
3883     // results can be OR'd together.
3884     bool TwoInputs = V1Used && V2Used;
3885     for (unsigned i = 0; i != 8; ++i) {
3886       int EltIdx = MaskVals[i] * 2;
3887       if (TwoInputs && (EltIdx >= 16)) {
3888         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3889         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3890         continue;
3891       }
3892       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3893       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3894     }
3895     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3896     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3897                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3898                                  MVT::v16i8, &pshufbMask[0], 16));
3899     if (!TwoInputs)
3900       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3901
3902     // Calculate the shuffle mask for the second input, shuffle it, and
3903     // OR it with the first shuffled input.
3904     pshufbMask.clear();
3905     for (unsigned i = 0; i != 8; ++i) {
3906       int EltIdx = MaskVals[i] * 2;
3907       if (EltIdx < 16) {
3908         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3909         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3910         continue;
3911       }
3912       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3913       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3914     }
3915     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3916     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3917                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3918                                  MVT::v16i8, &pshufbMask[0], 16));
3919     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3920     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3921   }
3922
3923   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3924   // and update MaskVals with new element order.
3925   BitVector InOrder(8);
3926   if (BestLoQuad >= 0) {
3927     SmallVector<int, 8> MaskV;
3928     for (int i = 0; i != 4; ++i) {
3929       int idx = MaskVals[i];
3930       if (idx < 0) {
3931         MaskV.push_back(-1);
3932         InOrder.set(i);
3933       } else if ((idx / 4) == BestLoQuad) {
3934         MaskV.push_back(idx & 3);
3935         InOrder.set(i);
3936       } else {
3937         MaskV.push_back(-1);
3938       }
3939     }
3940     for (unsigned i = 4; i != 8; ++i)
3941       MaskV.push_back(i);
3942     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3943                                 &MaskV[0]);
3944   }
3945
3946   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3947   // and update MaskVals with the new element order.
3948   if (BestHiQuad >= 0) {
3949     SmallVector<int, 8> MaskV;
3950     for (unsigned i = 0; i != 4; ++i)
3951       MaskV.push_back(i);
3952     for (unsigned i = 4; i != 8; ++i) {
3953       int idx = MaskVals[i];
3954       if (idx < 0) {
3955         MaskV.push_back(-1);
3956         InOrder.set(i);
3957       } else if ((idx / 4) == BestHiQuad) {
3958         MaskV.push_back((idx & 3) + 4);
3959         InOrder.set(i);
3960       } else {
3961         MaskV.push_back(-1);
3962       }
3963     }
3964     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3965                                 &MaskV[0]);
3966   }
3967
3968   // In case BestHi & BestLo were both -1, which means each quadword has a word
3969   // from each of the four input quadwords, calculate the InOrder bitvector now
3970   // before falling through to the insert/extract cleanup.
3971   if (BestLoQuad == -1 && BestHiQuad == -1) {
3972     NewV = V1;
3973     for (int i = 0; i != 8; ++i)
3974       if (MaskVals[i] < 0 || MaskVals[i] == i)
3975         InOrder.set(i);
3976   }
3977
3978   // The other elements are put in the right place using pextrw and pinsrw.
3979   for (unsigned i = 0; i != 8; ++i) {
3980     if (InOrder[i])
3981       continue;
3982     int EltIdx = MaskVals[i];
3983     if (EltIdx < 0)
3984       continue;
3985     SDValue ExtOp = (EltIdx < 8)
3986     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3987                   DAG.getIntPtrConstant(EltIdx))
3988     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3989                   DAG.getIntPtrConstant(EltIdx - 8));
3990     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3991                        DAG.getIntPtrConstant(i));
3992   }
3993   return NewV;
3994 }
3995
3996 // v16i8 shuffles - Prefer shuffles in the following order:
3997 // 1. [ssse3] 1 x pshufb
3998 // 2. [ssse3] 2 x pshufb + 1 x por
3999 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4000 static
4001 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4002                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4003   SDValue V1 = SVOp->getOperand(0);
4004   SDValue V2 = SVOp->getOperand(1);
4005   DebugLoc dl = SVOp->getDebugLoc();
4006   SmallVector<int, 16> MaskVals;
4007   SVOp->getMask(MaskVals);
4008
4009   // If we have SSSE3, case 1 is generated when all result bytes come from
4010   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4011   // present, fall back to case 3.
4012   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4013   bool V1Only = true;
4014   bool V2Only = true;
4015   for (unsigned i = 0; i < 16; ++i) {
4016     int EltIdx = MaskVals[i];
4017     if (EltIdx < 0)
4018       continue;
4019     if (EltIdx < 16)
4020       V2Only = false;
4021     else
4022       V1Only = false;
4023   }
4024
4025   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4026   if (TLI.getSubtarget()->hasSSSE3()) {
4027     SmallVector<SDValue,16> pshufbMask;
4028
4029     // If all result elements are from one input vector, then only translate
4030     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4031     //
4032     // Otherwise, we have elements from both input vectors, and must zero out
4033     // elements that come from V2 in the first mask, and V1 in the second mask
4034     // so that we can OR them together.
4035     bool TwoInputs = !(V1Only || V2Only);
4036     for (unsigned i = 0; i != 16; ++i) {
4037       int EltIdx = MaskVals[i];
4038       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4039         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4040         continue;
4041       }
4042       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4043     }
4044     // If all the elements are from V2, assign it to V1 and return after
4045     // building the first pshufb.
4046     if (V2Only)
4047       V1 = V2;
4048     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4049                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4050                                  MVT::v16i8, &pshufbMask[0], 16));
4051     if (!TwoInputs)
4052       return V1;
4053
4054     // Calculate the shuffle mask for the second input, shuffle it, and
4055     // OR it with the first shuffled input.
4056     pshufbMask.clear();
4057     for (unsigned i = 0; i != 16; ++i) {
4058       int EltIdx = MaskVals[i];
4059       if (EltIdx < 16) {
4060         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4061         continue;
4062       }
4063       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4064     }
4065     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4066                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4067                                  MVT::v16i8, &pshufbMask[0], 16));
4068     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4069   }
4070
4071   // No SSSE3 - Calculate in place words and then fix all out of place words
4072   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4073   // the 16 different words that comprise the two doublequadword input vectors.
4074   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4075   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4076   SDValue NewV = V2Only ? V2 : V1;
4077   for (int i = 0; i != 8; ++i) {
4078     int Elt0 = MaskVals[i*2];
4079     int Elt1 = MaskVals[i*2+1];
4080
4081     // This word of the result is all undef, skip it.
4082     if (Elt0 < 0 && Elt1 < 0)
4083       continue;
4084
4085     // This word of the result is already in the correct place, skip it.
4086     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4087       continue;
4088     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4089       continue;
4090
4091     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4092     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4093     SDValue InsElt;
4094
4095     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4096     // using a single extract together, load it and store it.
4097     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4098       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4099                            DAG.getIntPtrConstant(Elt1 / 2));
4100       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4101                         DAG.getIntPtrConstant(i));
4102       continue;
4103     }
4104
4105     // If Elt1 is defined, extract it from the appropriate source.  If the
4106     // source byte is not also odd, shift the extracted word left 8 bits
4107     // otherwise clear the bottom 8 bits if we need to do an or.
4108     if (Elt1 >= 0) {
4109       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4110                            DAG.getIntPtrConstant(Elt1 / 2));
4111       if ((Elt1 & 1) == 0)
4112         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4113                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4114       else if (Elt0 >= 0)
4115         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4116                              DAG.getConstant(0xFF00, MVT::i16));
4117     }
4118     // If Elt0 is defined, extract it from the appropriate source.  If the
4119     // source byte is not also even, shift the extracted word right 8 bits. If
4120     // Elt1 was also defined, OR the extracted values together before
4121     // inserting them in the result.
4122     if (Elt0 >= 0) {
4123       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4124                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4125       if ((Elt0 & 1) != 0)
4126         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4127                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4128       else if (Elt1 >= 0)
4129         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4130                              DAG.getConstant(0x00FF, MVT::i16));
4131       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4132                          : InsElt0;
4133     }
4134     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4135                        DAG.getIntPtrConstant(i));
4136   }
4137   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4138 }
4139
4140 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4141 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4142 /// done when every pair / quad of shuffle mask elements point to elements in
4143 /// the right sequence. e.g.
4144 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4145 static
4146 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4147                                  SelectionDAG &DAG,
4148                                  TargetLowering &TLI, DebugLoc dl) {
4149   EVT VT = SVOp->getValueType(0);
4150   SDValue V1 = SVOp->getOperand(0);
4151   SDValue V2 = SVOp->getOperand(1);
4152   unsigned NumElems = VT.getVectorNumElements();
4153   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4154   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4155   EVT MaskEltVT = MaskVT.getVectorElementType();
4156   EVT NewVT = MaskVT;
4157   switch (VT.getSimpleVT().SimpleTy) {
4158   default: assert(false && "Unexpected!");
4159   case MVT::v4f32: NewVT = MVT::v2f64; break;
4160   case MVT::v4i32: NewVT = MVT::v2i64; break;
4161   case MVT::v8i16: NewVT = MVT::v4i32; break;
4162   case MVT::v16i8: NewVT = MVT::v4i32; break;
4163   }
4164
4165   if (NewWidth == 2) {
4166     if (VT.isInteger())
4167       NewVT = MVT::v2i64;
4168     else
4169       NewVT = MVT::v2f64;
4170   }
4171   int Scale = NumElems / NewWidth;
4172   SmallVector<int, 8> MaskVec;
4173   for (unsigned i = 0; i < NumElems; i += Scale) {
4174     int StartIdx = -1;
4175     for (int j = 0; j < Scale; ++j) {
4176       int EltIdx = SVOp->getMaskElt(i+j);
4177       if (EltIdx < 0)
4178         continue;
4179       if (StartIdx == -1)
4180         StartIdx = EltIdx - (EltIdx % Scale);
4181       if (EltIdx != StartIdx + j)
4182         return SDValue();
4183     }
4184     if (StartIdx == -1)
4185       MaskVec.push_back(-1);
4186     else
4187       MaskVec.push_back(StartIdx / Scale);
4188   }
4189
4190   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4191   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4192   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4193 }
4194
4195 /// getVZextMovL - Return a zero-extending vector move low node.
4196 ///
4197 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4198                             SDValue SrcOp, SelectionDAG &DAG,
4199                             const X86Subtarget *Subtarget, DebugLoc dl) {
4200   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4201     LoadSDNode *LD = NULL;
4202     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4203       LD = dyn_cast<LoadSDNode>(SrcOp);
4204     if (!LD) {
4205       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4206       // instead.
4207       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4208       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4209           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4210           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4211           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4212         // PR2108
4213         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4214         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4215                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4216                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4217                                                    OpVT,
4218                                                    SrcOp.getOperand(0)
4219                                                           .getOperand(0))));
4220       }
4221     }
4222   }
4223
4224   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4225                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4226                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4227                                              OpVT, SrcOp)));
4228 }
4229
4230 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4231 /// shuffles.
4232 static SDValue
4233 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4234   SDValue V1 = SVOp->getOperand(0);
4235   SDValue V2 = SVOp->getOperand(1);
4236   DebugLoc dl = SVOp->getDebugLoc();
4237   EVT VT = SVOp->getValueType(0);
4238
4239   SmallVector<std::pair<int, int>, 8> Locs;
4240   Locs.resize(4);
4241   SmallVector<int, 8> Mask1(4U, -1);
4242   SmallVector<int, 8> PermMask;
4243   SVOp->getMask(PermMask);
4244
4245   unsigned NumHi = 0;
4246   unsigned NumLo = 0;
4247   for (unsigned i = 0; i != 4; ++i) {
4248     int Idx = PermMask[i];
4249     if (Idx < 0) {
4250       Locs[i] = std::make_pair(-1, -1);
4251     } else {
4252       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4253       if (Idx < 4) {
4254         Locs[i] = std::make_pair(0, NumLo);
4255         Mask1[NumLo] = Idx;
4256         NumLo++;
4257       } else {
4258         Locs[i] = std::make_pair(1, NumHi);
4259         if (2+NumHi < 4)
4260           Mask1[2+NumHi] = Idx;
4261         NumHi++;
4262       }
4263     }
4264   }
4265
4266   if (NumLo <= 2 && NumHi <= 2) {
4267     // If no more than two elements come from either vector. This can be
4268     // implemented with two shuffles. First shuffle gather the elements.
4269     // The second shuffle, which takes the first shuffle as both of its
4270     // vector operands, put the elements into the right order.
4271     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4272
4273     SmallVector<int, 8> Mask2(4U, -1);
4274
4275     for (unsigned i = 0; i != 4; ++i) {
4276       if (Locs[i].first == -1)
4277         continue;
4278       else {
4279         unsigned Idx = (i < 2) ? 0 : 4;
4280         Idx += Locs[i].first * 2 + Locs[i].second;
4281         Mask2[i] = Idx;
4282       }
4283     }
4284
4285     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4286   } else if (NumLo == 3 || NumHi == 3) {
4287     // Otherwise, we must have three elements from one vector, call it X, and
4288     // one element from the other, call it Y.  First, use a shufps to build an
4289     // intermediate vector with the one element from Y and the element from X
4290     // that will be in the same half in the final destination (the indexes don't
4291     // matter). Then, use a shufps to build the final vector, taking the half
4292     // containing the element from Y from the intermediate, and the other half
4293     // from X.
4294     if (NumHi == 3) {
4295       // Normalize it so the 3 elements come from V1.
4296       CommuteVectorShuffleMask(PermMask, VT);
4297       std::swap(V1, V2);
4298     }
4299
4300     // Find the element from V2.
4301     unsigned HiIndex;
4302     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4303       int Val = PermMask[HiIndex];
4304       if (Val < 0)
4305         continue;
4306       if (Val >= 4)
4307         break;
4308     }
4309
4310     Mask1[0] = PermMask[HiIndex];
4311     Mask1[1] = -1;
4312     Mask1[2] = PermMask[HiIndex^1];
4313     Mask1[3] = -1;
4314     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4315
4316     if (HiIndex >= 2) {
4317       Mask1[0] = PermMask[0];
4318       Mask1[1] = PermMask[1];
4319       Mask1[2] = HiIndex & 1 ? 6 : 4;
4320       Mask1[3] = HiIndex & 1 ? 4 : 6;
4321       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4322     } else {
4323       Mask1[0] = HiIndex & 1 ? 2 : 0;
4324       Mask1[1] = HiIndex & 1 ? 0 : 2;
4325       Mask1[2] = PermMask[2];
4326       Mask1[3] = PermMask[3];
4327       if (Mask1[2] >= 0)
4328         Mask1[2] += 4;
4329       if (Mask1[3] >= 0)
4330         Mask1[3] += 4;
4331       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4332     }
4333   }
4334
4335   // Break it into (shuffle shuffle_hi, shuffle_lo).
4336   Locs.clear();
4337   SmallVector<int,8> LoMask(4U, -1);
4338   SmallVector<int,8> HiMask(4U, -1);
4339
4340   SmallVector<int,8> *MaskPtr = &LoMask;
4341   unsigned MaskIdx = 0;
4342   unsigned LoIdx = 0;
4343   unsigned HiIdx = 2;
4344   for (unsigned i = 0; i != 4; ++i) {
4345     if (i == 2) {
4346       MaskPtr = &HiMask;
4347       MaskIdx = 1;
4348       LoIdx = 0;
4349       HiIdx = 2;
4350     }
4351     int Idx = PermMask[i];
4352     if (Idx < 0) {
4353       Locs[i] = std::make_pair(-1, -1);
4354     } else if (Idx < 4) {
4355       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4356       (*MaskPtr)[LoIdx] = Idx;
4357       LoIdx++;
4358     } else {
4359       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4360       (*MaskPtr)[HiIdx] = Idx;
4361       HiIdx++;
4362     }
4363   }
4364
4365   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4366   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4367   SmallVector<int, 8> MaskOps;
4368   for (unsigned i = 0; i != 4; ++i) {
4369     if (Locs[i].first == -1) {
4370       MaskOps.push_back(-1);
4371     } else {
4372       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4373       MaskOps.push_back(Idx);
4374     }
4375   }
4376   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4377 }
4378
4379 SDValue
4380 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4381   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4382   SDValue V1 = Op.getOperand(0);
4383   SDValue V2 = Op.getOperand(1);
4384   EVT VT = Op.getValueType();
4385   DebugLoc dl = Op.getDebugLoc();
4386   unsigned NumElems = VT.getVectorNumElements();
4387   bool isMMX = VT.getSizeInBits() == 64;
4388   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4389   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4390   bool V1IsSplat = false;
4391   bool V2IsSplat = false;
4392
4393   if (isZeroShuffle(SVOp))
4394     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4395
4396   // Promote splats to v4f32.
4397   if (SVOp->isSplat()) {
4398     if (isMMX || NumElems < 4)
4399       return Op;
4400     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4401   }
4402
4403   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4404   // do it!
4405   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4406     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4407     if (NewOp.getNode())
4408       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4409                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4410   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4411     // FIXME: Figure out a cleaner way to do this.
4412     // Try to make use of movq to zero out the top part.
4413     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4414       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4415       if (NewOp.getNode()) {
4416         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4417           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4418                               DAG, Subtarget, dl);
4419       }
4420     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4421       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4422       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4423         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4424                             DAG, Subtarget, dl);
4425     }
4426   }
4427
4428   if (X86::isPSHUFDMask(SVOp))
4429     return Op;
4430
4431   // Check if this can be converted into a logical shift.
4432   bool isLeft = false;
4433   unsigned ShAmt = 0;
4434   SDValue ShVal;
4435   bool isShift = getSubtarget()->hasSSE2() &&
4436     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4437   if (isShift && ShVal.hasOneUse()) {
4438     // If the shifted value has multiple uses, it may be cheaper to use
4439     // v_set0 + movlhps or movhlps, etc.
4440     EVT EltVT = VT.getVectorElementType();
4441     ShAmt *= EltVT.getSizeInBits();
4442     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4443   }
4444
4445   if (X86::isMOVLMask(SVOp)) {
4446     if (V1IsUndef)
4447       return V2;
4448     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4449       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4450     if (!isMMX)
4451       return Op;
4452   }
4453
4454   // FIXME: fold these into legal mask.
4455   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4456                  X86::isMOVSLDUPMask(SVOp) ||
4457                  X86::isMOVHLPSMask(SVOp) ||
4458                  X86::isMOVLHPSMask(SVOp) ||
4459                  X86::isMOVLPMask(SVOp)))
4460     return Op;
4461
4462   if (ShouldXformToMOVHLPS(SVOp) ||
4463       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4464     return CommuteVectorShuffle(SVOp, DAG);
4465
4466   if (isShift) {
4467     // No better options. Use a vshl / vsrl.
4468     EVT EltVT = VT.getVectorElementType();
4469     ShAmt *= EltVT.getSizeInBits();
4470     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4471   }
4472
4473   bool Commuted = false;
4474   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4475   // 1,1,1,1 -> v8i16 though.
4476   V1IsSplat = isSplatVector(V1.getNode());
4477   V2IsSplat = isSplatVector(V2.getNode());
4478
4479   // Canonicalize the splat or undef, if present, to be on the RHS.
4480   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4481     Op = CommuteVectorShuffle(SVOp, DAG);
4482     SVOp = cast<ShuffleVectorSDNode>(Op);
4483     V1 = SVOp->getOperand(0);
4484     V2 = SVOp->getOperand(1);
4485     std::swap(V1IsSplat, V2IsSplat);
4486     std::swap(V1IsUndef, V2IsUndef);
4487     Commuted = true;
4488   }
4489
4490   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4491     // Shuffling low element of v1 into undef, just return v1.
4492     if (V2IsUndef)
4493       return V1;
4494     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4495     // the instruction selector will not match, so get a canonical MOVL with
4496     // swapped operands to undo the commute.
4497     return getMOVL(DAG, dl, VT, V2, V1);
4498   }
4499
4500   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4501       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4502       X86::isUNPCKLMask(SVOp) ||
4503       X86::isUNPCKHMask(SVOp))
4504     return Op;
4505
4506   if (V2IsSplat) {
4507     // Normalize mask so all entries that point to V2 points to its first
4508     // element then try to match unpck{h|l} again. If match, return a
4509     // new vector_shuffle with the corrected mask.
4510     SDValue NewMask = NormalizeMask(SVOp, DAG);
4511     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4512     if (NSVOp != SVOp) {
4513       if (X86::isUNPCKLMask(NSVOp, true)) {
4514         return NewMask;
4515       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4516         return NewMask;
4517       }
4518     }
4519   }
4520
4521   if (Commuted) {
4522     // Commute is back and try unpck* again.
4523     // FIXME: this seems wrong.
4524     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4525     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4526     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4527         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4528         X86::isUNPCKLMask(NewSVOp) ||
4529         X86::isUNPCKHMask(NewSVOp))
4530       return NewOp;
4531   }
4532
4533   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4534
4535   // Normalize the node to match x86 shuffle ops if needed
4536   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4537     return CommuteVectorShuffle(SVOp, DAG);
4538
4539   // Check for legal shuffle and return?
4540   SmallVector<int, 16> PermMask;
4541   SVOp->getMask(PermMask);
4542   if (isShuffleMaskLegal(PermMask, VT))
4543     return Op;
4544
4545   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4546   if (VT == MVT::v8i16) {
4547     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4548     if (NewOp.getNode())
4549       return NewOp;
4550   }
4551
4552   if (VT == MVT::v16i8) {
4553     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4554     if (NewOp.getNode())
4555       return NewOp;
4556   }
4557
4558   // Handle all 4 wide cases with a number of shuffles except for MMX.
4559   if (NumElems == 4 && !isMMX)
4560     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4561
4562   return SDValue();
4563 }
4564
4565 SDValue
4566 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4567                                                 SelectionDAG &DAG) {
4568   EVT VT = Op.getValueType();
4569   DebugLoc dl = Op.getDebugLoc();
4570   if (VT.getSizeInBits() == 8) {
4571     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4572                                     Op.getOperand(0), Op.getOperand(1));
4573     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4574                                     DAG.getValueType(VT));
4575     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4576   } else if (VT.getSizeInBits() == 16) {
4577     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4578     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4579     if (Idx == 0)
4580       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4581                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4582                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4583                                                  MVT::v4i32,
4584                                                  Op.getOperand(0)),
4585                                      Op.getOperand(1)));
4586     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4587                                     Op.getOperand(0), Op.getOperand(1));
4588     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4589                                     DAG.getValueType(VT));
4590     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4591   } else if (VT == MVT::f32) {
4592     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4593     // the result back to FR32 register. It's only worth matching if the
4594     // result has a single use which is a store or a bitcast to i32.  And in
4595     // the case of a store, it's not worth it if the index is a constant 0,
4596     // because a MOVSSmr can be used instead, which is smaller and faster.
4597     if (!Op.hasOneUse())
4598       return SDValue();
4599     SDNode *User = *Op.getNode()->use_begin();
4600     if ((User->getOpcode() != ISD::STORE ||
4601          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4602           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4603         (User->getOpcode() != ISD::BIT_CONVERT ||
4604          User->getValueType(0) != MVT::i32))
4605       return SDValue();
4606     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4607                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4608                                               Op.getOperand(0)),
4609                                               Op.getOperand(1));
4610     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4611   } else if (VT == MVT::i32) {
4612     // ExtractPS works with constant index.
4613     if (isa<ConstantSDNode>(Op.getOperand(1)))
4614       return Op;
4615   }
4616   return SDValue();
4617 }
4618
4619
4620 SDValue
4621 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4622   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4623     return SDValue();
4624
4625   if (Subtarget->hasSSE41()) {
4626     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4627     if (Res.getNode())
4628       return Res;
4629   }
4630
4631   EVT VT = Op.getValueType();
4632   DebugLoc dl = Op.getDebugLoc();
4633   // TODO: handle v16i8.
4634   if (VT.getSizeInBits() == 16) {
4635     SDValue Vec = Op.getOperand(0);
4636     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4637     if (Idx == 0)
4638       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4639                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4640                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4641                                                  MVT::v4i32, Vec),
4642                                      Op.getOperand(1)));
4643     // Transform it so it match pextrw which produces a 32-bit result.
4644     EVT EltVT = MVT::i32;
4645     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4646                                     Op.getOperand(0), Op.getOperand(1));
4647     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4648                                     DAG.getValueType(VT));
4649     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4650   } else if (VT.getSizeInBits() == 32) {
4651     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4652     if (Idx == 0)
4653       return Op;
4654
4655     // SHUFPS the element to the lowest double word, then movss.
4656     int Mask[4] = { Idx, -1, -1, -1 };
4657     EVT VVT = Op.getOperand(0).getValueType();
4658     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4659                                        DAG.getUNDEF(VVT), Mask);
4660     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4661                        DAG.getIntPtrConstant(0));
4662   } else if (VT.getSizeInBits() == 64) {
4663     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4664     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4665     //        to match extract_elt for f64.
4666     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4667     if (Idx == 0)
4668       return Op;
4669
4670     // UNPCKHPD the element to the lowest double word, then movsd.
4671     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4672     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4673     int Mask[2] = { 1, -1 };
4674     EVT VVT = Op.getOperand(0).getValueType();
4675     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4676                                        DAG.getUNDEF(VVT), Mask);
4677     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4678                        DAG.getIntPtrConstant(0));
4679   }
4680
4681   return SDValue();
4682 }
4683
4684 SDValue
4685 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4686   EVT VT = Op.getValueType();
4687   EVT EltVT = VT.getVectorElementType();
4688   DebugLoc dl = Op.getDebugLoc();
4689
4690   SDValue N0 = Op.getOperand(0);
4691   SDValue N1 = Op.getOperand(1);
4692   SDValue N2 = Op.getOperand(2);
4693
4694   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4695       isa<ConstantSDNode>(N2)) {
4696     unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4697                                                 : X86ISD::PINSRW;
4698     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4699     // argument.
4700     if (N1.getValueType() != MVT::i32)
4701       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4702     if (N2.getValueType() != MVT::i32)
4703       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4704     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4705   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4706     // Bits [7:6] of the constant are the source select.  This will always be
4707     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4708     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4709     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4710     // Bits [5:4] of the constant are the destination select.  This is the
4711     //  value of the incoming immediate.
4712     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4713     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4714     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4715     // Create this as a scalar to vector..
4716     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4717     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4718   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4719     // PINSR* works with constant index.
4720     return Op;
4721   }
4722   return SDValue();
4723 }
4724
4725 SDValue
4726 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4727   EVT VT = Op.getValueType();
4728   EVT EltVT = VT.getVectorElementType();
4729
4730   if (Subtarget->hasSSE41())
4731     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4732
4733   if (EltVT == MVT::i8)
4734     return SDValue();
4735
4736   DebugLoc dl = Op.getDebugLoc();
4737   SDValue N0 = Op.getOperand(0);
4738   SDValue N1 = Op.getOperand(1);
4739   SDValue N2 = Op.getOperand(2);
4740
4741   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4742     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4743     // as its second argument.
4744     if (N1.getValueType() != MVT::i32)
4745       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4746     if (N2.getValueType() != MVT::i32)
4747       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4748     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4749   }
4750   return SDValue();
4751 }
4752
4753 SDValue
4754 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4755   DebugLoc dl = Op.getDebugLoc();
4756   if (Op.getValueType() == MVT::v2f32)
4757     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4758                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4759                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4760                                                Op.getOperand(0))));
4761
4762   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4763     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4764
4765   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4766   EVT VT = MVT::v2i32;
4767   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4768   default: break;
4769   case MVT::v16i8:
4770   case MVT::v8i16:
4771     VT = MVT::v4i32;
4772     break;
4773   }
4774   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4775                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4776 }
4777
4778 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4779 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4780 // one of the above mentioned nodes. It has to be wrapped because otherwise
4781 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4782 // be used to form addressing mode. These wrapped nodes will be selected
4783 // into MOV32ri.
4784 SDValue
4785 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4786   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4787
4788   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4789   // global base reg.
4790   unsigned char OpFlag = 0;
4791   unsigned WrapperKind = X86ISD::Wrapper;
4792   CodeModel::Model M = getTargetMachine().getCodeModel();
4793
4794   if (Subtarget->isPICStyleRIPRel() &&
4795       (M == CodeModel::Small || M == CodeModel::Kernel))
4796     WrapperKind = X86ISD::WrapperRIP;
4797   else if (Subtarget->isPICStyleGOT())
4798     OpFlag = X86II::MO_GOTOFF;
4799   else if (Subtarget->isPICStyleStubPIC())
4800     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4801
4802   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4803                                              CP->getAlignment(),
4804                                              CP->getOffset(), OpFlag);
4805   DebugLoc DL = CP->getDebugLoc();
4806   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4807   // With PIC, the address is actually $g + Offset.
4808   if (OpFlag) {
4809     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4810                          DAG.getNode(X86ISD::GlobalBaseReg,
4811                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4812                          Result);
4813   }
4814
4815   return Result;
4816 }
4817
4818 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4819   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4820
4821   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4822   // global base reg.
4823   unsigned char OpFlag = 0;
4824   unsigned WrapperKind = X86ISD::Wrapper;
4825   CodeModel::Model M = getTargetMachine().getCodeModel();
4826
4827   if (Subtarget->isPICStyleRIPRel() &&
4828       (M == CodeModel::Small || M == CodeModel::Kernel))
4829     WrapperKind = X86ISD::WrapperRIP;
4830   else if (Subtarget->isPICStyleGOT())
4831     OpFlag = X86II::MO_GOTOFF;
4832   else if (Subtarget->isPICStyleStubPIC())
4833     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4834
4835   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4836                                           OpFlag);
4837   DebugLoc DL = JT->getDebugLoc();
4838   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4839
4840   // With PIC, the address is actually $g + Offset.
4841   if (OpFlag) {
4842     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4843                          DAG.getNode(X86ISD::GlobalBaseReg,
4844                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4845                          Result);
4846   }
4847
4848   return Result;
4849 }
4850
4851 SDValue
4852 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4853   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4854
4855   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4856   // global base reg.
4857   unsigned char OpFlag = 0;
4858   unsigned WrapperKind = X86ISD::Wrapper;
4859   CodeModel::Model M = getTargetMachine().getCodeModel();
4860
4861   if (Subtarget->isPICStyleRIPRel() &&
4862       (M == CodeModel::Small || M == CodeModel::Kernel))
4863     WrapperKind = X86ISD::WrapperRIP;
4864   else if (Subtarget->isPICStyleGOT())
4865     OpFlag = X86II::MO_GOTOFF;
4866   else if (Subtarget->isPICStyleStubPIC())
4867     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4868
4869   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4870
4871   DebugLoc DL = Op.getDebugLoc();
4872   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4873
4874
4875   // With PIC, the address is actually $g + Offset.
4876   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4877       !Subtarget->is64Bit()) {
4878     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4879                          DAG.getNode(X86ISD::GlobalBaseReg,
4880                                      DebugLoc::getUnknownLoc(),
4881                                      getPointerTy()),
4882                          Result);
4883   }
4884
4885   return Result;
4886 }
4887
4888 SDValue
4889 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4890   // Create the TargetBlockAddressAddress node.
4891   unsigned char OpFlags =
4892     Subtarget->ClassifyBlockAddressReference();
4893   CodeModel::Model M = getTargetMachine().getCodeModel();
4894   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4895   DebugLoc dl = Op.getDebugLoc();
4896   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4897                                        /*isTarget=*/true, OpFlags);
4898
4899   if (Subtarget->isPICStyleRIPRel() &&
4900       (M == CodeModel::Small || M == CodeModel::Kernel))
4901     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4902   else
4903     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4904
4905   // With PIC, the address is actually $g + Offset.
4906   if (isGlobalRelativeToPICBase(OpFlags)) {
4907     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4908                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4909                          Result);
4910   }
4911
4912   return Result;
4913 }
4914
4915 SDValue
4916 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4917                                       int64_t Offset,
4918                                       SelectionDAG &DAG) const {
4919   // Create the TargetGlobalAddress node, folding in the constant
4920   // offset if it is legal.
4921   unsigned char OpFlags =
4922     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4923   CodeModel::Model M = getTargetMachine().getCodeModel();
4924   SDValue Result;
4925   if (OpFlags == X86II::MO_NO_FLAG &&
4926       X86::isOffsetSuitableForCodeModel(Offset, M)) {
4927     // A direct static reference to a global.
4928     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4929     Offset = 0;
4930   } else {
4931     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4932   }
4933
4934   if (Subtarget->isPICStyleRIPRel() &&
4935       (M == CodeModel::Small || M == CodeModel::Kernel))
4936     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4937   else
4938     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4939
4940   // With PIC, the address is actually $g + Offset.
4941   if (isGlobalRelativeToPICBase(OpFlags)) {
4942     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4943                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4944                          Result);
4945   }
4946
4947   // For globals that require a load from a stub to get the address, emit the
4948   // load.
4949   if (isGlobalStubReference(OpFlags))
4950     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4951                          PseudoSourceValue::getGOT(), 0);
4952
4953   // If there was a non-zero offset that we didn't fold, create an explicit
4954   // addition for it.
4955   if (Offset != 0)
4956     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4957                          DAG.getConstant(Offset, getPointerTy()));
4958
4959   return Result;
4960 }
4961
4962 SDValue
4963 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4964   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4965   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4966   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4967 }
4968
4969 static SDValue
4970 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4971            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4972            unsigned char OperandFlags) {
4973   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4974   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4975   DebugLoc dl = GA->getDebugLoc();
4976   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4977                                            GA->getValueType(0),
4978                                            GA->getOffset(),
4979                                            OperandFlags);
4980   if (InFlag) {
4981     SDValue Ops[] = { Chain,  TGA, *InFlag };
4982     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4983   } else {
4984     SDValue Ops[]  = { Chain, TGA };
4985     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4986   }
4987
4988   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
4989   MFI->setHasCalls(true);
4990
4991   SDValue Flag = Chain.getValue(1);
4992   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4993 }
4994
4995 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4996 static SDValue
4997 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4998                                 const EVT PtrVT) {
4999   SDValue InFlag;
5000   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5001   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5002                                      DAG.getNode(X86ISD::GlobalBaseReg,
5003                                                  DebugLoc::getUnknownLoc(),
5004                                                  PtrVT), InFlag);
5005   InFlag = Chain.getValue(1);
5006
5007   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5008 }
5009
5010 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5011 static SDValue
5012 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5013                                 const EVT PtrVT) {
5014   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5015                     X86::RAX, X86II::MO_TLSGD);
5016 }
5017
5018 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5019 // "local exec" model.
5020 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5021                                    const EVT PtrVT, TLSModel::Model model,
5022                                    bool is64Bit) {
5023   DebugLoc dl = GA->getDebugLoc();
5024   // Get the Thread Pointer
5025   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5026                              DebugLoc::getUnknownLoc(), PtrVT,
5027                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5028                                              MVT::i32));
5029
5030   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5031                                       NULL, 0);
5032
5033   unsigned char OperandFlags = 0;
5034   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5035   // initialexec.
5036   unsigned WrapperKind = X86ISD::Wrapper;
5037   if (model == TLSModel::LocalExec) {
5038     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5039   } else if (is64Bit) {
5040     assert(model == TLSModel::InitialExec);
5041     OperandFlags = X86II::MO_GOTTPOFF;
5042     WrapperKind = X86ISD::WrapperRIP;
5043   } else {
5044     assert(model == TLSModel::InitialExec);
5045     OperandFlags = X86II::MO_INDNTPOFF;
5046   }
5047
5048   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5049   // exec)
5050   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5051                                            GA->getOffset(), OperandFlags);
5052   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5053
5054   if (model == TLSModel::InitialExec)
5055     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5056                          PseudoSourceValue::getGOT(), 0);
5057
5058   // The address of the thread local variable is the add of the thread
5059   // pointer with the offset of the variable.
5060   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5061 }
5062
5063 SDValue
5064 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5065   // TODO: implement the "local dynamic" model
5066   // TODO: implement the "initial exec"model for pic executables
5067   assert(Subtarget->isTargetELF() &&
5068          "TLS not implemented for non-ELF targets");
5069   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5070   const GlobalValue *GV = GA->getGlobal();
5071
5072   // If GV is an alias then use the aliasee for determining
5073   // thread-localness.
5074   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5075     GV = GA->resolveAliasedGlobal(false);
5076
5077   TLSModel::Model model = getTLSModel(GV,
5078                                       getTargetMachine().getRelocationModel());
5079
5080   switch (model) {
5081   case TLSModel::GeneralDynamic:
5082   case TLSModel::LocalDynamic: // not implemented
5083     if (Subtarget->is64Bit())
5084       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5085     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5086
5087   case TLSModel::InitialExec:
5088   case TLSModel::LocalExec:
5089     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5090                                Subtarget->is64Bit());
5091   }
5092
5093   llvm_unreachable("Unreachable");
5094   return SDValue();
5095 }
5096
5097
5098 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5099 /// take a 2 x i32 value to shift plus a shift amount.
5100 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5101   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5102   EVT VT = Op.getValueType();
5103   unsigned VTBits = VT.getSizeInBits();
5104   DebugLoc dl = Op.getDebugLoc();
5105   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5106   SDValue ShOpLo = Op.getOperand(0);
5107   SDValue ShOpHi = Op.getOperand(1);
5108   SDValue ShAmt  = Op.getOperand(2);
5109   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5110                                      DAG.getConstant(VTBits - 1, MVT::i8))
5111                        : DAG.getConstant(0, VT);
5112
5113   SDValue Tmp2, Tmp3;
5114   if (Op.getOpcode() == ISD::SHL_PARTS) {
5115     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5116     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5117   } else {
5118     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5119     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5120   }
5121
5122   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5123                                 DAG.getConstant(VTBits, MVT::i8));
5124   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5125                              AndNode, DAG.getConstant(0, MVT::i8));
5126
5127   SDValue Hi, Lo;
5128   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5129   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5130   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5131
5132   if (Op.getOpcode() == ISD::SHL_PARTS) {
5133     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5134     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5135   } else {
5136     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5137     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5138   }
5139
5140   SDValue Ops[2] = { Lo, Hi };
5141   return DAG.getMergeValues(Ops, 2, dl);
5142 }
5143
5144 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5145   EVT SrcVT = Op.getOperand(0).getValueType();
5146
5147   if (SrcVT.isVector()) {
5148     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5149       return Op;
5150     }
5151     return SDValue();
5152   }
5153
5154   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5155          "Unknown SINT_TO_FP to lower!");
5156
5157   // These are really Legal; return the operand so the caller accepts it as
5158   // Legal.
5159   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5160     return Op;
5161   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5162       Subtarget->is64Bit()) {
5163     return Op;
5164   }
5165
5166   DebugLoc dl = Op.getDebugLoc();
5167   unsigned Size = SrcVT.getSizeInBits()/8;
5168   MachineFunction &MF = DAG.getMachineFunction();
5169   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5170   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5171   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5172                                StackSlot,
5173                                PseudoSourceValue::getFixedStack(SSFI), 0);
5174   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5175 }
5176
5177 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5178                                      SDValue StackSlot,
5179                                      SelectionDAG &DAG) {
5180   // Build the FILD
5181   DebugLoc dl = Op.getDebugLoc();
5182   SDVTList Tys;
5183   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5184   if (useSSE)
5185     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5186   else
5187     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5188   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5189   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5190                                Tys, Ops, array_lengthof(Ops));
5191
5192   if (useSSE) {
5193     Chain = Result.getValue(1);
5194     SDValue InFlag = Result.getValue(2);
5195
5196     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5197     // shouldn't be necessary except that RFP cannot be live across
5198     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5199     MachineFunction &MF = DAG.getMachineFunction();
5200     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5201     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5202     Tys = DAG.getVTList(MVT::Other);
5203     SDValue Ops[] = {
5204       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5205     };
5206     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5207     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5208                          PseudoSourceValue::getFixedStack(SSFI), 0);
5209   }
5210
5211   return Result;
5212 }
5213
5214 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5215 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5216   // This algorithm is not obvious. Here it is in C code, more or less:
5217   /*
5218     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5219       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5220       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5221
5222       // Copy ints to xmm registers.
5223       __m128i xh = _mm_cvtsi32_si128( hi );
5224       __m128i xl = _mm_cvtsi32_si128( lo );
5225
5226       // Combine into low half of a single xmm register.
5227       __m128i x = _mm_unpacklo_epi32( xh, xl );
5228       __m128d d;
5229       double sd;
5230
5231       // Merge in appropriate exponents to give the integer bits the right
5232       // magnitude.
5233       x = _mm_unpacklo_epi32( x, exp );
5234
5235       // Subtract away the biases to deal with the IEEE-754 double precision
5236       // implicit 1.
5237       d = _mm_sub_pd( (__m128d) x, bias );
5238
5239       // All conversions up to here are exact. The correctly rounded result is
5240       // calculated using the current rounding mode using the following
5241       // horizontal add.
5242       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5243       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5244                                 // store doesn't really need to be here (except
5245                                 // maybe to zero the other double)
5246       return sd;
5247     }
5248   */
5249
5250   DebugLoc dl = Op.getDebugLoc();
5251   LLVMContext *Context = DAG.getContext();
5252
5253   // Build some magic constants.
5254   std::vector<Constant*> CV0;
5255   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5256   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5257   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5258   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5259   Constant *C0 = ConstantVector::get(CV0);
5260   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5261
5262   std::vector<Constant*> CV1;
5263   CV1.push_back(
5264     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5265   CV1.push_back(
5266     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5267   Constant *C1 = ConstantVector::get(CV1);
5268   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5269
5270   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5271                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5272                                         Op.getOperand(0),
5273                                         DAG.getIntPtrConstant(1)));
5274   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5275                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5276                                         Op.getOperand(0),
5277                                         DAG.getIntPtrConstant(0)));
5278   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5279   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5280                               PseudoSourceValue::getConstantPool(), 0,
5281                               false, 16);
5282   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5283   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5284   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5285                               PseudoSourceValue::getConstantPool(), 0,
5286                               false, 16);
5287   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5288
5289   // Add the halves; easiest way is to swap them into another reg first.
5290   int ShufMask[2] = { 1, -1 };
5291   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5292                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5293   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5294   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5295                      DAG.getIntPtrConstant(0));
5296 }
5297
5298 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5299 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5300   DebugLoc dl = Op.getDebugLoc();
5301   // FP constant to bias correct the final result.
5302   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5303                                    MVT::f64);
5304
5305   // Load the 32-bit value into an XMM register.
5306   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5307                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5308                                          Op.getOperand(0),
5309                                          DAG.getIntPtrConstant(0)));
5310
5311   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5312                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5313                      DAG.getIntPtrConstant(0));
5314
5315   // Or the load with the bias.
5316   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5317                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5318                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5319                                                    MVT::v2f64, Load)),
5320                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5321                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5322                                                    MVT::v2f64, Bias)));
5323   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5324                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5325                    DAG.getIntPtrConstant(0));
5326
5327   // Subtract the bias.
5328   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5329
5330   // Handle final rounding.
5331   EVT DestVT = Op.getValueType();
5332
5333   if (DestVT.bitsLT(MVT::f64)) {
5334     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5335                        DAG.getIntPtrConstant(0));
5336   } else if (DestVT.bitsGT(MVT::f64)) {
5337     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5338   }
5339
5340   // Handle final rounding.
5341   return Sub;
5342 }
5343
5344 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5345   SDValue N0 = Op.getOperand(0);
5346   DebugLoc dl = Op.getDebugLoc();
5347
5348   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5349   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5350   // the optimization here.
5351   if (DAG.SignBitIsZero(N0))
5352     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5353
5354   EVT SrcVT = N0.getValueType();
5355   if (SrcVT == MVT::i64) {
5356     // We only handle SSE2 f64 target here; caller can expand the rest.
5357     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5358       return SDValue();
5359
5360     return LowerUINT_TO_FP_i64(Op, DAG);
5361   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5362     return LowerUINT_TO_FP_i32(Op, DAG);
5363   }
5364
5365   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5366
5367   // Make a 64-bit buffer, and use it to build an FILD.
5368   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5369   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5370   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5371                                    getPointerTy(), StackSlot, WordOff);
5372   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5373                                 StackSlot, NULL, 0);
5374   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5375                                 OffsetSlot, NULL, 0);
5376   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5377 }
5378
5379 std::pair<SDValue,SDValue> X86TargetLowering::
5380 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5381   DebugLoc dl = Op.getDebugLoc();
5382
5383   EVT DstTy = Op.getValueType();
5384
5385   if (!IsSigned) {
5386     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5387     DstTy = MVT::i64;
5388   }
5389
5390   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5391          DstTy.getSimpleVT() >= MVT::i16 &&
5392          "Unknown FP_TO_SINT to lower!");
5393
5394   // These are really Legal.
5395   if (DstTy == MVT::i32 &&
5396       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5397     return std::make_pair(SDValue(), SDValue());
5398   if (Subtarget->is64Bit() &&
5399       DstTy == MVT::i64 &&
5400       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5401     return std::make_pair(SDValue(), SDValue());
5402
5403   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5404   // stack slot.
5405   MachineFunction &MF = DAG.getMachineFunction();
5406   unsigned MemSize = DstTy.getSizeInBits()/8;
5407   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5408   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5409
5410   unsigned Opc;
5411   switch (DstTy.getSimpleVT().SimpleTy) {
5412   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5413   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5414   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5415   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5416   }
5417
5418   SDValue Chain = DAG.getEntryNode();
5419   SDValue Value = Op.getOperand(0);
5420   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5421     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5422     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5423                          PseudoSourceValue::getFixedStack(SSFI), 0);
5424     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5425     SDValue Ops[] = {
5426       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5427     };
5428     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5429     Chain = Value.getValue(1);
5430     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5431     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5432   }
5433
5434   // Build the FP_TO_INT*_IN_MEM
5435   SDValue Ops[] = { Chain, Value, StackSlot };
5436   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5437
5438   return std::make_pair(FIST, StackSlot);
5439 }
5440
5441 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5442   if (Op.getValueType().isVector()) {
5443     if (Op.getValueType() == MVT::v2i32 &&
5444         Op.getOperand(0).getValueType() == MVT::v2f64) {
5445       return Op;
5446     }
5447     return SDValue();
5448   }
5449
5450   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5451   SDValue FIST = Vals.first, StackSlot = Vals.second;
5452   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5453   if (FIST.getNode() == 0) return Op;
5454
5455   // Load the result.
5456   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5457                      FIST, StackSlot, NULL, 0);
5458 }
5459
5460 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5461   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5462   SDValue FIST = Vals.first, StackSlot = Vals.second;
5463   assert(FIST.getNode() && "Unexpected failure");
5464
5465   // Load the result.
5466   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5467                      FIST, StackSlot, NULL, 0);
5468 }
5469
5470 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5471   LLVMContext *Context = DAG.getContext();
5472   DebugLoc dl = Op.getDebugLoc();
5473   EVT VT = Op.getValueType();
5474   EVT EltVT = VT;
5475   if (VT.isVector())
5476     EltVT = VT.getVectorElementType();
5477   std::vector<Constant*> CV;
5478   if (EltVT == MVT::f64) {
5479     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5480     CV.push_back(C);
5481     CV.push_back(C);
5482   } else {
5483     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5484     CV.push_back(C);
5485     CV.push_back(C);
5486     CV.push_back(C);
5487     CV.push_back(C);
5488   }
5489   Constant *C = ConstantVector::get(CV);
5490   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5491   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5492                                PseudoSourceValue::getConstantPool(), 0,
5493                                false, 16);
5494   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5495 }
5496
5497 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5498   LLVMContext *Context = DAG.getContext();
5499   DebugLoc dl = Op.getDebugLoc();
5500   EVT VT = Op.getValueType();
5501   EVT EltVT = VT;
5502   if (VT.isVector())
5503     EltVT = VT.getVectorElementType();
5504   std::vector<Constant*> CV;
5505   if (EltVT == MVT::f64) {
5506     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5507     CV.push_back(C);
5508     CV.push_back(C);
5509   } else {
5510     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5511     CV.push_back(C);
5512     CV.push_back(C);
5513     CV.push_back(C);
5514     CV.push_back(C);
5515   }
5516   Constant *C = ConstantVector::get(CV);
5517   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5518   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5519                                PseudoSourceValue::getConstantPool(), 0,
5520                                false, 16);
5521   if (VT.isVector()) {
5522     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5523                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5524                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5525                                 Op.getOperand(0)),
5526                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5527   } else {
5528     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5529   }
5530 }
5531
5532 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5533   LLVMContext *Context = DAG.getContext();
5534   SDValue Op0 = Op.getOperand(0);
5535   SDValue Op1 = Op.getOperand(1);
5536   DebugLoc dl = Op.getDebugLoc();
5537   EVT VT = Op.getValueType();
5538   EVT SrcVT = Op1.getValueType();
5539
5540   // If second operand is smaller, extend it first.
5541   if (SrcVT.bitsLT(VT)) {
5542     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5543     SrcVT = VT;
5544   }
5545   // And if it is bigger, shrink it first.
5546   if (SrcVT.bitsGT(VT)) {
5547     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5548     SrcVT = VT;
5549   }
5550
5551   // At this point the operands and the result should have the same
5552   // type, and that won't be f80 since that is not custom lowered.
5553
5554   // First get the sign bit of second operand.
5555   std::vector<Constant*> CV;
5556   if (SrcVT == MVT::f64) {
5557     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5558     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5559   } else {
5560     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5561     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5562     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5563     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5564   }
5565   Constant *C = ConstantVector::get(CV);
5566   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5567   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5568                                 PseudoSourceValue::getConstantPool(), 0,
5569                                 false, 16);
5570   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5571
5572   // Shift sign bit right or left if the two operands have different types.
5573   if (SrcVT.bitsGT(VT)) {
5574     // Op0 is MVT::f32, Op1 is MVT::f64.
5575     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5576     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5577                           DAG.getConstant(32, MVT::i32));
5578     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5579     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5580                           DAG.getIntPtrConstant(0));
5581   }
5582
5583   // Clear first operand sign bit.
5584   CV.clear();
5585   if (VT == MVT::f64) {
5586     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5587     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5588   } else {
5589     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5590     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5591     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5592     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5593   }
5594   C = ConstantVector::get(CV);
5595   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5596   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5597                                 PseudoSourceValue::getConstantPool(), 0,
5598                                 false, 16);
5599   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5600
5601   // Or the value with the sign bit.
5602   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5603 }
5604
5605 /// Emit nodes that will be selected as "test Op0,Op0", or something
5606 /// equivalent.
5607 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5608                                     SelectionDAG &DAG) {
5609   DebugLoc dl = Op.getDebugLoc();
5610
5611   // CF and OF aren't always set the way we want. Determine which
5612   // of these we need.
5613   bool NeedCF = false;
5614   bool NeedOF = false;
5615   switch (X86CC) {
5616   case X86::COND_A: case X86::COND_AE:
5617   case X86::COND_B: case X86::COND_BE:
5618     NeedCF = true;
5619     break;
5620   case X86::COND_G: case X86::COND_GE:
5621   case X86::COND_L: case X86::COND_LE:
5622   case X86::COND_O: case X86::COND_NO:
5623     NeedOF = true;
5624     break;
5625   default: break;
5626   }
5627
5628   // See if we can use the EFLAGS value from the operand instead of
5629   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5630   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5631   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5632     unsigned Opcode = 0;
5633     unsigned NumOperands = 0;
5634     switch (Op.getNode()->getOpcode()) {
5635     case ISD::ADD:
5636       // Due to an isel shortcoming, be conservative if this add is likely to
5637       // be selected as part of a load-modify-store instruction. When the root
5638       // node in a match is a store, isel doesn't know how to remap non-chain
5639       // non-flag uses of other nodes in the match, such as the ADD in this
5640       // case. This leads to the ADD being left around and reselected, with
5641       // the result being two adds in the output.
5642       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5643            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5644         if (UI->getOpcode() == ISD::STORE)
5645           goto default_case;
5646       if (ConstantSDNode *C =
5647             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5648         // An add of one will be selected as an INC.
5649         if (C->getAPIntValue() == 1) {
5650           Opcode = X86ISD::INC;
5651           NumOperands = 1;
5652           break;
5653         }
5654         // An add of negative one (subtract of one) will be selected as a DEC.
5655         if (C->getAPIntValue().isAllOnesValue()) {
5656           Opcode = X86ISD::DEC;
5657           NumOperands = 1;
5658           break;
5659         }
5660       }
5661       // Otherwise use a regular EFLAGS-setting add.
5662       Opcode = X86ISD::ADD;
5663       NumOperands = 2;
5664       break;
5665     case ISD::AND: {
5666       // If the primary and result isn't used, don't bother using X86ISD::AND,
5667       // because a TEST instruction will be better.
5668       bool NonFlagUse = false;
5669       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5670              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5671         SDNode *User = *UI;
5672         unsigned UOpNo = UI.getOperandNo();
5673         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5674           // Look pass truncate.
5675           UOpNo = User->use_begin().getOperandNo();
5676           User = *User->use_begin();
5677         }
5678         if (User->getOpcode() != ISD::BRCOND &&
5679             User->getOpcode() != ISD::SETCC &&
5680             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5681           NonFlagUse = true;
5682           break;
5683         }
5684       }
5685       if (!NonFlagUse)
5686         break;
5687     }
5688     // FALL THROUGH
5689     case ISD::SUB:
5690     case ISD::OR:
5691     case ISD::XOR:
5692       // Due to the ISEL shortcoming noted above, be conservative if this op is
5693       // likely to be selected as part of a load-modify-store instruction.
5694       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5695            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5696         if (UI->getOpcode() == ISD::STORE)
5697           goto default_case;
5698       // Otherwise use a regular EFLAGS-setting instruction.
5699       switch (Op.getNode()->getOpcode()) {
5700       case ISD::SUB: Opcode = X86ISD::SUB; break;
5701       case ISD::OR:  Opcode = X86ISD::OR;  break;
5702       case ISD::XOR: Opcode = X86ISD::XOR; break;
5703       case ISD::AND: Opcode = X86ISD::AND; break;
5704       default: llvm_unreachable("unexpected operator!");
5705       }
5706       NumOperands = 2;
5707       break;
5708     case X86ISD::ADD:
5709     case X86ISD::SUB:
5710     case X86ISD::INC:
5711     case X86ISD::DEC:
5712     case X86ISD::OR:
5713     case X86ISD::XOR:
5714     case X86ISD::AND:
5715       return SDValue(Op.getNode(), 1);
5716     default:
5717     default_case:
5718       break;
5719     }
5720     if (Opcode != 0) {
5721       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5722       SmallVector<SDValue, 4> Ops;
5723       for (unsigned i = 0; i != NumOperands; ++i)
5724         Ops.push_back(Op.getOperand(i));
5725       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5726       DAG.ReplaceAllUsesWith(Op, New);
5727       return SDValue(New.getNode(), 1);
5728     }
5729   }
5730
5731   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5732   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5733                      DAG.getConstant(0, Op.getValueType()));
5734 }
5735
5736 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5737 /// equivalent.
5738 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5739                                    SelectionDAG &DAG) {
5740   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5741     if (C->getAPIntValue() == 0)
5742       return EmitTest(Op0, X86CC, DAG);
5743
5744   DebugLoc dl = Op0.getDebugLoc();
5745   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5746 }
5747
5748 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5749 /// if it's possible.
5750 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5751                          DebugLoc dl, SelectionDAG &DAG) {
5752   SDValue LHS, RHS;
5753   if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5754     if (ConstantSDNode *Op010C =
5755         dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5756       if (Op010C->getZExtValue() == 1) {
5757         LHS = Op0.getOperand(0);
5758         RHS = Op0.getOperand(1).getOperand(1);
5759       }
5760   } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5761     if (ConstantSDNode *Op000C =
5762         dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5763       if (Op000C->getZExtValue() == 1) {
5764         LHS = Op0.getOperand(1);
5765         RHS = Op0.getOperand(0).getOperand(1);
5766       }
5767   } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5768     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5769     SDValue AndLHS = Op0.getOperand(0);
5770     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5771       LHS = AndLHS.getOperand(0);
5772       RHS = AndLHS.getOperand(1);
5773     }
5774   }
5775
5776   if (LHS.getNode()) {
5777     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5778     // instruction.  Since the shift amount is in-range-or-undefined, we know
5779     // that doing a bittest on the i16 value is ok.  We extend to i32 because
5780     // the encoding for the i16 version is larger than the i32 version.
5781     if (LHS.getValueType() == MVT::i8)
5782       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5783
5784     // If the operand types disagree, extend the shift amount to match.  Since
5785     // BT ignores high bits (like shifts) we can use anyextend.
5786     if (LHS.getValueType() != RHS.getValueType())
5787       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5788
5789     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5790     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5791     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5792                        DAG.getConstant(Cond, MVT::i8), BT);
5793   }
5794
5795   return SDValue();
5796 }
5797
5798 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5799   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5800   SDValue Op0 = Op.getOperand(0);
5801   SDValue Op1 = Op.getOperand(1);
5802   DebugLoc dl = Op.getDebugLoc();
5803   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5804
5805   // Optimize to BT if possible.
5806   // Lower (X & (1 << N)) == 0 to BT(X, N).
5807   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5808   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5809   if (Op0.getOpcode() == ISD::AND &&
5810       Op0.hasOneUse() &&
5811       Op1.getOpcode() == ISD::Constant &&
5812       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5813       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5814     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5815     if (NewSetCC.getNode())
5816       return NewSetCC;
5817   }
5818
5819   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5820   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5821   if (X86CC == X86::COND_INVALID)
5822     return SDValue();
5823
5824   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5825
5826   // Use sbb x, x to materialize carry bit into a GPR.
5827   if (X86CC == X86::COND_B)
5828     return DAG.getNode(ISD::AND, dl, MVT::i8,
5829                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5830                                    DAG.getConstant(X86CC, MVT::i8), Cond),
5831                        DAG.getConstant(1, MVT::i8));
5832
5833   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5834                      DAG.getConstant(X86CC, MVT::i8), Cond);
5835 }
5836
5837 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5838   SDValue Cond;
5839   SDValue Op0 = Op.getOperand(0);
5840   SDValue Op1 = Op.getOperand(1);
5841   SDValue CC = Op.getOperand(2);
5842   EVT VT = Op.getValueType();
5843   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5844   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5845   DebugLoc dl = Op.getDebugLoc();
5846
5847   if (isFP) {
5848     unsigned SSECC = 8;
5849     EVT VT0 = Op0.getValueType();
5850     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5851     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5852     bool Swap = false;
5853
5854     switch (SetCCOpcode) {
5855     default: break;
5856     case ISD::SETOEQ:
5857     case ISD::SETEQ:  SSECC = 0; break;
5858     case ISD::SETOGT:
5859     case ISD::SETGT: Swap = true; // Fallthrough
5860     case ISD::SETLT:
5861     case ISD::SETOLT: SSECC = 1; break;
5862     case ISD::SETOGE:
5863     case ISD::SETGE: Swap = true; // Fallthrough
5864     case ISD::SETLE:
5865     case ISD::SETOLE: SSECC = 2; break;
5866     case ISD::SETUO:  SSECC = 3; break;
5867     case ISD::SETUNE:
5868     case ISD::SETNE:  SSECC = 4; break;
5869     case ISD::SETULE: Swap = true;
5870     case ISD::SETUGE: SSECC = 5; break;
5871     case ISD::SETULT: Swap = true;
5872     case ISD::SETUGT: SSECC = 6; break;
5873     case ISD::SETO:   SSECC = 7; break;
5874     }
5875     if (Swap)
5876       std::swap(Op0, Op1);
5877
5878     // In the two special cases we can't handle, emit two comparisons.
5879     if (SSECC == 8) {
5880       if (SetCCOpcode == ISD::SETUEQ) {
5881         SDValue UNORD, EQ;
5882         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5883         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5884         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5885       }
5886       else if (SetCCOpcode == ISD::SETONE) {
5887         SDValue ORD, NEQ;
5888         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5889         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5890         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5891       }
5892       llvm_unreachable("Illegal FP comparison");
5893     }
5894     // Handle all other FP comparisons here.
5895     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5896   }
5897
5898   // We are handling one of the integer comparisons here.  Since SSE only has
5899   // GT and EQ comparisons for integer, swapping operands and multiple
5900   // operations may be required for some comparisons.
5901   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5902   bool Swap = false, Invert = false, FlipSigns = false;
5903
5904   switch (VT.getSimpleVT().SimpleTy) {
5905   default: break;
5906   case MVT::v8i8:
5907   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5908   case MVT::v4i16:
5909   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5910   case MVT::v2i32:
5911   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5912   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5913   }
5914
5915   switch (SetCCOpcode) {
5916   default: break;
5917   case ISD::SETNE:  Invert = true;
5918   case ISD::SETEQ:  Opc = EQOpc; break;
5919   case ISD::SETLT:  Swap = true;
5920   case ISD::SETGT:  Opc = GTOpc; break;
5921   case ISD::SETGE:  Swap = true;
5922   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5923   case ISD::SETULT: Swap = true;
5924   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5925   case ISD::SETUGE: Swap = true;
5926   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5927   }
5928   if (Swap)
5929     std::swap(Op0, Op1);
5930
5931   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5932   // bits of the inputs before performing those operations.
5933   if (FlipSigns) {
5934     EVT EltVT = VT.getVectorElementType();
5935     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5936                                       EltVT);
5937     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5938     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5939                                     SignBits.size());
5940     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5941     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5942   }
5943
5944   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5945
5946   // If the logical-not of the result is required, perform that now.
5947   if (Invert)
5948     Result = DAG.getNOT(dl, Result, VT);
5949
5950   return Result;
5951 }
5952
5953 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5954 static bool isX86LogicalCmp(SDValue Op) {
5955   unsigned Opc = Op.getNode()->getOpcode();
5956   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5957     return true;
5958   if (Op.getResNo() == 1 &&
5959       (Opc == X86ISD::ADD ||
5960        Opc == X86ISD::SUB ||
5961        Opc == X86ISD::SMUL ||
5962        Opc == X86ISD::UMUL ||
5963        Opc == X86ISD::INC ||
5964        Opc == X86ISD::DEC ||
5965        Opc == X86ISD::OR ||
5966        Opc == X86ISD::XOR ||
5967        Opc == X86ISD::AND))
5968     return true;
5969
5970   return false;
5971 }
5972
5973 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5974   bool addTest = true;
5975   SDValue Cond  = Op.getOperand(0);
5976   DebugLoc dl = Op.getDebugLoc();
5977   SDValue CC;
5978
5979   if (Cond.getOpcode() == ISD::SETCC) {
5980     SDValue NewCond = LowerSETCC(Cond, DAG);
5981     if (NewCond.getNode())
5982       Cond = NewCond;
5983   }
5984
5985   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
5986   SDValue Op1 = Op.getOperand(1);
5987   SDValue Op2 = Op.getOperand(2);
5988   if (Cond.getOpcode() == X86ISD::SETCC &&
5989       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
5990     SDValue Cmp = Cond.getOperand(1);
5991     if (Cmp.getOpcode() == X86ISD::CMP) {
5992       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
5993       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
5994       ConstantSDNode *RHSC =
5995         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
5996       if (N1C && N1C->isAllOnesValue() &&
5997           N2C && N2C->isNullValue() &&
5998           RHSC && RHSC->isNullValue()) {
5999         SDValue CmpOp0 = Cmp.getOperand(0);
6000         Cmp = DAG.getNode(X86ISD::CMP, dl, Op.getValueType(),
6001                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6002         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6003                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6004       }
6005     }
6006   }
6007
6008   // Look pass (and (setcc_carry (cmp ...)), 1).
6009   if (Cond.getOpcode() == ISD::AND &&
6010       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6011     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6012     if (C && C->getAPIntValue() == 1) 
6013       Cond = Cond.getOperand(0);
6014   }
6015
6016   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6017   // setting operand in place of the X86ISD::SETCC.
6018   if (Cond.getOpcode() == X86ISD::SETCC ||
6019       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6020     CC = Cond.getOperand(0);
6021
6022     SDValue Cmp = Cond.getOperand(1);
6023     unsigned Opc = Cmp.getOpcode();
6024     EVT VT = Op.getValueType();
6025
6026     bool IllegalFPCMov = false;
6027     if (VT.isFloatingPoint() && !VT.isVector() &&
6028         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6029       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6030
6031     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6032         Opc == X86ISD::BT) { // FIXME
6033       Cond = Cmp;
6034       addTest = false;
6035     }
6036   }
6037
6038   if (addTest) {
6039     // Look pass the truncate.
6040     if (Cond.getOpcode() == ISD::TRUNCATE)
6041       Cond = Cond.getOperand(0);
6042
6043     // We know the result of AND is compared against zero. Try to match
6044     // it to BT.
6045     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6046       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6047       if (NewSetCC.getNode()) {
6048         CC = NewSetCC.getOperand(0);
6049         Cond = NewSetCC.getOperand(1);
6050         addTest = false;
6051       }
6052     }
6053   }
6054
6055   if (addTest) {
6056     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6057     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6058   }
6059
6060   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6061   // condition is true.
6062   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6063   SDValue Ops[] = { Op2, Op1, CC, Cond };
6064   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6065 }
6066
6067 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6068 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6069 // from the AND / OR.
6070 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6071   Opc = Op.getOpcode();
6072   if (Opc != ISD::OR && Opc != ISD::AND)
6073     return false;
6074   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6075           Op.getOperand(0).hasOneUse() &&
6076           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6077           Op.getOperand(1).hasOneUse());
6078 }
6079
6080 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6081 // 1 and that the SETCC node has a single use.
6082 static bool isXor1OfSetCC(SDValue Op) {
6083   if (Op.getOpcode() != ISD::XOR)
6084     return false;
6085   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6086   if (N1C && N1C->getAPIntValue() == 1) {
6087     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6088       Op.getOperand(0).hasOneUse();
6089   }
6090   return false;
6091 }
6092
6093 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6094   bool addTest = true;
6095   SDValue Chain = Op.getOperand(0);
6096   SDValue Cond  = Op.getOperand(1);
6097   SDValue Dest  = Op.getOperand(2);
6098   DebugLoc dl = Op.getDebugLoc();
6099   SDValue CC;
6100
6101   if (Cond.getOpcode() == ISD::SETCC) {
6102     SDValue NewCond = LowerSETCC(Cond, DAG);
6103     if (NewCond.getNode())
6104       Cond = NewCond;
6105   }
6106 #if 0
6107   // FIXME: LowerXALUO doesn't handle these!!
6108   else if (Cond.getOpcode() == X86ISD::ADD  ||
6109            Cond.getOpcode() == X86ISD::SUB  ||
6110            Cond.getOpcode() == X86ISD::SMUL ||
6111            Cond.getOpcode() == X86ISD::UMUL)
6112     Cond = LowerXALUO(Cond, DAG);
6113 #endif
6114
6115   // Look pass (and (setcc_carry (cmp ...)), 1).
6116   if (Cond.getOpcode() == ISD::AND &&
6117       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6118     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6119     if (C && C->getAPIntValue() == 1) 
6120       Cond = Cond.getOperand(0);
6121   }
6122
6123   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6124   // setting operand in place of the X86ISD::SETCC.
6125   if (Cond.getOpcode() == X86ISD::SETCC ||
6126       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6127     CC = Cond.getOperand(0);
6128
6129     SDValue Cmp = Cond.getOperand(1);
6130     unsigned Opc = Cmp.getOpcode();
6131     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6132     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6133       Cond = Cmp;
6134       addTest = false;
6135     } else {
6136       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6137       default: break;
6138       case X86::COND_O:
6139       case X86::COND_B:
6140         // These can only come from an arithmetic instruction with overflow,
6141         // e.g. SADDO, UADDO.
6142         Cond = Cond.getNode()->getOperand(1);
6143         addTest = false;
6144         break;
6145       }
6146     }
6147   } else {
6148     unsigned CondOpc;
6149     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6150       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6151       if (CondOpc == ISD::OR) {
6152         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6153         // two branches instead of an explicit OR instruction with a
6154         // separate test.
6155         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6156             isX86LogicalCmp(Cmp)) {
6157           CC = Cond.getOperand(0).getOperand(0);
6158           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6159                               Chain, Dest, CC, Cmp);
6160           CC = Cond.getOperand(1).getOperand(0);
6161           Cond = Cmp;
6162           addTest = false;
6163         }
6164       } else { // ISD::AND
6165         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6166         // two branches instead of an explicit AND instruction with a
6167         // separate test. However, we only do this if this block doesn't
6168         // have a fall-through edge, because this requires an explicit
6169         // jmp when the condition is false.
6170         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6171             isX86LogicalCmp(Cmp) &&
6172             Op.getNode()->hasOneUse()) {
6173           X86::CondCode CCode =
6174             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6175           CCode = X86::GetOppositeBranchCondition(CCode);
6176           CC = DAG.getConstant(CCode, MVT::i8);
6177           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6178           // Look for an unconditional branch following this conditional branch.
6179           // We need this because we need to reverse the successors in order
6180           // to implement FCMP_OEQ.
6181           if (User.getOpcode() == ISD::BR) {
6182             SDValue FalseBB = User.getOperand(1);
6183             SDValue NewBR =
6184               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6185             assert(NewBR == User);
6186             Dest = FalseBB;
6187
6188             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6189                                 Chain, Dest, CC, Cmp);
6190             X86::CondCode CCode =
6191               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6192             CCode = X86::GetOppositeBranchCondition(CCode);
6193             CC = DAG.getConstant(CCode, MVT::i8);
6194             Cond = Cmp;
6195             addTest = false;
6196           }
6197         }
6198       }
6199     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6200       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6201       // It should be transformed during dag combiner except when the condition
6202       // is set by a arithmetics with overflow node.
6203       X86::CondCode CCode =
6204         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6205       CCode = X86::GetOppositeBranchCondition(CCode);
6206       CC = DAG.getConstant(CCode, MVT::i8);
6207       Cond = Cond.getOperand(0).getOperand(1);
6208       addTest = false;
6209     }
6210   }
6211
6212   if (addTest) {
6213     // Look pass the truncate.
6214     if (Cond.getOpcode() == ISD::TRUNCATE)
6215       Cond = Cond.getOperand(0);
6216
6217     // We know the result of AND is compared against zero. Try to match
6218     // it to BT.
6219     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6220       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6221       if (NewSetCC.getNode()) {
6222         CC = NewSetCC.getOperand(0);
6223         Cond = NewSetCC.getOperand(1);
6224         addTest = false;
6225       }
6226     }
6227   }
6228
6229   if (addTest) {
6230     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6231     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6232   }
6233   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6234                      Chain, Dest, CC, Cond);
6235 }
6236
6237
6238 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6239 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6240 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6241 // that the guard pages used by the OS virtual memory manager are allocated in
6242 // correct sequence.
6243 SDValue
6244 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6245                                            SelectionDAG &DAG) {
6246   assert(Subtarget->isTargetCygMing() &&
6247          "This should be used only on Cygwin/Mingw targets");
6248   DebugLoc dl = Op.getDebugLoc();
6249
6250   // Get the inputs.
6251   SDValue Chain = Op.getOperand(0);
6252   SDValue Size  = Op.getOperand(1);
6253   // FIXME: Ensure alignment here
6254
6255   SDValue Flag;
6256
6257   EVT IntPtr = getPointerTy();
6258   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6259
6260   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6261
6262   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6263   Flag = Chain.getValue(1);
6264
6265   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6266   SDValue Ops[] = { Chain,
6267                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
6268                       DAG.getRegister(X86::EAX, IntPtr),
6269                       DAG.getRegister(X86StackPtr, SPTy),
6270                       Flag };
6271   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6272   Flag = Chain.getValue(1);
6273
6274   Chain = DAG.getCALLSEQ_END(Chain,
6275                              DAG.getIntPtrConstant(0, true),
6276                              DAG.getIntPtrConstant(0, true),
6277                              Flag);
6278
6279   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6280
6281   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6282   return DAG.getMergeValues(Ops1, 2, dl);
6283 }
6284
6285 SDValue
6286 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6287                                            SDValue Chain,
6288                                            SDValue Dst, SDValue Src,
6289                                            SDValue Size, unsigned Align,
6290                                            const Value *DstSV,
6291                                            uint64_t DstSVOff) {
6292   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6293
6294   // If not DWORD aligned or size is more than the threshold, call the library.
6295   // The libc version is likely to be faster for these cases. It can use the
6296   // address value and run time information about the CPU.
6297   if ((Align & 3) != 0 ||
6298       !ConstantSize ||
6299       ConstantSize->getZExtValue() >
6300         getSubtarget()->getMaxInlineSizeThreshold()) {
6301     SDValue InFlag(0, 0);
6302
6303     // Check to see if there is a specialized entry-point for memory zeroing.
6304     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6305
6306     if (const char *bzeroEntry =  V &&
6307         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6308       EVT IntPtr = getPointerTy();
6309       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6310       TargetLowering::ArgListTy Args;
6311       TargetLowering::ArgListEntry Entry;
6312       Entry.Node = Dst;
6313       Entry.Ty = IntPtrTy;
6314       Args.push_back(Entry);
6315       Entry.Node = Size;
6316       Args.push_back(Entry);
6317       std::pair<SDValue,SDValue> CallResult =
6318         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6319                     false, false, false, false,
6320                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6321                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6322                     DAG.GetOrdering(Chain.getNode()));
6323       return CallResult.second;
6324     }
6325
6326     // Otherwise have the target-independent code call memset.
6327     return SDValue();
6328   }
6329
6330   uint64_t SizeVal = ConstantSize->getZExtValue();
6331   SDValue InFlag(0, 0);
6332   EVT AVT;
6333   SDValue Count;
6334   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6335   unsigned BytesLeft = 0;
6336   bool TwoRepStos = false;
6337   if (ValC) {
6338     unsigned ValReg;
6339     uint64_t Val = ValC->getZExtValue() & 255;
6340
6341     // If the value is a constant, then we can potentially use larger sets.
6342     switch (Align & 3) {
6343     case 2:   // WORD aligned
6344       AVT = MVT::i16;
6345       ValReg = X86::AX;
6346       Val = (Val << 8) | Val;
6347       break;
6348     case 0:  // DWORD aligned
6349       AVT = MVT::i32;
6350       ValReg = X86::EAX;
6351       Val = (Val << 8)  | Val;
6352       Val = (Val << 16) | Val;
6353       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6354         AVT = MVT::i64;
6355         ValReg = X86::RAX;
6356         Val = (Val << 32) | Val;
6357       }
6358       break;
6359     default:  // Byte aligned
6360       AVT = MVT::i8;
6361       ValReg = X86::AL;
6362       Count = DAG.getIntPtrConstant(SizeVal);
6363       break;
6364     }
6365
6366     if (AVT.bitsGT(MVT::i8)) {
6367       unsigned UBytes = AVT.getSizeInBits() / 8;
6368       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6369       BytesLeft = SizeVal % UBytes;
6370     }
6371
6372     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6373                               InFlag);
6374     InFlag = Chain.getValue(1);
6375   } else {
6376     AVT = MVT::i8;
6377     Count  = DAG.getIntPtrConstant(SizeVal);
6378     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6379     InFlag = Chain.getValue(1);
6380   }
6381
6382   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6383                                                               X86::ECX,
6384                             Count, InFlag);
6385   InFlag = Chain.getValue(1);
6386   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6387                                                               X86::EDI,
6388                             Dst, InFlag);
6389   InFlag = Chain.getValue(1);
6390
6391   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6392   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6393   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6394
6395   if (TwoRepStos) {
6396     InFlag = Chain.getValue(1);
6397     Count  = Size;
6398     EVT CVT = Count.getValueType();
6399     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6400                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6401     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6402                                                              X86::ECX,
6403                               Left, InFlag);
6404     InFlag = Chain.getValue(1);
6405     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6406     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6407     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6408   } else if (BytesLeft) {
6409     // Handle the last 1 - 7 bytes.
6410     unsigned Offset = SizeVal - BytesLeft;
6411     EVT AddrVT = Dst.getValueType();
6412     EVT SizeVT = Size.getValueType();
6413
6414     Chain = DAG.getMemset(Chain, dl,
6415                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6416                                       DAG.getConstant(Offset, AddrVT)),
6417                           Src,
6418                           DAG.getConstant(BytesLeft, SizeVT),
6419                           Align, DstSV, DstSVOff + Offset);
6420   }
6421
6422   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6423   return Chain;
6424 }
6425
6426 SDValue
6427 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6428                                       SDValue Chain, SDValue Dst, SDValue Src,
6429                                       SDValue Size, unsigned Align,
6430                                       bool AlwaysInline,
6431                                       const Value *DstSV, uint64_t DstSVOff,
6432                                       const Value *SrcSV, uint64_t SrcSVOff) {
6433   // This requires the copy size to be a constant, preferrably
6434   // within a subtarget-specific limit.
6435   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6436   if (!ConstantSize)
6437     return SDValue();
6438   uint64_t SizeVal = ConstantSize->getZExtValue();
6439   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6440     return SDValue();
6441
6442   /// If not DWORD aligned, call the library.
6443   if ((Align & 3) != 0)
6444     return SDValue();
6445
6446   // DWORD aligned
6447   EVT AVT = MVT::i32;
6448   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6449     AVT = MVT::i64;
6450
6451   unsigned UBytes = AVT.getSizeInBits() / 8;
6452   unsigned CountVal = SizeVal / UBytes;
6453   SDValue Count = DAG.getIntPtrConstant(CountVal);
6454   unsigned BytesLeft = SizeVal % UBytes;
6455
6456   SDValue InFlag(0, 0);
6457   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6458                                                               X86::ECX,
6459                             Count, InFlag);
6460   InFlag = Chain.getValue(1);
6461   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6462                                                              X86::EDI,
6463                             Dst, InFlag);
6464   InFlag = Chain.getValue(1);
6465   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6466                                                               X86::ESI,
6467                             Src, InFlag);
6468   InFlag = Chain.getValue(1);
6469
6470   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6471   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6472   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6473                                 array_lengthof(Ops));
6474
6475   SmallVector<SDValue, 4> Results;
6476   Results.push_back(RepMovs);
6477   if (BytesLeft) {
6478     // Handle the last 1 - 7 bytes.
6479     unsigned Offset = SizeVal - BytesLeft;
6480     EVT DstVT = Dst.getValueType();
6481     EVT SrcVT = Src.getValueType();
6482     EVT SizeVT = Size.getValueType();
6483     Results.push_back(DAG.getMemcpy(Chain, dl,
6484                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6485                                                 DAG.getConstant(Offset, DstVT)),
6486                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6487                                                 DAG.getConstant(Offset, SrcVT)),
6488                                     DAG.getConstant(BytesLeft, SizeVT),
6489                                     Align, AlwaysInline,
6490                                     DstSV, DstSVOff + Offset,
6491                                     SrcSV, SrcSVOff + Offset));
6492   }
6493
6494   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6495                      &Results[0], Results.size());
6496 }
6497
6498 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6499   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6500   DebugLoc dl = Op.getDebugLoc();
6501
6502   if (!Subtarget->is64Bit()) {
6503     // vastart just stores the address of the VarArgsFrameIndex slot into the
6504     // memory location argument.
6505     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6506     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6507   }
6508
6509   // __va_list_tag:
6510   //   gp_offset         (0 - 6 * 8)
6511   //   fp_offset         (48 - 48 + 8 * 16)
6512   //   overflow_arg_area (point to parameters coming in memory).
6513   //   reg_save_area
6514   SmallVector<SDValue, 8> MemOps;
6515   SDValue FIN = Op.getOperand(1);
6516   // Store gp_offset
6517   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6518                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
6519                                  FIN, SV, 0);
6520   MemOps.push_back(Store);
6521
6522   // Store fp_offset
6523   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6524                     FIN, DAG.getIntPtrConstant(4));
6525   Store = DAG.getStore(Op.getOperand(0), dl,
6526                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6527                        FIN, SV, 0);
6528   MemOps.push_back(Store);
6529
6530   // Store ptr to overflow_arg_area
6531   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6532                     FIN, DAG.getIntPtrConstant(4));
6533   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6534   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6535   MemOps.push_back(Store);
6536
6537   // Store ptr to reg_save_area.
6538   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6539                     FIN, DAG.getIntPtrConstant(8));
6540   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6541   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6542   MemOps.push_back(Store);
6543   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6544                      &MemOps[0], MemOps.size());
6545 }
6546
6547 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6548   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6549   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6550   SDValue Chain = Op.getOperand(0);
6551   SDValue SrcPtr = Op.getOperand(1);
6552   SDValue SrcSV = Op.getOperand(2);
6553
6554   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6555   return SDValue();
6556 }
6557
6558 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6559   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6560   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6561   SDValue Chain = Op.getOperand(0);
6562   SDValue DstPtr = Op.getOperand(1);
6563   SDValue SrcPtr = Op.getOperand(2);
6564   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6565   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6566   DebugLoc dl = Op.getDebugLoc();
6567
6568   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6569                        DAG.getIntPtrConstant(24), 8, false,
6570                        DstSV, 0, SrcSV, 0);
6571 }
6572
6573 SDValue
6574 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6575   DebugLoc dl = Op.getDebugLoc();
6576   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6577   switch (IntNo) {
6578   default: return SDValue();    // Don't custom lower most intrinsics.
6579   // Comparison intrinsics.
6580   case Intrinsic::x86_sse_comieq_ss:
6581   case Intrinsic::x86_sse_comilt_ss:
6582   case Intrinsic::x86_sse_comile_ss:
6583   case Intrinsic::x86_sse_comigt_ss:
6584   case Intrinsic::x86_sse_comige_ss:
6585   case Intrinsic::x86_sse_comineq_ss:
6586   case Intrinsic::x86_sse_ucomieq_ss:
6587   case Intrinsic::x86_sse_ucomilt_ss:
6588   case Intrinsic::x86_sse_ucomile_ss:
6589   case Intrinsic::x86_sse_ucomigt_ss:
6590   case Intrinsic::x86_sse_ucomige_ss:
6591   case Intrinsic::x86_sse_ucomineq_ss:
6592   case Intrinsic::x86_sse2_comieq_sd:
6593   case Intrinsic::x86_sse2_comilt_sd:
6594   case Intrinsic::x86_sse2_comile_sd:
6595   case Intrinsic::x86_sse2_comigt_sd:
6596   case Intrinsic::x86_sse2_comige_sd:
6597   case Intrinsic::x86_sse2_comineq_sd:
6598   case Intrinsic::x86_sse2_ucomieq_sd:
6599   case Intrinsic::x86_sse2_ucomilt_sd:
6600   case Intrinsic::x86_sse2_ucomile_sd:
6601   case Intrinsic::x86_sse2_ucomigt_sd:
6602   case Intrinsic::x86_sse2_ucomige_sd:
6603   case Intrinsic::x86_sse2_ucomineq_sd: {
6604     unsigned Opc = 0;
6605     ISD::CondCode CC = ISD::SETCC_INVALID;
6606     switch (IntNo) {
6607     default: break;
6608     case Intrinsic::x86_sse_comieq_ss:
6609     case Intrinsic::x86_sse2_comieq_sd:
6610       Opc = X86ISD::COMI;
6611       CC = ISD::SETEQ;
6612       break;
6613     case Intrinsic::x86_sse_comilt_ss:
6614     case Intrinsic::x86_sse2_comilt_sd:
6615       Opc = X86ISD::COMI;
6616       CC = ISD::SETLT;
6617       break;
6618     case Intrinsic::x86_sse_comile_ss:
6619     case Intrinsic::x86_sse2_comile_sd:
6620       Opc = X86ISD::COMI;
6621       CC = ISD::SETLE;
6622       break;
6623     case Intrinsic::x86_sse_comigt_ss:
6624     case Intrinsic::x86_sse2_comigt_sd:
6625       Opc = X86ISD::COMI;
6626       CC = ISD::SETGT;
6627       break;
6628     case Intrinsic::x86_sse_comige_ss:
6629     case Intrinsic::x86_sse2_comige_sd:
6630       Opc = X86ISD::COMI;
6631       CC = ISD::SETGE;
6632       break;
6633     case Intrinsic::x86_sse_comineq_ss:
6634     case Intrinsic::x86_sse2_comineq_sd:
6635       Opc = X86ISD::COMI;
6636       CC = ISD::SETNE;
6637       break;
6638     case Intrinsic::x86_sse_ucomieq_ss:
6639     case Intrinsic::x86_sse2_ucomieq_sd:
6640       Opc = X86ISD::UCOMI;
6641       CC = ISD::SETEQ;
6642       break;
6643     case Intrinsic::x86_sse_ucomilt_ss:
6644     case Intrinsic::x86_sse2_ucomilt_sd:
6645       Opc = X86ISD::UCOMI;
6646       CC = ISD::SETLT;
6647       break;
6648     case Intrinsic::x86_sse_ucomile_ss:
6649     case Intrinsic::x86_sse2_ucomile_sd:
6650       Opc = X86ISD::UCOMI;
6651       CC = ISD::SETLE;
6652       break;
6653     case Intrinsic::x86_sse_ucomigt_ss:
6654     case Intrinsic::x86_sse2_ucomigt_sd:
6655       Opc = X86ISD::UCOMI;
6656       CC = ISD::SETGT;
6657       break;
6658     case Intrinsic::x86_sse_ucomige_ss:
6659     case Intrinsic::x86_sse2_ucomige_sd:
6660       Opc = X86ISD::UCOMI;
6661       CC = ISD::SETGE;
6662       break;
6663     case Intrinsic::x86_sse_ucomineq_ss:
6664     case Intrinsic::x86_sse2_ucomineq_sd:
6665       Opc = X86ISD::UCOMI;
6666       CC = ISD::SETNE;
6667       break;
6668     }
6669
6670     SDValue LHS = Op.getOperand(1);
6671     SDValue RHS = Op.getOperand(2);
6672     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6673     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6674     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6675     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6676                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6677     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6678   }
6679   // ptest intrinsics. The intrinsic these come from are designed to return
6680   // an integer value, not just an instruction so lower it to the ptest
6681   // pattern and a setcc for the result.
6682   case Intrinsic::x86_sse41_ptestz:
6683   case Intrinsic::x86_sse41_ptestc:
6684   case Intrinsic::x86_sse41_ptestnzc:{
6685     unsigned X86CC = 0;
6686     switch (IntNo) {
6687     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6688     case Intrinsic::x86_sse41_ptestz:
6689       // ZF = 1
6690       X86CC = X86::COND_E;
6691       break;
6692     case Intrinsic::x86_sse41_ptestc:
6693       // CF = 1
6694       X86CC = X86::COND_B;
6695       break;
6696     case Intrinsic::x86_sse41_ptestnzc:
6697       // ZF and CF = 0
6698       X86CC = X86::COND_A;
6699       break;
6700     }
6701
6702     SDValue LHS = Op.getOperand(1);
6703     SDValue RHS = Op.getOperand(2);
6704     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6705     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6706     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6707     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6708   }
6709
6710   // Fix vector shift instructions where the last operand is a non-immediate
6711   // i32 value.
6712   case Intrinsic::x86_sse2_pslli_w:
6713   case Intrinsic::x86_sse2_pslli_d:
6714   case Intrinsic::x86_sse2_pslli_q:
6715   case Intrinsic::x86_sse2_psrli_w:
6716   case Intrinsic::x86_sse2_psrli_d:
6717   case Intrinsic::x86_sse2_psrli_q:
6718   case Intrinsic::x86_sse2_psrai_w:
6719   case Intrinsic::x86_sse2_psrai_d:
6720   case Intrinsic::x86_mmx_pslli_w:
6721   case Intrinsic::x86_mmx_pslli_d:
6722   case Intrinsic::x86_mmx_pslli_q:
6723   case Intrinsic::x86_mmx_psrli_w:
6724   case Intrinsic::x86_mmx_psrli_d:
6725   case Intrinsic::x86_mmx_psrli_q:
6726   case Intrinsic::x86_mmx_psrai_w:
6727   case Intrinsic::x86_mmx_psrai_d: {
6728     SDValue ShAmt = Op.getOperand(2);
6729     if (isa<ConstantSDNode>(ShAmt))
6730       return SDValue();
6731
6732     unsigned NewIntNo = 0;
6733     EVT ShAmtVT = MVT::v4i32;
6734     switch (IntNo) {
6735     case Intrinsic::x86_sse2_pslli_w:
6736       NewIntNo = Intrinsic::x86_sse2_psll_w;
6737       break;
6738     case Intrinsic::x86_sse2_pslli_d:
6739       NewIntNo = Intrinsic::x86_sse2_psll_d;
6740       break;
6741     case Intrinsic::x86_sse2_pslli_q:
6742       NewIntNo = Intrinsic::x86_sse2_psll_q;
6743       break;
6744     case Intrinsic::x86_sse2_psrli_w:
6745       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6746       break;
6747     case Intrinsic::x86_sse2_psrli_d:
6748       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6749       break;
6750     case Intrinsic::x86_sse2_psrli_q:
6751       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6752       break;
6753     case Intrinsic::x86_sse2_psrai_w:
6754       NewIntNo = Intrinsic::x86_sse2_psra_w;
6755       break;
6756     case Intrinsic::x86_sse2_psrai_d:
6757       NewIntNo = Intrinsic::x86_sse2_psra_d;
6758       break;
6759     default: {
6760       ShAmtVT = MVT::v2i32;
6761       switch (IntNo) {
6762       case Intrinsic::x86_mmx_pslli_w:
6763         NewIntNo = Intrinsic::x86_mmx_psll_w;
6764         break;
6765       case Intrinsic::x86_mmx_pslli_d:
6766         NewIntNo = Intrinsic::x86_mmx_psll_d;
6767         break;
6768       case Intrinsic::x86_mmx_pslli_q:
6769         NewIntNo = Intrinsic::x86_mmx_psll_q;
6770         break;
6771       case Intrinsic::x86_mmx_psrli_w:
6772         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6773         break;
6774       case Intrinsic::x86_mmx_psrli_d:
6775         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6776         break;
6777       case Intrinsic::x86_mmx_psrli_q:
6778         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6779         break;
6780       case Intrinsic::x86_mmx_psrai_w:
6781         NewIntNo = Intrinsic::x86_mmx_psra_w;
6782         break;
6783       case Intrinsic::x86_mmx_psrai_d:
6784         NewIntNo = Intrinsic::x86_mmx_psra_d;
6785         break;
6786       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6787       }
6788       break;
6789     }
6790     }
6791
6792     // The vector shift intrinsics with scalars uses 32b shift amounts but
6793     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6794     // to be zero.
6795     SDValue ShOps[4];
6796     ShOps[0] = ShAmt;
6797     ShOps[1] = DAG.getConstant(0, MVT::i32);
6798     if (ShAmtVT == MVT::v4i32) {
6799       ShOps[2] = DAG.getUNDEF(MVT::i32);
6800       ShOps[3] = DAG.getUNDEF(MVT::i32);
6801       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6802     } else {
6803       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6804     }
6805
6806     EVT VT = Op.getValueType();
6807     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6808     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6809                        DAG.getConstant(NewIntNo, MVT::i32),
6810                        Op.getOperand(1), ShAmt);
6811   }
6812   }
6813 }
6814
6815 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6817   DebugLoc dl = Op.getDebugLoc();
6818
6819   if (Depth > 0) {
6820     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6821     SDValue Offset =
6822       DAG.getConstant(TD->getPointerSize(),
6823                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6824     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6825                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6826                                    FrameAddr, Offset),
6827                        NULL, 0);
6828   }
6829
6830   // Just load the return address.
6831   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6832   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6833                      RetAddrFI, NULL, 0);
6834 }
6835
6836 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6837   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6838   MFI->setFrameAddressIsTaken(true);
6839   EVT VT = Op.getValueType();
6840   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6841   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6842   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6843   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6844   while (Depth--)
6845     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6846   return FrameAddr;
6847 }
6848
6849 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6850                                                      SelectionDAG &DAG) {
6851   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6852 }
6853
6854 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6855 {
6856   MachineFunction &MF = DAG.getMachineFunction();
6857   SDValue Chain     = Op.getOperand(0);
6858   SDValue Offset    = Op.getOperand(1);
6859   SDValue Handler   = Op.getOperand(2);
6860   DebugLoc dl       = Op.getDebugLoc();
6861
6862   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6863                                   getPointerTy());
6864   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6865
6866   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6867                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6868   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6869   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6870   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6871   MF.getRegInfo().addLiveOut(StoreAddrReg);
6872
6873   return DAG.getNode(X86ISD::EH_RETURN, dl,
6874                      MVT::Other,
6875                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6876 }
6877
6878 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6879                                              SelectionDAG &DAG) {
6880   SDValue Root = Op.getOperand(0);
6881   SDValue Trmp = Op.getOperand(1); // trampoline
6882   SDValue FPtr = Op.getOperand(2); // nested function
6883   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6884   DebugLoc dl  = Op.getDebugLoc();
6885
6886   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6887
6888   const X86InstrInfo *TII =
6889     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6890
6891   if (Subtarget->is64Bit()) {
6892     SDValue OutChains[6];
6893
6894     // Large code-model.
6895
6896     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6897     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6898
6899     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6900     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6901
6902     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6903
6904     // Load the pointer to the nested function into R11.
6905     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6906     SDValue Addr = Trmp;
6907     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6908                                 Addr, TrmpAddr, 0);
6909
6910     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6911                        DAG.getConstant(2, MVT::i64));
6912     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6913
6914     // Load the 'nest' parameter value into R10.
6915     // R10 is specified in X86CallingConv.td
6916     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6917     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6918                        DAG.getConstant(10, MVT::i64));
6919     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6920                                 Addr, TrmpAddr, 10);
6921
6922     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6923                        DAG.getConstant(12, MVT::i64));
6924     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6925
6926     // Jump to the nested function.
6927     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6928     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6929                        DAG.getConstant(20, MVT::i64));
6930     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6931                                 Addr, TrmpAddr, 20);
6932
6933     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6934     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6935                        DAG.getConstant(22, MVT::i64));
6936     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6937                                 TrmpAddr, 22);
6938
6939     SDValue Ops[] =
6940       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6941     return DAG.getMergeValues(Ops, 2, dl);
6942   } else {
6943     const Function *Func =
6944       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6945     CallingConv::ID CC = Func->getCallingConv();
6946     unsigned NestReg;
6947
6948     switch (CC) {
6949     default:
6950       llvm_unreachable("Unsupported calling convention");
6951     case CallingConv::C:
6952     case CallingConv::X86_StdCall: {
6953       // Pass 'nest' parameter in ECX.
6954       // Must be kept in sync with X86CallingConv.td
6955       NestReg = X86::ECX;
6956
6957       // Check that ECX wasn't needed by an 'inreg' parameter.
6958       const FunctionType *FTy = Func->getFunctionType();
6959       const AttrListPtr &Attrs = Func->getAttributes();
6960
6961       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6962         unsigned InRegCount = 0;
6963         unsigned Idx = 1;
6964
6965         for (FunctionType::param_iterator I = FTy->param_begin(),
6966              E = FTy->param_end(); I != E; ++I, ++Idx)
6967           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6968             // FIXME: should only count parameters that are lowered to integers.
6969             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6970
6971         if (InRegCount > 2) {
6972           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6973         }
6974       }
6975       break;
6976     }
6977     case CallingConv::X86_FastCall:
6978     case CallingConv::Fast:
6979       // Pass 'nest' parameter in EAX.
6980       // Must be kept in sync with X86CallingConv.td
6981       NestReg = X86::EAX;
6982       break;
6983     }
6984
6985     SDValue OutChains[4];
6986     SDValue Addr, Disp;
6987
6988     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6989                        DAG.getConstant(10, MVT::i32));
6990     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6991
6992     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6993     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6994     OutChains[0] = DAG.getStore(Root, dl,
6995                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6996                                 Trmp, TrmpAddr, 0);
6997
6998     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6999                        DAG.getConstant(1, MVT::i32));
7000     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
7001
7002     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
7003     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7004                        DAG.getConstant(5, MVT::i32));
7005     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7006                                 TrmpAddr, 5, false, 1);
7007
7008     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7009                        DAG.getConstant(6, MVT::i32));
7010     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
7011
7012     SDValue Ops[] =
7013       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7014     return DAG.getMergeValues(Ops, 2, dl);
7015   }
7016 }
7017
7018 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7019   /*
7020    The rounding mode is in bits 11:10 of FPSR, and has the following
7021    settings:
7022      00 Round to nearest
7023      01 Round to -inf
7024      10 Round to +inf
7025      11 Round to 0
7026
7027   FLT_ROUNDS, on the other hand, expects the following:
7028     -1 Undefined
7029      0 Round to 0
7030      1 Round to nearest
7031      2 Round to +inf
7032      3 Round to -inf
7033
7034   To perform the conversion, we do:
7035     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7036   */
7037
7038   MachineFunction &MF = DAG.getMachineFunction();
7039   const TargetMachine &TM = MF.getTarget();
7040   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7041   unsigned StackAlignment = TFI.getStackAlignment();
7042   EVT VT = Op.getValueType();
7043   DebugLoc dl = Op.getDebugLoc();
7044
7045   // Save FP Control Word to stack slot
7046   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7047   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7048
7049   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7050                               DAG.getEntryNode(), StackSlot);
7051
7052   // Load FP Control Word from stack slot
7053   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7054
7055   // Transform as necessary
7056   SDValue CWD1 =
7057     DAG.getNode(ISD::SRL, dl, MVT::i16,
7058                 DAG.getNode(ISD::AND, dl, MVT::i16,
7059                             CWD, DAG.getConstant(0x800, MVT::i16)),
7060                 DAG.getConstant(11, MVT::i8));
7061   SDValue CWD2 =
7062     DAG.getNode(ISD::SRL, dl, MVT::i16,
7063                 DAG.getNode(ISD::AND, dl, MVT::i16,
7064                             CWD, DAG.getConstant(0x400, MVT::i16)),
7065                 DAG.getConstant(9, MVT::i8));
7066
7067   SDValue RetVal =
7068     DAG.getNode(ISD::AND, dl, MVT::i16,
7069                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7070                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7071                             DAG.getConstant(1, MVT::i16)),
7072                 DAG.getConstant(3, MVT::i16));
7073
7074
7075   return DAG.getNode((VT.getSizeInBits() < 16 ?
7076                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7077 }
7078
7079 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7080   EVT VT = Op.getValueType();
7081   EVT OpVT = VT;
7082   unsigned NumBits = VT.getSizeInBits();
7083   DebugLoc dl = Op.getDebugLoc();
7084
7085   Op = Op.getOperand(0);
7086   if (VT == MVT::i8) {
7087     // Zero extend to i32 since there is not an i8 bsr.
7088     OpVT = MVT::i32;
7089     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7090   }
7091
7092   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7093   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7094   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7095
7096   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7097   SDValue Ops[] = {
7098     Op,
7099     DAG.getConstant(NumBits+NumBits-1, OpVT),
7100     DAG.getConstant(X86::COND_E, MVT::i8),
7101     Op.getValue(1)
7102   };
7103   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7104
7105   // Finally xor with NumBits-1.
7106   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7107
7108   if (VT == MVT::i8)
7109     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7110   return Op;
7111 }
7112
7113 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7114   EVT VT = Op.getValueType();
7115   EVT OpVT = VT;
7116   unsigned NumBits = VT.getSizeInBits();
7117   DebugLoc dl = Op.getDebugLoc();
7118
7119   Op = Op.getOperand(0);
7120   if (VT == MVT::i8) {
7121     OpVT = MVT::i32;
7122     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7123   }
7124
7125   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7126   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7127   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7128
7129   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7130   SDValue Ops[] = {
7131     Op,
7132     DAG.getConstant(NumBits, OpVT),
7133     DAG.getConstant(X86::COND_E, MVT::i8),
7134     Op.getValue(1)
7135   };
7136   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7137
7138   if (VT == MVT::i8)
7139     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7140   return Op;
7141 }
7142
7143 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7144   EVT VT = Op.getValueType();
7145   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7146   DebugLoc dl = Op.getDebugLoc();
7147
7148   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7149   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7150   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7151   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7152   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7153   //
7154   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7155   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7156   //  return AloBlo + AloBhi + AhiBlo;
7157
7158   SDValue A = Op.getOperand(0);
7159   SDValue B = Op.getOperand(1);
7160
7161   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7162                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7163                        A, DAG.getConstant(32, MVT::i32));
7164   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7165                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7166                        B, DAG.getConstant(32, MVT::i32));
7167   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7168                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7169                        A, B);
7170   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7171                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7172                        A, Bhi);
7173   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7174                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7175                        Ahi, B);
7176   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7177                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7178                        AloBhi, DAG.getConstant(32, MVT::i32));
7179   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7180                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7181                        AhiBlo, DAG.getConstant(32, MVT::i32));
7182   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7183   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7184   return Res;
7185 }
7186
7187
7188 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7189   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7190   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7191   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7192   // has only one use.
7193   SDNode *N = Op.getNode();
7194   SDValue LHS = N->getOperand(0);
7195   SDValue RHS = N->getOperand(1);
7196   unsigned BaseOp = 0;
7197   unsigned Cond = 0;
7198   DebugLoc dl = Op.getDebugLoc();
7199
7200   switch (Op.getOpcode()) {
7201   default: llvm_unreachable("Unknown ovf instruction!");
7202   case ISD::SADDO:
7203     // A subtract of one will be selected as a INC. Note that INC doesn't
7204     // set CF, so we can't do this for UADDO.
7205     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7206       if (C->getAPIntValue() == 1) {
7207         BaseOp = X86ISD::INC;
7208         Cond = X86::COND_O;
7209         break;
7210       }
7211     BaseOp = X86ISD::ADD;
7212     Cond = X86::COND_O;
7213     break;
7214   case ISD::UADDO:
7215     BaseOp = X86ISD::ADD;
7216     Cond = X86::COND_B;
7217     break;
7218   case ISD::SSUBO:
7219     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7220     // set CF, so we can't do this for USUBO.
7221     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7222       if (C->getAPIntValue() == 1) {
7223         BaseOp = X86ISD::DEC;
7224         Cond = X86::COND_O;
7225         break;
7226       }
7227     BaseOp = X86ISD::SUB;
7228     Cond = X86::COND_O;
7229     break;
7230   case ISD::USUBO:
7231     BaseOp = X86ISD::SUB;
7232     Cond = X86::COND_B;
7233     break;
7234   case ISD::SMULO:
7235     BaseOp = X86ISD::SMUL;
7236     Cond = X86::COND_O;
7237     break;
7238   case ISD::UMULO:
7239     BaseOp = X86ISD::UMUL;
7240     Cond = X86::COND_B;
7241     break;
7242   }
7243
7244   // Also sets EFLAGS.
7245   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7246   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7247
7248   SDValue SetCC =
7249     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7250                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7251
7252   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7253   return Sum;
7254 }
7255
7256 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7257   EVT T = Op.getValueType();
7258   DebugLoc dl = Op.getDebugLoc();
7259   unsigned Reg = 0;
7260   unsigned size = 0;
7261   switch(T.getSimpleVT().SimpleTy) {
7262   default:
7263     assert(false && "Invalid value type!");
7264   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7265   case MVT::i16: Reg = X86::AX;  size = 2; break;
7266   case MVT::i32: Reg = X86::EAX; size = 4; break;
7267   case MVT::i64:
7268     assert(Subtarget->is64Bit() && "Node not type legal!");
7269     Reg = X86::RAX; size = 8;
7270     break;
7271   }
7272   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7273                                     Op.getOperand(2), SDValue());
7274   SDValue Ops[] = { cpIn.getValue(0),
7275                     Op.getOperand(1),
7276                     Op.getOperand(3),
7277                     DAG.getTargetConstant(size, MVT::i8),
7278                     cpIn.getValue(1) };
7279   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7280   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7281   SDValue cpOut =
7282     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7283   return cpOut;
7284 }
7285
7286 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7287                                                  SelectionDAG &DAG) {
7288   assert(Subtarget->is64Bit() && "Result not type legalized?");
7289   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7290   SDValue TheChain = Op.getOperand(0);
7291   DebugLoc dl = Op.getDebugLoc();
7292   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7293   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7294   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7295                                    rax.getValue(2));
7296   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7297                             DAG.getConstant(32, MVT::i8));
7298   SDValue Ops[] = {
7299     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7300     rdx.getValue(1)
7301   };
7302   return DAG.getMergeValues(Ops, 2, dl);
7303 }
7304
7305 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7306   SDNode *Node = Op.getNode();
7307   DebugLoc dl = Node->getDebugLoc();
7308   EVT T = Node->getValueType(0);
7309   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7310                               DAG.getConstant(0, T), Node->getOperand(2));
7311   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7312                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7313                        Node->getOperand(0),
7314                        Node->getOperand(1), negOp,
7315                        cast<AtomicSDNode>(Node)->getSrcValue(),
7316                        cast<AtomicSDNode>(Node)->getAlignment());
7317 }
7318
7319 /// LowerOperation - Provide custom lowering hooks for some operations.
7320 ///
7321 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7322   switch (Op.getOpcode()) {
7323   default: llvm_unreachable("Should not custom lower this!");
7324   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7325   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7326   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7327   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7328   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7329   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7330   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7331   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7332   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7333   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7334   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7335   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7336   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7337   case ISD::SHL_PARTS:
7338   case ISD::SRA_PARTS:
7339   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7340   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7341   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7342   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7343   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7344   case ISD::FABS:               return LowerFABS(Op, DAG);
7345   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7346   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7347   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7348   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7349   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7350   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7351   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7352   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7353   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7354   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7355   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7356   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7357   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7358   case ISD::FRAME_TO_ARGS_OFFSET:
7359                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7360   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7361   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7362   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7363   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7364   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7365   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7366   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7367   case ISD::SADDO:
7368   case ISD::UADDO:
7369   case ISD::SSUBO:
7370   case ISD::USUBO:
7371   case ISD::SMULO:
7372   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7373   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7374   }
7375 }
7376
7377 void X86TargetLowering::
7378 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7379                         SelectionDAG &DAG, unsigned NewOp) {
7380   EVT T = Node->getValueType(0);
7381   DebugLoc dl = Node->getDebugLoc();
7382   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7383
7384   SDValue Chain = Node->getOperand(0);
7385   SDValue In1 = Node->getOperand(1);
7386   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7387                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7388   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7389                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7390   SDValue Ops[] = { Chain, In1, In2L, In2H };
7391   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7392   SDValue Result =
7393     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7394                             cast<MemSDNode>(Node)->getMemOperand());
7395   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7396   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7397   Results.push_back(Result.getValue(2));
7398 }
7399
7400 /// ReplaceNodeResults - Replace a node with an illegal result type
7401 /// with a new node built out of custom code.
7402 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7403                                            SmallVectorImpl<SDValue>&Results,
7404                                            SelectionDAG &DAG) {
7405   DebugLoc dl = N->getDebugLoc();
7406   switch (N->getOpcode()) {
7407   default:
7408     assert(false && "Do not know how to custom type legalize this operation!");
7409     return;
7410   case ISD::FP_TO_SINT: {
7411     std::pair<SDValue,SDValue> Vals =
7412         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7413     SDValue FIST = Vals.first, StackSlot = Vals.second;
7414     if (FIST.getNode() != 0) {
7415       EVT VT = N->getValueType(0);
7416       // Return a load from the stack slot.
7417       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7418     }
7419     return;
7420   }
7421   case ISD::READCYCLECOUNTER: {
7422     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7423     SDValue TheChain = N->getOperand(0);
7424     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7425     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7426                                      rd.getValue(1));
7427     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7428                                      eax.getValue(2));
7429     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7430     SDValue Ops[] = { eax, edx };
7431     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7432     Results.push_back(edx.getValue(1));
7433     return;
7434   }
7435   case ISD::SDIV:
7436   case ISD::UDIV:
7437   case ISD::SREM:
7438   case ISD::UREM: {
7439     EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7440     Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7441     return;
7442   }
7443   case ISD::ATOMIC_CMP_SWAP: {
7444     EVT T = N->getValueType(0);
7445     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7446     SDValue cpInL, cpInH;
7447     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7448                         DAG.getConstant(0, MVT::i32));
7449     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7450                         DAG.getConstant(1, MVT::i32));
7451     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7452     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7453                              cpInL.getValue(1));
7454     SDValue swapInL, swapInH;
7455     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7456                           DAG.getConstant(0, MVT::i32));
7457     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7458                           DAG.getConstant(1, MVT::i32));
7459     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7460                                cpInH.getValue(1));
7461     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7462                                swapInL.getValue(1));
7463     SDValue Ops[] = { swapInH.getValue(0),
7464                       N->getOperand(1),
7465                       swapInH.getValue(1) };
7466     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7467     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7468     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7469                                         MVT::i32, Result.getValue(1));
7470     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7471                                         MVT::i32, cpOutL.getValue(2));
7472     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7473     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7474     Results.push_back(cpOutH.getValue(1));
7475     return;
7476   }
7477   case ISD::ATOMIC_LOAD_ADD:
7478     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7479     return;
7480   case ISD::ATOMIC_LOAD_AND:
7481     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7482     return;
7483   case ISD::ATOMIC_LOAD_NAND:
7484     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7485     return;
7486   case ISD::ATOMIC_LOAD_OR:
7487     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7488     return;
7489   case ISD::ATOMIC_LOAD_SUB:
7490     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7491     return;
7492   case ISD::ATOMIC_LOAD_XOR:
7493     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7494     return;
7495   case ISD::ATOMIC_SWAP:
7496     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7497     return;
7498   }
7499 }
7500
7501 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7502   switch (Opcode) {
7503   default: return NULL;
7504   case X86ISD::BSF:                return "X86ISD::BSF";
7505   case X86ISD::BSR:                return "X86ISD::BSR";
7506   case X86ISD::SHLD:               return "X86ISD::SHLD";
7507   case X86ISD::SHRD:               return "X86ISD::SHRD";
7508   case X86ISD::FAND:               return "X86ISD::FAND";
7509   case X86ISD::FOR:                return "X86ISD::FOR";
7510   case X86ISD::FXOR:               return "X86ISD::FXOR";
7511   case X86ISD::FSRL:               return "X86ISD::FSRL";
7512   case X86ISD::FILD:               return "X86ISD::FILD";
7513   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7514   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7515   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7516   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7517   case X86ISD::FLD:                return "X86ISD::FLD";
7518   case X86ISD::FST:                return "X86ISD::FST";
7519   case X86ISD::CALL:               return "X86ISD::CALL";
7520   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7521   case X86ISD::BT:                 return "X86ISD::BT";
7522   case X86ISD::CMP:                return "X86ISD::CMP";
7523   case X86ISD::COMI:               return "X86ISD::COMI";
7524   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7525   case X86ISD::SETCC:              return "X86ISD::SETCC";
7526   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7527   case X86ISD::CMOV:               return "X86ISD::CMOV";
7528   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7529   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7530   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7531   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7532   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7533   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7534   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7535   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7536   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7537   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7538   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7539   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7540   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7541   case X86ISD::FMAX:               return "X86ISD::FMAX";
7542   case X86ISD::FMIN:               return "X86ISD::FMIN";
7543   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7544   case X86ISD::FRCP:               return "X86ISD::FRCP";
7545   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7546   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7547   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7548   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7549   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7550   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7551   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7552   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7553   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7554   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7555   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7556   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7557   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7558   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7559   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7560   case X86ISD::VSHL:               return "X86ISD::VSHL";
7561   case X86ISD::VSRL:               return "X86ISD::VSRL";
7562   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7563   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7564   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7565   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7566   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7567   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7568   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7569   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7570   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7571   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7572   case X86ISD::ADD:                return "X86ISD::ADD";
7573   case X86ISD::SUB:                return "X86ISD::SUB";
7574   case X86ISD::SMUL:               return "X86ISD::SMUL";
7575   case X86ISD::UMUL:               return "X86ISD::UMUL";
7576   case X86ISD::INC:                return "X86ISD::INC";
7577   case X86ISD::DEC:                return "X86ISD::DEC";
7578   case X86ISD::OR:                 return "X86ISD::OR";
7579   case X86ISD::XOR:                return "X86ISD::XOR";
7580   case X86ISD::AND:                return "X86ISD::AND";
7581   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7582   case X86ISD::PTEST:              return "X86ISD::PTEST";
7583   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7584   }
7585 }
7586
7587 // isLegalAddressingMode - Return true if the addressing mode represented
7588 // by AM is legal for this target, for a load/store of the specified type.
7589 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7590                                               const Type *Ty) const {
7591   // X86 supports extremely general addressing modes.
7592   CodeModel::Model M = getTargetMachine().getCodeModel();
7593
7594   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7595   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7596     return false;
7597
7598   if (AM.BaseGV) {
7599     unsigned GVFlags =
7600       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7601
7602     // If a reference to this global requires an extra load, we can't fold it.
7603     if (isGlobalStubReference(GVFlags))
7604       return false;
7605
7606     // If BaseGV requires a register for the PIC base, we cannot also have a
7607     // BaseReg specified.
7608     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7609       return false;
7610
7611     // If lower 4G is not available, then we must use rip-relative addressing.
7612     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7613       return false;
7614   }
7615
7616   switch (AM.Scale) {
7617   case 0:
7618   case 1:
7619   case 2:
7620   case 4:
7621   case 8:
7622     // These scales always work.
7623     break;
7624   case 3:
7625   case 5:
7626   case 9:
7627     // These scales are formed with basereg+scalereg.  Only accept if there is
7628     // no basereg yet.
7629     if (AM.HasBaseReg)
7630       return false;
7631     break;
7632   default:  // Other stuff never works.
7633     return false;
7634   }
7635
7636   return true;
7637 }
7638
7639
7640 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7641   if (!Ty1->isInteger() || !Ty2->isInteger())
7642     return false;
7643   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7644   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7645   if (NumBits1 <= NumBits2)
7646     return false;
7647   return Subtarget->is64Bit() || NumBits1 < 64;
7648 }
7649
7650 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7651   if (!VT1.isInteger() || !VT2.isInteger())
7652     return false;
7653   unsigned NumBits1 = VT1.getSizeInBits();
7654   unsigned NumBits2 = VT2.getSizeInBits();
7655   if (NumBits1 <= NumBits2)
7656     return false;
7657   return Subtarget->is64Bit() || NumBits1 < 64;
7658 }
7659
7660 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7661   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7662   return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7663 }
7664
7665 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7666   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7667   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7668 }
7669
7670 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7671   // i16 instructions are longer (0x66 prefix) and potentially slower.
7672   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7673 }
7674
7675 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7676 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7677 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7678 /// are assumed to be legal.
7679 bool
7680 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7681                                       EVT VT) const {
7682   // Only do shuffles on 128-bit vector types for now.
7683   if (VT.getSizeInBits() == 64)
7684     return false;
7685
7686   // FIXME: pshufb, blends, shifts.
7687   return (VT.getVectorNumElements() == 2 ||
7688           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7689           isMOVLMask(M, VT) ||
7690           isSHUFPMask(M, VT) ||
7691           isPSHUFDMask(M, VT) ||
7692           isPSHUFHWMask(M, VT) ||
7693           isPSHUFLWMask(M, VT) ||
7694           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7695           isUNPCKLMask(M, VT) ||
7696           isUNPCKHMask(M, VT) ||
7697           isUNPCKL_v_undef_Mask(M, VT) ||
7698           isUNPCKH_v_undef_Mask(M, VT));
7699 }
7700
7701 bool
7702 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7703                                           EVT VT) const {
7704   unsigned NumElts = VT.getVectorNumElements();
7705   // FIXME: This collection of masks seems suspect.
7706   if (NumElts == 2)
7707     return true;
7708   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7709     return (isMOVLMask(Mask, VT)  ||
7710             isCommutedMOVLMask(Mask, VT, true) ||
7711             isSHUFPMask(Mask, VT) ||
7712             isCommutedSHUFPMask(Mask, VT));
7713   }
7714   return false;
7715 }
7716
7717 //===----------------------------------------------------------------------===//
7718 //                           X86 Scheduler Hooks
7719 //===----------------------------------------------------------------------===//
7720
7721 // private utility function
7722 MachineBasicBlock *
7723 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7724                                                        MachineBasicBlock *MBB,
7725                                                        unsigned regOpc,
7726                                                        unsigned immOpc,
7727                                                        unsigned LoadOpc,
7728                                                        unsigned CXchgOpc,
7729                                                        unsigned copyOpc,
7730                                                        unsigned notOpc,
7731                                                        unsigned EAXreg,
7732                                                        TargetRegisterClass *RC,
7733                                                        bool invSrc) const {
7734   // For the atomic bitwise operator, we generate
7735   //   thisMBB:
7736   //   newMBB:
7737   //     ld  t1 = [bitinstr.addr]
7738   //     op  t2 = t1, [bitinstr.val]
7739   //     mov EAX = t1
7740   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7741   //     bz  newMBB
7742   //     fallthrough -->nextMBB
7743   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7744   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7745   MachineFunction::iterator MBBIter = MBB;
7746   ++MBBIter;
7747
7748   /// First build the CFG
7749   MachineFunction *F = MBB->getParent();
7750   MachineBasicBlock *thisMBB = MBB;
7751   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7752   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7753   F->insert(MBBIter, newMBB);
7754   F->insert(MBBIter, nextMBB);
7755
7756   // Move all successors to thisMBB to nextMBB
7757   nextMBB->transferSuccessors(thisMBB);
7758
7759   // Update thisMBB to fall through to newMBB
7760   thisMBB->addSuccessor(newMBB);
7761
7762   // newMBB jumps to itself and fall through to nextMBB
7763   newMBB->addSuccessor(nextMBB);
7764   newMBB->addSuccessor(newMBB);
7765
7766   // Insert instructions into newMBB based on incoming instruction
7767   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7768          "unexpected number of operands");
7769   DebugLoc dl = bInstr->getDebugLoc();
7770   MachineOperand& destOper = bInstr->getOperand(0);
7771   MachineOperand* argOpers[2 + X86AddrNumOperands];
7772   int numArgs = bInstr->getNumOperands() - 1;
7773   for (int i=0; i < numArgs; ++i)
7774     argOpers[i] = &bInstr->getOperand(i+1);
7775
7776   // x86 address has 4 operands: base, index, scale, and displacement
7777   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7778   int valArgIndx = lastAddrIndx + 1;
7779
7780   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7781   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7782   for (int i=0; i <= lastAddrIndx; ++i)
7783     (*MIB).addOperand(*argOpers[i]);
7784
7785   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7786   if (invSrc) {
7787     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7788   }
7789   else
7790     tt = t1;
7791
7792   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7793   assert((argOpers[valArgIndx]->isReg() ||
7794           argOpers[valArgIndx]->isImm()) &&
7795          "invalid operand");
7796   if (argOpers[valArgIndx]->isReg())
7797     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7798   else
7799     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7800   MIB.addReg(tt);
7801   (*MIB).addOperand(*argOpers[valArgIndx]);
7802
7803   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7804   MIB.addReg(t1);
7805
7806   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7807   for (int i=0; i <= lastAddrIndx; ++i)
7808     (*MIB).addOperand(*argOpers[i]);
7809   MIB.addReg(t2);
7810   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7811   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7812                     bInstr->memoperands_end());
7813
7814   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7815   MIB.addReg(EAXreg);
7816
7817   // insert branch
7818   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7819
7820   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7821   return nextMBB;
7822 }
7823
7824 // private utility function:  64 bit atomics on 32 bit host.
7825 MachineBasicBlock *
7826 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7827                                                        MachineBasicBlock *MBB,
7828                                                        unsigned regOpcL,
7829                                                        unsigned regOpcH,
7830                                                        unsigned immOpcL,
7831                                                        unsigned immOpcH,
7832                                                        bool invSrc) const {
7833   // For the atomic bitwise operator, we generate
7834   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7835   //     ld t1,t2 = [bitinstr.addr]
7836   //   newMBB:
7837   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7838   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7839   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7840   //     mov ECX, EBX <- t5, t6
7841   //     mov EAX, EDX <- t1, t2
7842   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7843   //     mov t3, t4 <- EAX, EDX
7844   //     bz  newMBB
7845   //     result in out1, out2
7846   //     fallthrough -->nextMBB
7847
7848   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7849   const unsigned LoadOpc = X86::MOV32rm;
7850   const unsigned copyOpc = X86::MOV32rr;
7851   const unsigned NotOpc = X86::NOT32r;
7852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7853   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7854   MachineFunction::iterator MBBIter = MBB;
7855   ++MBBIter;
7856
7857   /// First build the CFG
7858   MachineFunction *F = MBB->getParent();
7859   MachineBasicBlock *thisMBB = MBB;
7860   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7861   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7862   F->insert(MBBIter, newMBB);
7863   F->insert(MBBIter, nextMBB);
7864
7865   // Move all successors to thisMBB to nextMBB
7866   nextMBB->transferSuccessors(thisMBB);
7867
7868   // Update thisMBB to fall through to newMBB
7869   thisMBB->addSuccessor(newMBB);
7870
7871   // newMBB jumps to itself and fall through to nextMBB
7872   newMBB->addSuccessor(nextMBB);
7873   newMBB->addSuccessor(newMBB);
7874
7875   DebugLoc dl = bInstr->getDebugLoc();
7876   // Insert instructions into newMBB based on incoming instruction
7877   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7878   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7879          "unexpected number of operands");
7880   MachineOperand& dest1Oper = bInstr->getOperand(0);
7881   MachineOperand& dest2Oper = bInstr->getOperand(1);
7882   MachineOperand* argOpers[2 + X86AddrNumOperands];
7883   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7884     argOpers[i] = &bInstr->getOperand(i+2);
7885
7886   // x86 address has 5 operands: base, index, scale, displacement, and segment.
7887   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7888
7889   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7890   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7891   for (int i=0; i <= lastAddrIndx; ++i)
7892     (*MIB).addOperand(*argOpers[i]);
7893   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7894   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7895   // add 4 to displacement.
7896   for (int i=0; i <= lastAddrIndx-2; ++i)
7897     (*MIB).addOperand(*argOpers[i]);
7898   MachineOperand newOp3 = *(argOpers[3]);
7899   if (newOp3.isImm())
7900     newOp3.setImm(newOp3.getImm()+4);
7901   else
7902     newOp3.setOffset(newOp3.getOffset()+4);
7903   (*MIB).addOperand(newOp3);
7904   (*MIB).addOperand(*argOpers[lastAddrIndx]);
7905
7906   // t3/4 are defined later, at the bottom of the loop
7907   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7908   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7909   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7910     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7911   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7912     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7913
7914   // The subsequent operations should be using the destination registers of
7915   //the PHI instructions.
7916   if (invSrc) {
7917     t1 = F->getRegInfo().createVirtualRegister(RC);
7918     t2 = F->getRegInfo().createVirtualRegister(RC);
7919     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7920     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7921   } else {
7922     t1 = dest1Oper.getReg();
7923     t2 = dest2Oper.getReg();
7924   }
7925
7926   int valArgIndx = lastAddrIndx + 1;
7927   assert((argOpers[valArgIndx]->isReg() ||
7928           argOpers[valArgIndx]->isImm()) &&
7929          "invalid operand");
7930   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7931   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7932   if (argOpers[valArgIndx]->isReg())
7933     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7934   else
7935     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7936   if (regOpcL != X86::MOV32rr)
7937     MIB.addReg(t1);
7938   (*MIB).addOperand(*argOpers[valArgIndx]);
7939   assert(argOpers[valArgIndx + 1]->isReg() ==
7940          argOpers[valArgIndx]->isReg());
7941   assert(argOpers[valArgIndx + 1]->isImm() ==
7942          argOpers[valArgIndx]->isImm());
7943   if (argOpers[valArgIndx + 1]->isReg())
7944     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7945   else
7946     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7947   if (regOpcH != X86::MOV32rr)
7948     MIB.addReg(t2);
7949   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7950
7951   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7952   MIB.addReg(t1);
7953   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7954   MIB.addReg(t2);
7955
7956   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7957   MIB.addReg(t5);
7958   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7959   MIB.addReg(t6);
7960
7961   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7962   for (int i=0; i <= lastAddrIndx; ++i)
7963     (*MIB).addOperand(*argOpers[i]);
7964
7965   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7966   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7967                     bInstr->memoperands_end());
7968
7969   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7970   MIB.addReg(X86::EAX);
7971   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7972   MIB.addReg(X86::EDX);
7973
7974   // insert branch
7975   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7976
7977   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7978   return nextMBB;
7979 }
7980
7981 // private utility function
7982 MachineBasicBlock *
7983 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7984                                                       MachineBasicBlock *MBB,
7985                                                       unsigned cmovOpc) const {
7986   // For the atomic min/max operator, we generate
7987   //   thisMBB:
7988   //   newMBB:
7989   //     ld t1 = [min/max.addr]
7990   //     mov t2 = [min/max.val]
7991   //     cmp  t1, t2
7992   //     cmov[cond] t2 = t1
7993   //     mov EAX = t1
7994   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7995   //     bz   newMBB
7996   //     fallthrough -->nextMBB
7997   //
7998   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7999   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8000   MachineFunction::iterator MBBIter = MBB;
8001   ++MBBIter;
8002
8003   /// First build the CFG
8004   MachineFunction *F = MBB->getParent();
8005   MachineBasicBlock *thisMBB = MBB;
8006   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8007   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8008   F->insert(MBBIter, newMBB);
8009   F->insert(MBBIter, nextMBB);
8010
8011   // Move all successors of thisMBB to nextMBB
8012   nextMBB->transferSuccessors(thisMBB);
8013
8014   // Update thisMBB to fall through to newMBB
8015   thisMBB->addSuccessor(newMBB);
8016
8017   // newMBB jumps to newMBB and fall through to nextMBB
8018   newMBB->addSuccessor(nextMBB);
8019   newMBB->addSuccessor(newMBB);
8020
8021   DebugLoc dl = mInstr->getDebugLoc();
8022   // Insert instructions into newMBB based on incoming instruction
8023   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8024          "unexpected number of operands");
8025   MachineOperand& destOper = mInstr->getOperand(0);
8026   MachineOperand* argOpers[2 + X86AddrNumOperands];
8027   int numArgs = mInstr->getNumOperands() - 1;
8028   for (int i=0; i < numArgs; ++i)
8029     argOpers[i] = &mInstr->getOperand(i+1);
8030
8031   // x86 address has 4 operands: base, index, scale, and displacement
8032   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8033   int valArgIndx = lastAddrIndx + 1;
8034
8035   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8036   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8037   for (int i=0; i <= lastAddrIndx; ++i)
8038     (*MIB).addOperand(*argOpers[i]);
8039
8040   // We only support register and immediate values
8041   assert((argOpers[valArgIndx]->isReg() ||
8042           argOpers[valArgIndx]->isImm()) &&
8043          "invalid operand");
8044
8045   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8046   if (argOpers[valArgIndx]->isReg())
8047     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8048   else
8049     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8050   (*MIB).addOperand(*argOpers[valArgIndx]);
8051
8052   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8053   MIB.addReg(t1);
8054
8055   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8056   MIB.addReg(t1);
8057   MIB.addReg(t2);
8058
8059   // Generate movc
8060   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8061   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8062   MIB.addReg(t2);
8063   MIB.addReg(t1);
8064
8065   // Cmp and exchange if none has modified the memory location
8066   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8067   for (int i=0; i <= lastAddrIndx; ++i)
8068     (*MIB).addOperand(*argOpers[i]);
8069   MIB.addReg(t3);
8070   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8071   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8072                     mInstr->memoperands_end());
8073
8074   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8075   MIB.addReg(X86::EAX);
8076
8077   // insert branch
8078   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8079
8080   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8081   return nextMBB;
8082 }
8083
8084 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8085 // all of this code can be replaced with that in the .td file.
8086 MachineBasicBlock *
8087 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8088                             unsigned numArgs, bool memArg) const {
8089
8090   MachineFunction *F = BB->getParent();
8091   DebugLoc dl = MI->getDebugLoc();
8092   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8093
8094   unsigned Opc;
8095   if (memArg)
8096     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8097   else
8098     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8099
8100   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8101
8102   for (unsigned i = 0; i < numArgs; ++i) {
8103     MachineOperand &Op = MI->getOperand(i+1);
8104
8105     if (!(Op.isReg() && Op.isImplicit()))
8106       MIB.addOperand(Op);
8107   }
8108
8109   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8110     .addReg(X86::XMM0);
8111
8112   F->DeleteMachineInstr(MI);
8113
8114   return BB;
8115 }
8116
8117 MachineBasicBlock *
8118 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8119                                                  MachineInstr *MI,
8120                                                  MachineBasicBlock *MBB) const {
8121   // Emit code to save XMM registers to the stack. The ABI says that the
8122   // number of registers to save is given in %al, so it's theoretically
8123   // possible to do an indirect jump trick to avoid saving all of them,
8124   // however this code takes a simpler approach and just executes all
8125   // of the stores if %al is non-zero. It's less code, and it's probably
8126   // easier on the hardware branch predictor, and stores aren't all that
8127   // expensive anyway.
8128
8129   // Create the new basic blocks. One block contains all the XMM stores,
8130   // and one block is the final destination regardless of whether any
8131   // stores were performed.
8132   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8133   MachineFunction *F = MBB->getParent();
8134   MachineFunction::iterator MBBIter = MBB;
8135   ++MBBIter;
8136   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8137   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8138   F->insert(MBBIter, XMMSaveMBB);
8139   F->insert(MBBIter, EndMBB);
8140
8141   // Set up the CFG.
8142   // Move any original successors of MBB to the end block.
8143   EndMBB->transferSuccessors(MBB);
8144   // The original block will now fall through to the XMM save block.
8145   MBB->addSuccessor(XMMSaveMBB);
8146   // The XMMSaveMBB will fall through to the end block.
8147   XMMSaveMBB->addSuccessor(EndMBB);
8148
8149   // Now add the instructions.
8150   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8151   DebugLoc DL = MI->getDebugLoc();
8152
8153   unsigned CountReg = MI->getOperand(0).getReg();
8154   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8155   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8156
8157   if (!Subtarget->isTargetWin64()) {
8158     // If %al is 0, branch around the XMM save block.
8159     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8160     BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8161     MBB->addSuccessor(EndMBB);
8162   }
8163
8164   // In the XMM save block, save all the XMM argument registers.
8165   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8166     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8167     MachineMemOperand *MMO =
8168       F->getMachineMemOperand(
8169         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8170         MachineMemOperand::MOStore, Offset,
8171         /*Size=*/16, /*Align=*/16);
8172     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8173       .addFrameIndex(RegSaveFrameIndex)
8174       .addImm(/*Scale=*/1)
8175       .addReg(/*IndexReg=*/0)
8176       .addImm(/*Disp=*/Offset)
8177       .addReg(/*Segment=*/0)
8178       .addReg(MI->getOperand(i).getReg())
8179       .addMemOperand(MMO);
8180   }
8181
8182   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8183
8184   return EndMBB;
8185 }
8186
8187 MachineBasicBlock *
8188 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8189                                      MachineBasicBlock *BB,
8190                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8191   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8192   DebugLoc DL = MI->getDebugLoc();
8193
8194   // To "insert" a SELECT_CC instruction, we actually have to insert the
8195   // diamond control-flow pattern.  The incoming instruction knows the
8196   // destination vreg to set, the condition code register to branch on, the
8197   // true/false values to select between, and a branch opcode to use.
8198   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8199   MachineFunction::iterator It = BB;
8200   ++It;
8201
8202   //  thisMBB:
8203   //  ...
8204   //   TrueVal = ...
8205   //   cmpTY ccX, r1, r2
8206   //   bCC copy1MBB
8207   //   fallthrough --> copy0MBB
8208   MachineBasicBlock *thisMBB = BB;
8209   MachineFunction *F = BB->getParent();
8210   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8211   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8212   unsigned Opc =
8213     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8214   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8215   F->insert(It, copy0MBB);
8216   F->insert(It, sinkMBB);
8217   // Update machine-CFG edges by first adding all successors of the current
8218   // block to the new block which will contain the Phi node for the select.
8219   // Also inform sdisel of the edge changes.
8220   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8221          E = BB->succ_end(); I != E; ++I) {
8222     EM->insert(std::make_pair(*I, sinkMBB));
8223     sinkMBB->addSuccessor(*I);
8224   }
8225   // Next, remove all successors of the current block, and add the true
8226   // and fallthrough blocks as its successors.
8227   while (!BB->succ_empty())
8228     BB->removeSuccessor(BB->succ_begin());
8229   // Add the true and fallthrough blocks as its successors.
8230   BB->addSuccessor(copy0MBB);
8231   BB->addSuccessor(sinkMBB);
8232
8233   //  copy0MBB:
8234   //   %FalseValue = ...
8235   //   # fallthrough to sinkMBB
8236   BB = copy0MBB;
8237
8238   // Update machine-CFG edges
8239   BB->addSuccessor(sinkMBB);
8240
8241   //  sinkMBB:
8242   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8243   //  ...
8244   BB = sinkMBB;
8245   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8246     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8247     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8248
8249   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8250   return BB;
8251 }
8252
8253
8254 MachineBasicBlock *
8255 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8256                                                MachineBasicBlock *BB,
8257                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8258   switch (MI->getOpcode()) {
8259   default: assert(false && "Unexpected instr type to insert");
8260   case X86::CMOV_GR8:
8261   case X86::CMOV_V1I64:
8262   case X86::CMOV_FR32:
8263   case X86::CMOV_FR64:
8264   case X86::CMOV_V4F32:
8265   case X86::CMOV_V2F64:
8266   case X86::CMOV_V2I64:
8267     return EmitLoweredSelect(MI, BB, EM);
8268
8269   case X86::FP32_TO_INT16_IN_MEM:
8270   case X86::FP32_TO_INT32_IN_MEM:
8271   case X86::FP32_TO_INT64_IN_MEM:
8272   case X86::FP64_TO_INT16_IN_MEM:
8273   case X86::FP64_TO_INT32_IN_MEM:
8274   case X86::FP64_TO_INT64_IN_MEM:
8275   case X86::FP80_TO_INT16_IN_MEM:
8276   case X86::FP80_TO_INT32_IN_MEM:
8277   case X86::FP80_TO_INT64_IN_MEM: {
8278     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8279     DebugLoc DL = MI->getDebugLoc();
8280
8281     // Change the floating point control register to use "round towards zero"
8282     // mode when truncating to an integer value.
8283     MachineFunction *F = BB->getParent();
8284     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8285     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8286
8287     // Load the old value of the high byte of the control word...
8288     unsigned OldCW =
8289       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8290     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8291                       CWFrameIdx);
8292
8293     // Set the high part to be round to zero...
8294     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8295       .addImm(0xC7F);
8296
8297     // Reload the modified control word now...
8298     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8299
8300     // Restore the memory image of control word to original value
8301     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8302       .addReg(OldCW);
8303
8304     // Get the X86 opcode to use.
8305     unsigned Opc;
8306     switch (MI->getOpcode()) {
8307     default: llvm_unreachable("illegal opcode!");
8308     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8309     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8310     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8311     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8312     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8313     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8314     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8315     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8316     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8317     }
8318
8319     X86AddressMode AM;
8320     MachineOperand &Op = MI->getOperand(0);
8321     if (Op.isReg()) {
8322       AM.BaseType = X86AddressMode::RegBase;
8323       AM.Base.Reg = Op.getReg();
8324     } else {
8325       AM.BaseType = X86AddressMode::FrameIndexBase;
8326       AM.Base.FrameIndex = Op.getIndex();
8327     }
8328     Op = MI->getOperand(1);
8329     if (Op.isImm())
8330       AM.Scale = Op.getImm();
8331     Op = MI->getOperand(2);
8332     if (Op.isImm())
8333       AM.IndexReg = Op.getImm();
8334     Op = MI->getOperand(3);
8335     if (Op.isGlobal()) {
8336       AM.GV = Op.getGlobal();
8337     } else {
8338       AM.Disp = Op.getImm();
8339     }
8340     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8341                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8342
8343     // Reload the original control word now.
8344     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8345
8346     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8347     return BB;
8348   }
8349     // String/text processing lowering.
8350   case X86::PCMPISTRM128REG:
8351     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8352   case X86::PCMPISTRM128MEM:
8353     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8354   case X86::PCMPESTRM128REG:
8355     return EmitPCMP(MI, BB, 5, false /* in mem */);
8356   case X86::PCMPESTRM128MEM:
8357     return EmitPCMP(MI, BB, 5, true /* in mem */);
8358
8359     // Atomic Lowering.
8360   case X86::ATOMAND32:
8361     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8362                                                X86::AND32ri, X86::MOV32rm,
8363                                                X86::LCMPXCHG32, X86::MOV32rr,
8364                                                X86::NOT32r, X86::EAX,
8365                                                X86::GR32RegisterClass);
8366   case X86::ATOMOR32:
8367     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8368                                                X86::OR32ri, X86::MOV32rm,
8369                                                X86::LCMPXCHG32, X86::MOV32rr,
8370                                                X86::NOT32r, X86::EAX,
8371                                                X86::GR32RegisterClass);
8372   case X86::ATOMXOR32:
8373     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8374                                                X86::XOR32ri, X86::MOV32rm,
8375                                                X86::LCMPXCHG32, X86::MOV32rr,
8376                                                X86::NOT32r, X86::EAX,
8377                                                X86::GR32RegisterClass);
8378   case X86::ATOMNAND32:
8379     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8380                                                X86::AND32ri, X86::MOV32rm,
8381                                                X86::LCMPXCHG32, X86::MOV32rr,
8382                                                X86::NOT32r, X86::EAX,
8383                                                X86::GR32RegisterClass, true);
8384   case X86::ATOMMIN32:
8385     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8386   case X86::ATOMMAX32:
8387     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8388   case X86::ATOMUMIN32:
8389     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8390   case X86::ATOMUMAX32:
8391     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8392
8393   case X86::ATOMAND16:
8394     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8395                                                X86::AND16ri, X86::MOV16rm,
8396                                                X86::LCMPXCHG16, X86::MOV16rr,
8397                                                X86::NOT16r, X86::AX,
8398                                                X86::GR16RegisterClass);
8399   case X86::ATOMOR16:
8400     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8401                                                X86::OR16ri, X86::MOV16rm,
8402                                                X86::LCMPXCHG16, X86::MOV16rr,
8403                                                X86::NOT16r, X86::AX,
8404                                                X86::GR16RegisterClass);
8405   case X86::ATOMXOR16:
8406     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8407                                                X86::XOR16ri, X86::MOV16rm,
8408                                                X86::LCMPXCHG16, X86::MOV16rr,
8409                                                X86::NOT16r, X86::AX,
8410                                                X86::GR16RegisterClass);
8411   case X86::ATOMNAND16:
8412     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8413                                                X86::AND16ri, X86::MOV16rm,
8414                                                X86::LCMPXCHG16, X86::MOV16rr,
8415                                                X86::NOT16r, X86::AX,
8416                                                X86::GR16RegisterClass, true);
8417   case X86::ATOMMIN16:
8418     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8419   case X86::ATOMMAX16:
8420     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8421   case X86::ATOMUMIN16:
8422     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8423   case X86::ATOMUMAX16:
8424     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8425
8426   case X86::ATOMAND8:
8427     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8428                                                X86::AND8ri, X86::MOV8rm,
8429                                                X86::LCMPXCHG8, X86::MOV8rr,
8430                                                X86::NOT8r, X86::AL,
8431                                                X86::GR8RegisterClass);
8432   case X86::ATOMOR8:
8433     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8434                                                X86::OR8ri, X86::MOV8rm,
8435                                                X86::LCMPXCHG8, X86::MOV8rr,
8436                                                X86::NOT8r, X86::AL,
8437                                                X86::GR8RegisterClass);
8438   case X86::ATOMXOR8:
8439     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8440                                                X86::XOR8ri, X86::MOV8rm,
8441                                                X86::LCMPXCHG8, X86::MOV8rr,
8442                                                X86::NOT8r, X86::AL,
8443                                                X86::GR8RegisterClass);
8444   case X86::ATOMNAND8:
8445     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8446                                                X86::AND8ri, X86::MOV8rm,
8447                                                X86::LCMPXCHG8, X86::MOV8rr,
8448                                                X86::NOT8r, X86::AL,
8449                                                X86::GR8RegisterClass, true);
8450   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8451   // This group is for 64-bit host.
8452   case X86::ATOMAND64:
8453     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8454                                                X86::AND64ri32, X86::MOV64rm,
8455                                                X86::LCMPXCHG64, X86::MOV64rr,
8456                                                X86::NOT64r, X86::RAX,
8457                                                X86::GR64RegisterClass);
8458   case X86::ATOMOR64:
8459     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8460                                                X86::OR64ri32, X86::MOV64rm,
8461                                                X86::LCMPXCHG64, X86::MOV64rr,
8462                                                X86::NOT64r, X86::RAX,
8463                                                X86::GR64RegisterClass);
8464   case X86::ATOMXOR64:
8465     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8466                                                X86::XOR64ri32, X86::MOV64rm,
8467                                                X86::LCMPXCHG64, X86::MOV64rr,
8468                                                X86::NOT64r, X86::RAX,
8469                                                X86::GR64RegisterClass);
8470   case X86::ATOMNAND64:
8471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8472                                                X86::AND64ri32, X86::MOV64rm,
8473                                                X86::LCMPXCHG64, X86::MOV64rr,
8474                                                X86::NOT64r, X86::RAX,
8475                                                X86::GR64RegisterClass, true);
8476   case X86::ATOMMIN64:
8477     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8478   case X86::ATOMMAX64:
8479     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8480   case X86::ATOMUMIN64:
8481     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8482   case X86::ATOMUMAX64:
8483     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8484
8485   // This group does 64-bit operations on a 32-bit host.
8486   case X86::ATOMAND6432:
8487     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8488                                                X86::AND32rr, X86::AND32rr,
8489                                                X86::AND32ri, X86::AND32ri,
8490                                                false);
8491   case X86::ATOMOR6432:
8492     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8493                                                X86::OR32rr, X86::OR32rr,
8494                                                X86::OR32ri, X86::OR32ri,
8495                                                false);
8496   case X86::ATOMXOR6432:
8497     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8498                                                X86::XOR32rr, X86::XOR32rr,
8499                                                X86::XOR32ri, X86::XOR32ri,
8500                                                false);
8501   case X86::ATOMNAND6432:
8502     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8503                                                X86::AND32rr, X86::AND32rr,
8504                                                X86::AND32ri, X86::AND32ri,
8505                                                true);
8506   case X86::ATOMADD6432:
8507     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8508                                                X86::ADD32rr, X86::ADC32rr,
8509                                                X86::ADD32ri, X86::ADC32ri,
8510                                                false);
8511   case X86::ATOMSUB6432:
8512     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8513                                                X86::SUB32rr, X86::SBB32rr,
8514                                                X86::SUB32ri, X86::SBB32ri,
8515                                                false);
8516   case X86::ATOMSWAP6432:
8517     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8518                                                X86::MOV32rr, X86::MOV32rr,
8519                                                X86::MOV32ri, X86::MOV32ri,
8520                                                false);
8521   case X86::VASTART_SAVE_XMM_REGS:
8522     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8523   }
8524 }
8525
8526 //===----------------------------------------------------------------------===//
8527 //                           X86 Optimization Hooks
8528 //===----------------------------------------------------------------------===//
8529
8530 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8531                                                        const APInt &Mask,
8532                                                        APInt &KnownZero,
8533                                                        APInt &KnownOne,
8534                                                        const SelectionDAG &DAG,
8535                                                        unsigned Depth) const {
8536   unsigned Opc = Op.getOpcode();
8537   assert((Opc >= ISD::BUILTIN_OP_END ||
8538           Opc == ISD::INTRINSIC_WO_CHAIN ||
8539           Opc == ISD::INTRINSIC_W_CHAIN ||
8540           Opc == ISD::INTRINSIC_VOID) &&
8541          "Should use MaskedValueIsZero if you don't know whether Op"
8542          " is a target node!");
8543
8544   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8545   switch (Opc) {
8546   default: break;
8547   case X86ISD::ADD:
8548   case X86ISD::SUB:
8549   case X86ISD::SMUL:
8550   case X86ISD::UMUL:
8551   case X86ISD::INC:
8552   case X86ISD::DEC:
8553   case X86ISD::OR:
8554   case X86ISD::XOR:
8555   case X86ISD::AND:
8556     // These nodes' second result is a boolean.
8557     if (Op.getResNo() == 0)
8558       break;
8559     // Fallthrough
8560   case X86ISD::SETCC:
8561     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8562                                        Mask.getBitWidth() - 1);
8563     break;
8564   }
8565 }
8566
8567 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8568 /// node is a GlobalAddress + offset.
8569 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8570                                        GlobalValue* &GA, int64_t &Offset) const{
8571   if (N->getOpcode() == X86ISD::Wrapper) {
8572     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8573       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8574       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8575       return true;
8576     }
8577   }
8578   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8579 }
8580
8581 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8582                                      EVT EltVT, LoadSDNode *&LDBase,
8583                                      unsigned &LastLoadedElt,
8584                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8585                                      const TargetLowering &TLI) {
8586   LDBase = NULL;
8587   LastLoadedElt = -1U;
8588   for (unsigned i = 0; i < NumElems; ++i) {
8589     if (N->getMaskElt(i) < 0) {
8590       if (!LDBase)
8591         return false;
8592       continue;
8593     }
8594
8595     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8596     if (!Elt.getNode() ||
8597         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8598       return false;
8599     if (!LDBase) {
8600       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8601         return false;
8602       LDBase = cast<LoadSDNode>(Elt.getNode());
8603       LastLoadedElt = i;
8604       continue;
8605     }
8606     if (Elt.getOpcode() == ISD::UNDEF)
8607       continue;
8608
8609     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8610     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8611       return false;
8612     LastLoadedElt = i;
8613   }
8614   return true;
8615 }
8616
8617 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8618 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8619 /// if the load addresses are consecutive, non-overlapping, and in the right
8620 /// order.  In the case of v2i64, it will see if it can rewrite the
8621 /// shuffle to be an appropriate build vector so it can take advantage of
8622 // performBuildVectorCombine.
8623 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8624                                      const TargetLowering &TLI) {
8625   DebugLoc dl = N->getDebugLoc();
8626   EVT VT = N->getValueType(0);
8627   EVT EltVT = VT.getVectorElementType();
8628   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8629   unsigned NumElems = VT.getVectorNumElements();
8630
8631   if (VT.getSizeInBits() != 128)
8632     return SDValue();
8633
8634   // Try to combine a vector_shuffle into a 128-bit load.
8635   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8636   LoadSDNode *LD = NULL;
8637   unsigned LastLoadedElt;
8638   if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8639                                 MFI, TLI))
8640     return SDValue();
8641
8642   if (LastLoadedElt == NumElems - 1) {
8643     if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8644       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8645                          LD->getSrcValue(), LD->getSrcValueOffset(),
8646                          LD->isVolatile());
8647     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8648                        LD->getSrcValue(), LD->getSrcValueOffset(),
8649                        LD->isVolatile(), LD->getAlignment());
8650   } else if (NumElems == 4 && LastLoadedElt == 1) {
8651     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8652     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8653     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8654     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8655   }
8656   return SDValue();
8657 }
8658
8659 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8660 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8661                                     const X86Subtarget *Subtarget) {
8662   DebugLoc DL = N->getDebugLoc();
8663   SDValue Cond = N->getOperand(0);
8664   // Get the LHS/RHS of the select.
8665   SDValue LHS = N->getOperand(1);
8666   SDValue RHS = N->getOperand(2);
8667
8668   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8669   // instructions have the peculiarity that if either operand is a NaN,
8670   // they chose what we call the RHS operand (and as such are not symmetric).
8671   // It happens that this matches the semantics of the common C idiom
8672   // x<y?x:y and related forms, so we can recognize these cases.
8673   if (Subtarget->hasSSE2() &&
8674       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8675       Cond.getOpcode() == ISD::SETCC) {
8676     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8677
8678     unsigned Opcode = 0;
8679     // Check for x CC y ? x : y.
8680     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8681       switch (CC) {
8682       default: break;
8683       case ISD::SETULT:
8684         // This can be a min if we can prove that at least one of the operands
8685         // is not a nan.
8686         if (!FiniteOnlyFPMath()) {
8687           if (DAG.isKnownNeverNaN(RHS)) {
8688             // Put the potential NaN in the RHS so that SSE will preserve it.
8689             std::swap(LHS, RHS);
8690           } else if (!DAG.isKnownNeverNaN(LHS))
8691             break;
8692         }
8693         Opcode = X86ISD::FMIN;
8694         break;
8695       case ISD::SETOLE:
8696         // This can be a min if we can prove that at least one of the operands
8697         // is not a nan.
8698         if (!FiniteOnlyFPMath()) {
8699           if (DAG.isKnownNeverNaN(LHS)) {
8700             // Put the potential NaN in the RHS so that SSE will preserve it.
8701             std::swap(LHS, RHS);
8702           } else if (!DAG.isKnownNeverNaN(RHS))
8703             break;
8704         }
8705         Opcode = X86ISD::FMIN;
8706         break;
8707       case ISD::SETULE:
8708         // This can be a min, but if either operand is a NaN we need it to
8709         // preserve the original LHS.
8710         std::swap(LHS, RHS);
8711       case ISD::SETOLT:
8712       case ISD::SETLT:
8713       case ISD::SETLE:
8714         Opcode = X86ISD::FMIN;
8715         break;
8716
8717       case ISD::SETOGE:
8718         // This can be a max if we can prove that at least one of the operands
8719         // is not a nan.
8720         if (!FiniteOnlyFPMath()) {
8721           if (DAG.isKnownNeverNaN(LHS)) {
8722             // Put the potential NaN in the RHS so that SSE will preserve it.
8723             std::swap(LHS, RHS);
8724           } else if (!DAG.isKnownNeverNaN(RHS))
8725             break;
8726         }
8727         Opcode = X86ISD::FMAX;
8728         break;
8729       case ISD::SETUGT:
8730         // This can be a max if we can prove that at least one of the operands
8731         // is not a nan.
8732         if (!FiniteOnlyFPMath()) {
8733           if (DAG.isKnownNeverNaN(RHS)) {
8734             // Put the potential NaN in the RHS so that SSE will preserve it.
8735             std::swap(LHS, RHS);
8736           } else if (!DAG.isKnownNeverNaN(LHS))
8737             break;
8738         }
8739         Opcode = X86ISD::FMAX;
8740         break;
8741       case ISD::SETUGE:
8742         // This can be a max, but if either operand is a NaN we need it to
8743         // preserve the original LHS.
8744         std::swap(LHS, RHS);
8745       case ISD::SETOGT:
8746       case ISD::SETGT:
8747       case ISD::SETGE:
8748         Opcode = X86ISD::FMAX;
8749         break;
8750       }
8751     // Check for x CC y ? y : x -- a min/max with reversed arms.
8752     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8753       switch (CC) {
8754       default: break;
8755       case ISD::SETOGE:
8756         // This can be a min if we can prove that at least one of the operands
8757         // is not a nan.
8758         if (!FiniteOnlyFPMath()) {
8759           if (DAG.isKnownNeverNaN(RHS)) {
8760             // Put the potential NaN in the RHS so that SSE will preserve it.
8761             std::swap(LHS, RHS);
8762           } else if (!DAG.isKnownNeverNaN(LHS))
8763             break;
8764         }
8765         Opcode = X86ISD::FMIN;
8766         break;
8767       case ISD::SETUGT:
8768         // This can be a min if we can prove that at least one of the operands
8769         // is not a nan.
8770         if (!FiniteOnlyFPMath()) {
8771           if (DAG.isKnownNeverNaN(LHS)) {
8772             // Put the potential NaN in the RHS so that SSE will preserve it.
8773             std::swap(LHS, RHS);
8774           } else if (!DAG.isKnownNeverNaN(RHS))
8775             break;
8776         }
8777         Opcode = X86ISD::FMIN;
8778         break;
8779       case ISD::SETUGE:
8780         // This can be a min, but if either operand is a NaN we need it to
8781         // preserve the original LHS.
8782         std::swap(LHS, RHS);
8783       case ISD::SETOGT:
8784       case ISD::SETGT:
8785       case ISD::SETGE:
8786         Opcode = X86ISD::FMIN;
8787         break;
8788
8789       case ISD::SETULT:
8790         // This can be a max if we can prove that at least one of the operands
8791         // is not a nan.
8792         if (!FiniteOnlyFPMath()) {
8793           if (DAG.isKnownNeverNaN(LHS)) {
8794             // Put the potential NaN in the RHS so that SSE will preserve it.
8795             std::swap(LHS, RHS);
8796           } else if (!DAG.isKnownNeverNaN(RHS))
8797             break;
8798         }
8799         Opcode = X86ISD::FMAX;
8800         break;
8801       case ISD::SETOLE:
8802         // This can be a max if we can prove that at least one of the operands
8803         // is not a nan.
8804         if (!FiniteOnlyFPMath()) {
8805           if (DAG.isKnownNeverNaN(RHS)) {
8806             // Put the potential NaN in the RHS so that SSE will preserve it.
8807             std::swap(LHS, RHS);
8808           } else if (!DAG.isKnownNeverNaN(LHS))
8809             break;
8810         }
8811         Opcode = X86ISD::FMAX;
8812         break;
8813       case ISD::SETULE:
8814         // This can be a max, but if either operand is a NaN we need it to
8815         // preserve the original LHS.
8816         std::swap(LHS, RHS);
8817       case ISD::SETOLT:
8818       case ISD::SETLT:
8819       case ISD::SETLE:
8820         Opcode = X86ISD::FMAX;
8821         break;
8822       }
8823     }
8824
8825     if (Opcode)
8826       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8827   }
8828
8829   // If this is a select between two integer constants, try to do some
8830   // optimizations.
8831   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8832     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8833       // Don't do this for crazy integer types.
8834       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8835         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8836         // so that TrueC (the true value) is larger than FalseC.
8837         bool NeedsCondInvert = false;
8838
8839         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8840             // Efficiently invertible.
8841             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8842              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8843               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8844           NeedsCondInvert = true;
8845           std::swap(TrueC, FalseC);
8846         }
8847
8848         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8849         if (FalseC->getAPIntValue() == 0 &&
8850             TrueC->getAPIntValue().isPowerOf2()) {
8851           if (NeedsCondInvert) // Invert the condition if needed.
8852             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8853                                DAG.getConstant(1, Cond.getValueType()));
8854
8855           // Zero extend the condition if needed.
8856           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8857
8858           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8859           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8860                              DAG.getConstant(ShAmt, MVT::i8));
8861         }
8862
8863         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8864         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8865           if (NeedsCondInvert) // Invert the condition if needed.
8866             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8867                                DAG.getConstant(1, Cond.getValueType()));
8868
8869           // Zero extend the condition if needed.
8870           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8871                              FalseC->getValueType(0), Cond);
8872           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8873                              SDValue(FalseC, 0));
8874         }
8875
8876         // Optimize cases that will turn into an LEA instruction.  This requires
8877         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8878         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8879           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8880           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8881
8882           bool isFastMultiplier = false;
8883           if (Diff < 10) {
8884             switch ((unsigned char)Diff) {
8885               default: break;
8886               case 1:  // result = add base, cond
8887               case 2:  // result = lea base(    , cond*2)
8888               case 3:  // result = lea base(cond, cond*2)
8889               case 4:  // result = lea base(    , cond*4)
8890               case 5:  // result = lea base(cond, cond*4)
8891               case 8:  // result = lea base(    , cond*8)
8892               case 9:  // result = lea base(cond, cond*8)
8893                 isFastMultiplier = true;
8894                 break;
8895             }
8896           }
8897
8898           if (isFastMultiplier) {
8899             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8900             if (NeedsCondInvert) // Invert the condition if needed.
8901               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8902                                  DAG.getConstant(1, Cond.getValueType()));
8903
8904             // Zero extend the condition if needed.
8905             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8906                                Cond);
8907             // Scale the condition by the difference.
8908             if (Diff != 1)
8909               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8910                                  DAG.getConstant(Diff, Cond.getValueType()));
8911
8912             // Add the base if non-zero.
8913             if (FalseC->getAPIntValue() != 0)
8914               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8915                                  SDValue(FalseC, 0));
8916             return Cond;
8917           }
8918         }
8919       }
8920   }
8921
8922   return SDValue();
8923 }
8924
8925 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8926 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8927                                   TargetLowering::DAGCombinerInfo &DCI) {
8928   DebugLoc DL = N->getDebugLoc();
8929
8930   // If the flag operand isn't dead, don't touch this CMOV.
8931   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8932     return SDValue();
8933
8934   // If this is a select between two integer constants, try to do some
8935   // optimizations.  Note that the operands are ordered the opposite of SELECT
8936   // operands.
8937   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8938     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8939       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8940       // larger than FalseC (the false value).
8941       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8942
8943       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8944         CC = X86::GetOppositeBranchCondition(CC);
8945         std::swap(TrueC, FalseC);
8946       }
8947
8948       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
8949       // This is efficient for any integer data type (including i8/i16) and
8950       // shift amount.
8951       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8952         SDValue Cond = N->getOperand(3);
8953         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8954                            DAG.getConstant(CC, MVT::i8), Cond);
8955
8956         // Zero extend the condition if needed.
8957         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8958
8959         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8960         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8961                            DAG.getConstant(ShAmt, MVT::i8));
8962         if (N->getNumValues() == 2)  // Dead flag value?
8963           return DCI.CombineTo(N, Cond, SDValue());
8964         return Cond;
8965       }
8966
8967       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
8968       // for any integer data type, including i8/i16.
8969       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8970         SDValue Cond = N->getOperand(3);
8971         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8972                            DAG.getConstant(CC, MVT::i8), Cond);
8973
8974         // Zero extend the condition if needed.
8975         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8976                            FalseC->getValueType(0), Cond);
8977         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8978                            SDValue(FalseC, 0));
8979
8980         if (N->getNumValues() == 2)  // Dead flag value?
8981           return DCI.CombineTo(N, Cond, SDValue());
8982         return Cond;
8983       }
8984
8985       // Optimize cases that will turn into an LEA instruction.  This requires
8986       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8987       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8988         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8989         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8990
8991         bool isFastMultiplier = false;
8992         if (Diff < 10) {
8993           switch ((unsigned char)Diff) {
8994           default: break;
8995           case 1:  // result = add base, cond
8996           case 2:  // result = lea base(    , cond*2)
8997           case 3:  // result = lea base(cond, cond*2)
8998           case 4:  // result = lea base(    , cond*4)
8999           case 5:  // result = lea base(cond, cond*4)
9000           case 8:  // result = lea base(    , cond*8)
9001           case 9:  // result = lea base(cond, cond*8)
9002             isFastMultiplier = true;
9003             break;
9004           }
9005         }
9006
9007         if (isFastMultiplier) {
9008           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9009           SDValue Cond = N->getOperand(3);
9010           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9011                              DAG.getConstant(CC, MVT::i8), Cond);
9012           // Zero extend the condition if needed.
9013           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9014                              Cond);
9015           // Scale the condition by the difference.
9016           if (Diff != 1)
9017             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9018                                DAG.getConstant(Diff, Cond.getValueType()));
9019
9020           // Add the base if non-zero.
9021           if (FalseC->getAPIntValue() != 0)
9022             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9023                                SDValue(FalseC, 0));
9024           if (N->getNumValues() == 2)  // Dead flag value?
9025             return DCI.CombineTo(N, Cond, SDValue());
9026           return Cond;
9027         }
9028       }
9029     }
9030   }
9031   return SDValue();
9032 }
9033
9034
9035 /// PerformMulCombine - Optimize a single multiply with constant into two
9036 /// in order to implement it with two cheaper instructions, e.g.
9037 /// LEA + SHL, LEA + LEA.
9038 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9039                                  TargetLowering::DAGCombinerInfo &DCI) {
9040   if (DAG.getMachineFunction().
9041       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9042     return SDValue();
9043
9044   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9045     return SDValue();
9046
9047   EVT VT = N->getValueType(0);
9048   if (VT != MVT::i64)
9049     return SDValue();
9050
9051   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9052   if (!C)
9053     return SDValue();
9054   uint64_t MulAmt = C->getZExtValue();
9055   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9056     return SDValue();
9057
9058   uint64_t MulAmt1 = 0;
9059   uint64_t MulAmt2 = 0;
9060   if ((MulAmt % 9) == 0) {
9061     MulAmt1 = 9;
9062     MulAmt2 = MulAmt / 9;
9063   } else if ((MulAmt % 5) == 0) {
9064     MulAmt1 = 5;
9065     MulAmt2 = MulAmt / 5;
9066   } else if ((MulAmt % 3) == 0) {
9067     MulAmt1 = 3;
9068     MulAmt2 = MulAmt / 3;
9069   }
9070   if (MulAmt2 &&
9071       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9072     DebugLoc DL = N->getDebugLoc();
9073
9074     if (isPowerOf2_64(MulAmt2) &&
9075         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9076       // If second multiplifer is pow2, issue it first. We want the multiply by
9077       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9078       // is an add.
9079       std::swap(MulAmt1, MulAmt2);
9080
9081     SDValue NewMul;
9082     if (isPowerOf2_64(MulAmt1))
9083       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9084                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9085     else
9086       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9087                            DAG.getConstant(MulAmt1, VT));
9088
9089     if (isPowerOf2_64(MulAmt2))
9090       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9091                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9092     else
9093       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9094                            DAG.getConstant(MulAmt2, VT));
9095
9096     // Do not add new nodes to DAG combiner worklist.
9097     DCI.CombineTo(N, NewMul, false);
9098   }
9099   return SDValue();
9100 }
9101
9102 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9103   SDValue N0 = N->getOperand(0);
9104   SDValue N1 = N->getOperand(1);
9105   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9106   EVT VT = N0.getValueType();
9107
9108   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9109   // since the result of setcc_c is all zero's or all ones.
9110   if (N1C && N0.getOpcode() == ISD::AND &&
9111       N0.getOperand(1).getOpcode() == ISD::Constant) {
9112     SDValue N00 = N0.getOperand(0);
9113     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9114         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9115           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9116          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9117       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9118       APInt ShAmt = N1C->getAPIntValue();
9119       Mask = Mask.shl(ShAmt);
9120       if (Mask != 0)
9121         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9122                            N00, DAG.getConstant(Mask, VT));
9123     }
9124   }
9125
9126   return SDValue();
9127 }
9128
9129 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9130 ///                       when possible.
9131 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9132                                    const X86Subtarget *Subtarget) {
9133   EVT VT = N->getValueType(0);
9134   if (!VT.isVector() && VT.isInteger() &&
9135       N->getOpcode() == ISD::SHL)
9136     return PerformSHLCombine(N, DAG);
9137
9138   // On X86 with SSE2 support, we can transform this to a vector shift if
9139   // all elements are shifted by the same amount.  We can't do this in legalize
9140   // because the a constant vector is typically transformed to a constant pool
9141   // so we have no knowledge of the shift amount.
9142   if (!Subtarget->hasSSE2())
9143     return SDValue();
9144
9145   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9146     return SDValue();
9147
9148   SDValue ShAmtOp = N->getOperand(1);
9149   EVT EltVT = VT.getVectorElementType();
9150   DebugLoc DL = N->getDebugLoc();
9151   SDValue BaseShAmt = SDValue();
9152   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9153     unsigned NumElts = VT.getVectorNumElements();
9154     unsigned i = 0;
9155     for (; i != NumElts; ++i) {
9156       SDValue Arg = ShAmtOp.getOperand(i);
9157       if (Arg.getOpcode() == ISD::UNDEF) continue;
9158       BaseShAmt = Arg;
9159       break;
9160     }
9161     for (; i != NumElts; ++i) {
9162       SDValue Arg = ShAmtOp.getOperand(i);
9163       if (Arg.getOpcode() == ISD::UNDEF) continue;
9164       if (Arg != BaseShAmt) {
9165         return SDValue();
9166       }
9167     }
9168   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9169              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9170     SDValue InVec = ShAmtOp.getOperand(0);
9171     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9172       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9173       unsigned i = 0;
9174       for (; i != NumElts; ++i) {
9175         SDValue Arg = InVec.getOperand(i);
9176         if (Arg.getOpcode() == ISD::UNDEF) continue;
9177         BaseShAmt = Arg;
9178         break;
9179       }
9180     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9181        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9182          unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9183          if (C->getZExtValue() == SplatIdx)
9184            BaseShAmt = InVec.getOperand(1);
9185        }
9186     }
9187     if (BaseShAmt.getNode() == 0)
9188       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9189                               DAG.getIntPtrConstant(0));
9190   } else
9191     return SDValue();
9192
9193   // The shift amount is an i32.
9194   if (EltVT.bitsGT(MVT::i32))
9195     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9196   else if (EltVT.bitsLT(MVT::i32))
9197     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9198
9199   // The shift amount is identical so we can do a vector shift.
9200   SDValue  ValOp = N->getOperand(0);
9201   switch (N->getOpcode()) {
9202   default:
9203     llvm_unreachable("Unknown shift opcode!");
9204     break;
9205   case ISD::SHL:
9206     if (VT == MVT::v2i64)
9207       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9208                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9209                          ValOp, BaseShAmt);
9210     if (VT == MVT::v4i32)
9211       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9212                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9213                          ValOp, BaseShAmt);
9214     if (VT == MVT::v8i16)
9215       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9216                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9217                          ValOp, BaseShAmt);
9218     break;
9219   case ISD::SRA:
9220     if (VT == MVT::v4i32)
9221       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9222                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9223                          ValOp, BaseShAmt);
9224     if (VT == MVT::v8i16)
9225       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9226                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9227                          ValOp, BaseShAmt);
9228     break;
9229   case ISD::SRL:
9230     if (VT == MVT::v2i64)
9231       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9232                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9233                          ValOp, BaseShAmt);
9234     if (VT == MVT::v4i32)
9235       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9236                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9237                          ValOp, BaseShAmt);
9238     if (VT ==  MVT::v8i16)
9239       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9240                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9241                          ValOp, BaseShAmt);
9242     break;
9243   }
9244   return SDValue();
9245 }
9246
9247 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9248                                 const X86Subtarget *Subtarget) {
9249   EVT VT = N->getValueType(0);
9250   if (VT != MVT::i64 || !Subtarget->is64Bit())
9251     return SDValue();
9252
9253   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9254   SDValue N0 = N->getOperand(0);
9255   SDValue N1 = N->getOperand(1);
9256   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9257     std::swap(N0, N1);
9258   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9259     return SDValue();
9260
9261   SDValue ShAmt0 = N0.getOperand(1);
9262   if (ShAmt0.getValueType() != MVT::i8)
9263     return SDValue();
9264   SDValue ShAmt1 = N1.getOperand(1);
9265   if (ShAmt1.getValueType() != MVT::i8)
9266     return SDValue();
9267   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9268     ShAmt0 = ShAmt0.getOperand(0);
9269   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9270     ShAmt1 = ShAmt1.getOperand(0);
9271
9272   DebugLoc DL = N->getDebugLoc();
9273   unsigned Opc = X86ISD::SHLD;
9274   SDValue Op0 = N0.getOperand(0);
9275   SDValue Op1 = N1.getOperand(0);
9276   if (ShAmt0.getOpcode() == ISD::SUB) {
9277     Opc = X86ISD::SHRD;
9278     std::swap(Op0, Op1);
9279     std::swap(ShAmt0, ShAmt1);
9280   }
9281
9282   if (ShAmt1.getOpcode() == ISD::SUB) {
9283     SDValue Sum = ShAmt1.getOperand(0);
9284     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9285       if (SumC->getSExtValue() == 64 &&
9286           ShAmt1.getOperand(1) == ShAmt0)
9287         return DAG.getNode(Opc, DL, VT,
9288                            Op0, Op1,
9289                            DAG.getNode(ISD::TRUNCATE, DL,
9290                                        MVT::i8, ShAmt0));
9291     }
9292   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9293     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9294     if (ShAmt0C &&
9295         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9296       return DAG.getNode(Opc, DL, VT,
9297                          N0.getOperand(0), N1.getOperand(0),
9298                          DAG.getNode(ISD::TRUNCATE, DL,
9299                                        MVT::i8, ShAmt0));
9300   }
9301
9302   return SDValue();
9303 }
9304
9305 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9306 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9307                                    const X86Subtarget *Subtarget) {
9308   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9309   // the FP state in cases where an emms may be missing.
9310   // A preferable solution to the general problem is to figure out the right
9311   // places to insert EMMS.  This qualifies as a quick hack.
9312
9313   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9314   StoreSDNode *St = cast<StoreSDNode>(N);
9315   EVT VT = St->getValue().getValueType();
9316   if (VT.getSizeInBits() != 64)
9317     return SDValue();
9318
9319   const Function *F = DAG.getMachineFunction().getFunction();
9320   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9321   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9322     && Subtarget->hasSSE2();
9323   if ((VT.isVector() ||
9324        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9325       isa<LoadSDNode>(St->getValue()) &&
9326       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9327       St->getChain().hasOneUse() && !St->isVolatile()) {
9328     SDNode* LdVal = St->getValue().getNode();
9329     LoadSDNode *Ld = 0;
9330     int TokenFactorIndex = -1;
9331     SmallVector<SDValue, 8> Ops;
9332     SDNode* ChainVal = St->getChain().getNode();
9333     // Must be a store of a load.  We currently handle two cases:  the load
9334     // is a direct child, and it's under an intervening TokenFactor.  It is
9335     // possible to dig deeper under nested TokenFactors.
9336     if (ChainVal == LdVal)
9337       Ld = cast<LoadSDNode>(St->getChain());
9338     else if (St->getValue().hasOneUse() &&
9339              ChainVal->getOpcode() == ISD::TokenFactor) {
9340       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9341         if (ChainVal->getOperand(i).getNode() == LdVal) {
9342           TokenFactorIndex = i;
9343           Ld = cast<LoadSDNode>(St->getValue());
9344         } else
9345           Ops.push_back(ChainVal->getOperand(i));
9346       }
9347     }
9348
9349     if (!Ld || !ISD::isNormalLoad(Ld))
9350       return SDValue();
9351
9352     // If this is not the MMX case, i.e. we are just turning i64 load/store
9353     // into f64 load/store, avoid the transformation if there are multiple
9354     // uses of the loaded value.
9355     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9356       return SDValue();
9357
9358     DebugLoc LdDL = Ld->getDebugLoc();
9359     DebugLoc StDL = N->getDebugLoc();
9360     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9361     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9362     // pair instead.
9363     if (Subtarget->is64Bit() || F64IsLegal) {
9364       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9365       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9366                                   Ld->getBasePtr(), Ld->getSrcValue(),
9367                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9368                                   Ld->getAlignment());
9369       SDValue NewChain = NewLd.getValue(1);
9370       if (TokenFactorIndex != -1) {
9371         Ops.push_back(NewChain);
9372         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9373                                Ops.size());
9374       }
9375       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9376                           St->getSrcValue(), St->getSrcValueOffset(),
9377                           St->isVolatile(), St->getAlignment());
9378     }
9379
9380     // Otherwise, lower to two pairs of 32-bit loads / stores.
9381     SDValue LoAddr = Ld->getBasePtr();
9382     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9383                                  DAG.getConstant(4, MVT::i32));
9384
9385     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9386                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9387                                Ld->isVolatile(), Ld->getAlignment());
9388     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9389                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9390                                Ld->isVolatile(),
9391                                MinAlign(Ld->getAlignment(), 4));
9392
9393     SDValue NewChain = LoLd.getValue(1);
9394     if (TokenFactorIndex != -1) {
9395       Ops.push_back(LoLd);
9396       Ops.push_back(HiLd);
9397       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9398                              Ops.size());
9399     }
9400
9401     LoAddr = St->getBasePtr();
9402     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9403                          DAG.getConstant(4, MVT::i32));
9404
9405     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9406                                 St->getSrcValue(), St->getSrcValueOffset(),
9407                                 St->isVolatile(), St->getAlignment());
9408     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9409                                 St->getSrcValue(),
9410                                 St->getSrcValueOffset() + 4,
9411                                 St->isVolatile(),
9412                                 MinAlign(St->getAlignment(), 4));
9413     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9414   }
9415   return SDValue();
9416 }
9417
9418 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9419 /// X86ISD::FXOR nodes.
9420 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9421   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9422   // F[X]OR(0.0, x) -> x
9423   // F[X]OR(x, 0.0) -> x
9424   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9425     if (C->getValueAPF().isPosZero())
9426       return N->getOperand(1);
9427   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9428     if (C->getValueAPF().isPosZero())
9429       return N->getOperand(0);
9430   return SDValue();
9431 }
9432
9433 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9434 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9435   // FAND(0.0, x) -> 0.0
9436   // FAND(x, 0.0) -> 0.0
9437   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9438     if (C->getValueAPF().isPosZero())
9439       return N->getOperand(0);
9440   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9441     if (C->getValueAPF().isPosZero())
9442       return N->getOperand(1);
9443   return SDValue();
9444 }
9445
9446 static SDValue PerformBTCombine(SDNode *N,
9447                                 SelectionDAG &DAG,
9448                                 TargetLowering::DAGCombinerInfo &DCI) {
9449   // BT ignores high bits in the bit index operand.
9450   SDValue Op1 = N->getOperand(1);
9451   if (Op1.hasOneUse()) {
9452     unsigned BitWidth = Op1.getValueSizeInBits();
9453     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9454     APInt KnownZero, KnownOne;
9455     TargetLowering::TargetLoweringOpt TLO(DAG);
9456     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9457     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9458         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9459       DCI.CommitTargetLoweringOpt(TLO);
9460   }
9461   return SDValue();
9462 }
9463
9464 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9465   SDValue Op = N->getOperand(0);
9466   if (Op.getOpcode() == ISD::BIT_CONVERT)
9467     Op = Op.getOperand(0);
9468   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9469   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9470       VT.getVectorElementType().getSizeInBits() ==
9471       OpVT.getVectorElementType().getSizeInBits()) {
9472     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9473   }
9474   return SDValue();
9475 }
9476
9477 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9478 // Locked instructions, in turn, have implicit fence semantics (all memory
9479 // operations are flushed before issuing the locked instruction, and the
9480 // are not buffered), so we can fold away the common pattern of
9481 // fence-atomic-fence.
9482 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9483   SDValue atomic = N->getOperand(0);
9484   switch (atomic.getOpcode()) {
9485     case ISD::ATOMIC_CMP_SWAP:
9486     case ISD::ATOMIC_SWAP:
9487     case ISD::ATOMIC_LOAD_ADD:
9488     case ISD::ATOMIC_LOAD_SUB:
9489     case ISD::ATOMIC_LOAD_AND:
9490     case ISD::ATOMIC_LOAD_OR:
9491     case ISD::ATOMIC_LOAD_XOR:
9492     case ISD::ATOMIC_LOAD_NAND:
9493     case ISD::ATOMIC_LOAD_MIN:
9494     case ISD::ATOMIC_LOAD_MAX:
9495     case ISD::ATOMIC_LOAD_UMIN:
9496     case ISD::ATOMIC_LOAD_UMAX:
9497       break;
9498     default:
9499       return SDValue();
9500   }
9501
9502   SDValue fence = atomic.getOperand(0);
9503   if (fence.getOpcode() != ISD::MEMBARRIER)
9504     return SDValue();
9505
9506   switch (atomic.getOpcode()) {
9507     case ISD::ATOMIC_CMP_SWAP:
9508       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9509                                     atomic.getOperand(1), atomic.getOperand(2),
9510                                     atomic.getOperand(3));
9511     case ISD::ATOMIC_SWAP:
9512     case ISD::ATOMIC_LOAD_ADD:
9513     case ISD::ATOMIC_LOAD_SUB:
9514     case ISD::ATOMIC_LOAD_AND:
9515     case ISD::ATOMIC_LOAD_OR:
9516     case ISD::ATOMIC_LOAD_XOR:
9517     case ISD::ATOMIC_LOAD_NAND:
9518     case ISD::ATOMIC_LOAD_MIN:
9519     case ISD::ATOMIC_LOAD_MAX:
9520     case ISD::ATOMIC_LOAD_UMIN:
9521     case ISD::ATOMIC_LOAD_UMAX:
9522       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9523                                     atomic.getOperand(1), atomic.getOperand(2));
9524     default:
9525       return SDValue();
9526   }
9527 }
9528
9529 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9530   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9531   //           (and (i32 x86isd::setcc_carry), 1)
9532   // This eliminates the zext. This transformation is necessary because
9533   // ISD::SETCC is always legalized to i8.
9534   DebugLoc dl = N->getDebugLoc();
9535   SDValue N0 = N->getOperand(0);
9536   EVT VT = N->getValueType(0);
9537   if (N0.getOpcode() == ISD::AND &&
9538       N0.hasOneUse() &&
9539       N0.getOperand(0).hasOneUse()) {
9540     SDValue N00 = N0.getOperand(0);
9541     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9542       return SDValue();
9543     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9544     if (!C || C->getZExtValue() != 1)
9545       return SDValue();
9546     return DAG.getNode(ISD::AND, dl, VT,
9547                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9548                                    N00.getOperand(0), N00.getOperand(1)),
9549                        DAG.getConstant(1, VT));
9550   }
9551
9552   return SDValue();
9553 }
9554
9555 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9556                                              DAGCombinerInfo &DCI) const {
9557   SelectionDAG &DAG = DCI.DAG;
9558   switch (N->getOpcode()) {
9559   default: break;
9560   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9561   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9562   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9563   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9564   case ISD::SHL:
9565   case ISD::SRA:
9566   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9567   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9568   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9569   case X86ISD::FXOR:
9570   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9571   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9572   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9573   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9574   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9575   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9576   }
9577
9578   return SDValue();
9579 }
9580
9581 //===----------------------------------------------------------------------===//
9582 //                           X86 Inline Assembly Support
9583 //===----------------------------------------------------------------------===//
9584
9585 static bool LowerToBSwap(CallInst *CI) {
9586   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9587   // we will turn this bswap into something that will be lowered to logical ops
9588   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9589   // so don't worry about this.
9590
9591   // Verify this is a simple bswap.
9592   if (CI->getNumOperands() != 2 ||
9593       CI->getType() != CI->getOperand(1)->getType() ||
9594       !CI->getType()->isInteger())
9595     return false;
9596
9597   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9598   if (!Ty || Ty->getBitWidth() % 16 != 0)
9599     return false;
9600
9601   // Okay, we can do this xform, do so now.
9602   const Type *Tys[] = { Ty };
9603   Module *M = CI->getParent()->getParent()->getParent();
9604   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9605
9606   Value *Op = CI->getOperand(1);
9607   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9608
9609   CI->replaceAllUsesWith(Op);
9610   CI->eraseFromParent();
9611   return true;
9612 }
9613
9614 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9615   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9616   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9617
9618   std::string AsmStr = IA->getAsmString();
9619
9620   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9621   SmallVector<StringRef, 4> AsmPieces;
9622   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9623
9624   switch (AsmPieces.size()) {
9625   default: return false;
9626   case 1:
9627     AsmStr = AsmPieces[0];
9628     AsmPieces.clear();
9629     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9630
9631     // bswap $0
9632     if (AsmPieces.size() == 2 &&
9633         (AsmPieces[0] == "bswap" ||
9634          AsmPieces[0] == "bswapq" ||
9635          AsmPieces[0] == "bswapl") &&
9636         (AsmPieces[1] == "$0" ||
9637          AsmPieces[1] == "${0:q}")) {
9638       // No need to check constraints, nothing other than the equivalent of
9639       // "=r,0" would be valid here.
9640       return LowerToBSwap(CI);
9641     }
9642     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9643     if (CI->getType()->isInteger(16) &&
9644         AsmPieces.size() == 3 &&
9645         AsmPieces[0] == "rorw" &&
9646         AsmPieces[1] == "$$8," &&
9647         AsmPieces[2] == "${0:w}" &&
9648         IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9649       return LowerToBSwap(CI);
9650     }
9651     break;
9652   case 3:
9653     if (CI->getType()->isInteger(64) &&
9654         Constraints.size() >= 2 &&
9655         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9656         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9657       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9658       SmallVector<StringRef, 4> Words;
9659       SplitString(AsmPieces[0], Words, " \t");
9660       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9661         Words.clear();
9662         SplitString(AsmPieces[1], Words, " \t");
9663         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9664           Words.clear();
9665           SplitString(AsmPieces[2], Words, " \t,");
9666           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9667               Words[2] == "%edx") {
9668             return LowerToBSwap(CI);
9669           }
9670         }
9671       }
9672     }
9673     break;
9674   }
9675   return false;
9676 }
9677
9678
9679
9680 /// getConstraintType - Given a constraint letter, return the type of
9681 /// constraint it is for this target.
9682 X86TargetLowering::ConstraintType
9683 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9684   if (Constraint.size() == 1) {
9685     switch (Constraint[0]) {
9686     case 'A':
9687       return C_Register;
9688     case 'f':
9689     case 'r':
9690     case 'R':
9691     case 'l':
9692     case 'q':
9693     case 'Q':
9694     case 'x':
9695     case 'y':
9696     case 'Y':
9697       return C_RegisterClass;
9698     case 'e':
9699     case 'Z':
9700       return C_Other;
9701     default:
9702       break;
9703     }
9704   }
9705   return TargetLowering::getConstraintType(Constraint);
9706 }
9707
9708 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9709 /// with another that has more specific requirements based on the type of the
9710 /// corresponding operand.
9711 const char *X86TargetLowering::
9712 LowerXConstraint(EVT ConstraintVT) const {
9713   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9714   // 'f' like normal targets.
9715   if (ConstraintVT.isFloatingPoint()) {
9716     if (Subtarget->hasSSE2())
9717       return "Y";
9718     if (Subtarget->hasSSE1())
9719       return "x";
9720   }
9721
9722   return TargetLowering::LowerXConstraint(ConstraintVT);
9723 }
9724
9725 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9726 /// vector.  If it is invalid, don't add anything to Ops.
9727 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9728                                                      char Constraint,
9729                                                      bool hasMemory,
9730                                                      std::vector<SDValue>&Ops,
9731                                                      SelectionDAG &DAG) const {
9732   SDValue Result(0, 0);
9733
9734   switch (Constraint) {
9735   default: break;
9736   case 'I':
9737     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9738       if (C->getZExtValue() <= 31) {
9739         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9740         break;
9741       }
9742     }
9743     return;
9744   case 'J':
9745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9746       if (C->getZExtValue() <= 63) {
9747         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9748         break;
9749       }
9750     }
9751     return;
9752   case 'K':
9753     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9754       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9755         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9756         break;
9757       }
9758     }
9759     return;
9760   case 'N':
9761     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9762       if (C->getZExtValue() <= 255) {
9763         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9764         break;
9765       }
9766     }
9767     return;
9768   case 'e': {
9769     // 32-bit signed value
9770     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9771       const ConstantInt *CI = C->getConstantIntValue();
9772       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9773                                   C->getSExtValue())) {
9774         // Widen to 64 bits here to get it sign extended.
9775         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9776         break;
9777       }
9778     // FIXME gcc accepts some relocatable values here too, but only in certain
9779     // memory models; it's complicated.
9780     }
9781     return;
9782   }
9783   case 'Z': {
9784     // 32-bit unsigned value
9785     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9786       const ConstantInt *CI = C->getConstantIntValue();
9787       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9788                                   C->getZExtValue())) {
9789         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9790         break;
9791       }
9792     }
9793     // FIXME gcc accepts some relocatable values here too, but only in certain
9794     // memory models; it's complicated.
9795     return;
9796   }
9797   case 'i': {
9798     // Literal immediates are always ok.
9799     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9800       // Widen to 64 bits here to get it sign extended.
9801       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9802       break;
9803     }
9804
9805     // If we are in non-pic codegen mode, we allow the address of a global (with
9806     // an optional displacement) to be used with 'i'.
9807     GlobalAddressSDNode *GA = 0;
9808     int64_t Offset = 0;
9809
9810     // Match either (GA), (GA+C), (GA+C1+C2), etc.
9811     while (1) {
9812       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9813         Offset += GA->getOffset();
9814         break;
9815       } else if (Op.getOpcode() == ISD::ADD) {
9816         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9817           Offset += C->getZExtValue();
9818           Op = Op.getOperand(0);
9819           continue;
9820         }
9821       } else if (Op.getOpcode() == ISD::SUB) {
9822         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9823           Offset += -C->getZExtValue();
9824           Op = Op.getOperand(0);
9825           continue;
9826         }
9827       }
9828
9829       // Otherwise, this isn't something we can handle, reject it.
9830       return;
9831     }
9832
9833     GlobalValue *GV = GA->getGlobal();
9834     // If we require an extra load to get this address, as in PIC mode, we
9835     // can't accept it.
9836     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9837                                                         getTargetMachine())))
9838       return;
9839
9840     if (hasMemory)
9841       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9842     else
9843       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9844     Result = Op;
9845     break;
9846   }
9847   }
9848
9849   if (Result.getNode()) {
9850     Ops.push_back(Result);
9851     return;
9852   }
9853   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9854                                                       Ops, DAG);
9855 }
9856
9857 std::vector<unsigned> X86TargetLowering::
9858 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9859                                   EVT VT) const {
9860   if (Constraint.size() == 1) {
9861     // FIXME: not handling fp-stack yet!
9862     switch (Constraint[0]) {      // GCC X86 Constraint Letters
9863     default: break;  // Unknown constraint letter
9864     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9865       if (Subtarget->is64Bit()) {
9866         if (VT == MVT::i32)
9867           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9868                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9869                                        X86::R10D,X86::R11D,X86::R12D,
9870                                        X86::R13D,X86::R14D,X86::R15D,
9871                                        X86::EBP, X86::ESP, 0);
9872         else if (VT == MVT::i16)
9873           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
9874                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
9875                                        X86::R10W,X86::R11W,X86::R12W,
9876                                        X86::R13W,X86::R14W,X86::R15W,
9877                                        X86::BP,  X86::SP, 0);
9878         else if (VT == MVT::i8)
9879           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
9880                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9881                                        X86::R10B,X86::R11B,X86::R12B,
9882                                        X86::R13B,X86::R14B,X86::R15B,
9883                                        X86::BPL, X86::SPL, 0);
9884
9885         else if (VT == MVT::i64)
9886           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9887                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
9888                                        X86::R10, X86::R11, X86::R12,
9889                                        X86::R13, X86::R14, X86::R15,
9890                                        X86::RBP, X86::RSP, 0);
9891
9892         break;
9893       }
9894       // 32-bit fallthrough
9895     case 'Q':   // Q_REGS
9896       if (VT == MVT::i32)
9897         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9898       else if (VT == MVT::i16)
9899         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9900       else if (VT == MVT::i8)
9901         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9902       else if (VT == MVT::i64)
9903         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9904       break;
9905     }
9906   }
9907
9908   return std::vector<unsigned>();
9909 }
9910
9911 std::pair<unsigned, const TargetRegisterClass*>
9912 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9913                                                 EVT VT) const {
9914   // First, see if this is a constraint that directly corresponds to an LLVM
9915   // register class.
9916   if (Constraint.size() == 1) {
9917     // GCC Constraint Letters
9918     switch (Constraint[0]) {
9919     default: break;
9920     case 'r':   // GENERAL_REGS
9921     case 'l':   // INDEX_REGS
9922       if (VT == MVT::i8)
9923         return std::make_pair(0U, X86::GR8RegisterClass);
9924       if (VT == MVT::i16)
9925         return std::make_pair(0U, X86::GR16RegisterClass);
9926       if (VT == MVT::i32 || !Subtarget->is64Bit())
9927         return std::make_pair(0U, X86::GR32RegisterClass);
9928       return std::make_pair(0U, X86::GR64RegisterClass);
9929     case 'R':   // LEGACY_REGS
9930       if (VT == MVT::i8)
9931         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9932       if (VT == MVT::i16)
9933         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9934       if (VT == MVT::i32 || !Subtarget->is64Bit())
9935         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9936       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9937     case 'f':  // FP Stack registers.
9938       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9939       // value to the correct fpstack register class.
9940       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9941         return std::make_pair(0U, X86::RFP32RegisterClass);
9942       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9943         return std::make_pair(0U, X86::RFP64RegisterClass);
9944       return std::make_pair(0U, X86::RFP80RegisterClass);
9945     case 'y':   // MMX_REGS if MMX allowed.
9946       if (!Subtarget->hasMMX()) break;
9947       return std::make_pair(0U, X86::VR64RegisterClass);
9948     case 'Y':   // SSE_REGS if SSE2 allowed
9949       if (!Subtarget->hasSSE2()) break;
9950       // FALL THROUGH.
9951     case 'x':   // SSE_REGS if SSE1 allowed
9952       if (!Subtarget->hasSSE1()) break;
9953
9954       switch (VT.getSimpleVT().SimpleTy) {
9955       default: break;
9956       // Scalar SSE types.
9957       case MVT::f32:
9958       case MVT::i32:
9959         return std::make_pair(0U, X86::FR32RegisterClass);
9960       case MVT::f64:
9961       case MVT::i64:
9962         return std::make_pair(0U, X86::FR64RegisterClass);
9963       // Vector types.
9964       case MVT::v16i8:
9965       case MVT::v8i16:
9966       case MVT::v4i32:
9967       case MVT::v2i64:
9968       case MVT::v4f32:
9969       case MVT::v2f64:
9970         return std::make_pair(0U, X86::VR128RegisterClass);
9971       }
9972       break;
9973     }
9974   }
9975
9976   // Use the default implementation in TargetLowering to convert the register
9977   // constraint into a member of a register class.
9978   std::pair<unsigned, const TargetRegisterClass*> Res;
9979   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9980
9981   // Not found as a standard register?
9982   if (Res.second == 0) {
9983     // Map st(0) -> st(7) -> ST0
9984     if (Constraint.size() == 7 && Constraint[0] == '{' &&
9985         tolower(Constraint[1]) == 's' &&
9986         tolower(Constraint[2]) == 't' &&
9987         Constraint[3] == '(' &&
9988         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9989         Constraint[5] == ')' &&
9990         Constraint[6] == '}') {
9991
9992       Res.first = X86::ST0+Constraint[4]-'0';
9993       Res.second = X86::RFP80RegisterClass;
9994       return Res;
9995     }
9996
9997     // GCC allows "st(0)" to be called just plain "st".
9998     if (StringRef("{st}").equals_lower(Constraint)) {
9999       Res.first = X86::ST0;
10000       Res.second = X86::RFP80RegisterClass;
10001       return Res;
10002     }
10003
10004     // flags -> EFLAGS
10005     if (StringRef("{flags}").equals_lower(Constraint)) {
10006       Res.first = X86::EFLAGS;
10007       Res.second = X86::CCRRegisterClass;
10008       return Res;
10009     }
10010
10011     // 'A' means EAX + EDX.
10012     if (Constraint == "A") {
10013       Res.first = X86::EAX;
10014       Res.second = X86::GR32_ADRegisterClass;
10015       return Res;
10016     }
10017     return Res;
10018   }
10019
10020   // Otherwise, check to see if this is a register class of the wrong value
10021   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10022   // turn into {ax},{dx}.
10023   if (Res.second->hasType(VT))
10024     return Res;   // Correct type already, nothing to do.
10025
10026   // All of the single-register GCC register classes map their values onto
10027   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10028   // really want an 8-bit or 32-bit register, map to the appropriate register
10029   // class and return the appropriate register.
10030   if (Res.second == X86::GR16RegisterClass) {
10031     if (VT == MVT::i8) {
10032       unsigned DestReg = 0;
10033       switch (Res.first) {
10034       default: break;
10035       case X86::AX: DestReg = X86::AL; break;
10036       case X86::DX: DestReg = X86::DL; break;
10037       case X86::CX: DestReg = X86::CL; break;
10038       case X86::BX: DestReg = X86::BL; break;
10039       }
10040       if (DestReg) {
10041         Res.first = DestReg;
10042         Res.second = X86::GR8RegisterClass;
10043       }
10044     } else if (VT == MVT::i32) {
10045       unsigned DestReg = 0;
10046       switch (Res.first) {
10047       default: break;
10048       case X86::AX: DestReg = X86::EAX; break;
10049       case X86::DX: DestReg = X86::EDX; break;
10050       case X86::CX: DestReg = X86::ECX; break;
10051       case X86::BX: DestReg = X86::EBX; break;
10052       case X86::SI: DestReg = X86::ESI; break;
10053       case X86::DI: DestReg = X86::EDI; break;
10054       case X86::BP: DestReg = X86::EBP; break;
10055       case X86::SP: DestReg = X86::ESP; break;
10056       }
10057       if (DestReg) {
10058         Res.first = DestReg;
10059         Res.second = X86::GR32RegisterClass;
10060       }
10061     } else if (VT == MVT::i64) {
10062       unsigned DestReg = 0;
10063       switch (Res.first) {
10064       default: break;
10065       case X86::AX: DestReg = X86::RAX; break;
10066       case X86::DX: DestReg = X86::RDX; break;
10067       case X86::CX: DestReg = X86::RCX; break;
10068       case X86::BX: DestReg = X86::RBX; break;
10069       case X86::SI: DestReg = X86::RSI; break;
10070       case X86::DI: DestReg = X86::RDI; break;
10071       case X86::BP: DestReg = X86::RBP; break;
10072       case X86::SP: DestReg = X86::RSP; break;
10073       }
10074       if (DestReg) {
10075         Res.first = DestReg;
10076         Res.second = X86::GR64RegisterClass;
10077       }
10078     }
10079   } else if (Res.second == X86::FR32RegisterClass ||
10080              Res.second == X86::FR64RegisterClass ||
10081              Res.second == X86::VR128RegisterClass) {
10082     // Handle references to XMM physical registers that got mapped into the
10083     // wrong class.  This can happen with constraints like {xmm0} where the
10084     // target independent register mapper will just pick the first match it can
10085     // find, ignoring the required type.
10086     if (VT == MVT::f32)
10087       Res.second = X86::FR32RegisterClass;
10088     else if (VT == MVT::f64)
10089       Res.second = X86::FR64RegisterClass;
10090     else if (X86::VR128RegisterClass->hasType(VT))
10091       Res.second = X86::VR128RegisterClass;
10092   }
10093
10094   return Res;
10095 }
10096
10097 //===----------------------------------------------------------------------===//
10098 //                           X86 Widen vector type
10099 //===----------------------------------------------------------------------===//
10100
10101 /// getWidenVectorType: given a vector type, returns the type to widen
10102 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10103 /// If there is no vector type that we want to widen to, returns MVT::Other
10104 /// When and where to widen is target dependent based on the cost of
10105 /// scalarizing vs using the wider vector type.
10106
10107 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10108   assert(VT.isVector());
10109   if (isTypeLegal(VT))
10110     return VT;
10111
10112   // TODO: In computeRegisterProperty, we can compute the list of legal vector
10113   //       type based on element type.  This would speed up our search (though
10114   //       it may not be worth it since the size of the list is relatively
10115   //       small).
10116   EVT EltVT = VT.getVectorElementType();
10117   unsigned NElts = VT.getVectorNumElements();
10118
10119   // On X86, it make sense to widen any vector wider than 1
10120   if (NElts <= 1)
10121     return MVT::Other;
10122
10123   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10124        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10125     EVT SVT = (MVT::SimpleValueType)nVT;
10126
10127     if (isTypeLegal(SVT) &&
10128         SVT.getVectorElementType() == EltVT &&
10129         SVT.getVectorNumElements() > NElts)
10130       return SVT;
10131   }
10132   return MVT::Other;
10133 }