Make x86-64 64-bit bitconvert work when SSE is not available.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66   default: llvm_unreachable("unknown subtarget type");
67   case X86Subtarget::isDarwin:
68     if (TM.getSubtarget<X86Subtarget>().is64Bit())
69       return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   case X86Subtarget::isELF:
72    if (TM.getSubtarget<X86Subtarget>().is64Bit())
73      return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80 }
81
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83   : TargetLowering(TM, createTLOF(TM)) {
84   Subtarget = &TM.getSubtarget<X86Subtarget>();
85   X86ScalarSSEf64 = Subtarget->hasSSE2();
86   X86ScalarSSEf32 = Subtarget->hasSSE1();
87   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88
89   RegInfo = TM.getRegisterInfo();
90   TD = getTargetData();
91
92   // Set up the TargetLowering object.
93
94   // X86 is weird, it always uses i8 for shift amounts and setcc results.
95   setShiftAmountType(MVT::i8);
96   setBooleanContents(ZeroOrOneBooleanContent);
97   setSchedulingPreference(SchedulingForRegPressure);
98   setStackPointerRegisterToSaveRestore(X86StackPtr);
99
100   if (Subtarget->isTargetDarwin()) {
101     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102     setUseUnderscoreSetJmp(false);
103     setUseUnderscoreLongJmp(false);
104   } else if (Subtarget->isTargetMingw()) {
105     // MS runtime is weird: it exports _setjmp, but longjmp!
106     setUseUnderscoreSetJmp(true);
107     setUseUnderscoreLongJmp(false);
108   } else {
109     setUseUnderscoreSetJmp(true);
110     setUseUnderscoreLongJmp(true);
111   }
112
113   // Set up the register classes.
114   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117   if (Subtarget->is64Bit())
118     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119
120   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121
122   // We don't accept any truncstore of integer registers.
123   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
129
130   // SETOEQ and SETUNE require checking two conditions.
131   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137
138   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139   // operation.
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
141   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
142   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
143
144   if (Subtarget->is64Bit()) {
145     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
146     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
147   } else if (!UseSoftFloat) {
148     // We have an algorithm for SSE2->double, and we turn this into a
149     // 64-bit FILD followed by conditional FADD for other targets.
150     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
151     // We have an algorithm for SSE2, and we turn this into a 64-bit
152     // FILD for other targets.
153     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
154   }
155
156   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
157   // this operation.
158   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
159   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
160
161   if (!UseSoftFloat) {
162     // SSE has no i16 to fp conversion, only i32
163     if (X86ScalarSSEf32) {
164       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
165       // f32 and f64 cases are Legal, f80 case is not
166       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
167     } else {
168       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
170     }
171   } else {
172     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
173     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
174   }
175
176   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
177   // are Legal, f80 is custom lowered.
178   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
179   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
180
181   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
182   // this operation.
183   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
184   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
185
186   if (X86ScalarSSEf32) {
187     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
188     // f32 and f64 cases are Legal, f80 case is not
189     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
190   } else {
191     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
193   }
194
195   // Handle FP_TO_UINT by promoting the destination to a larger signed
196   // conversion.
197   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
198   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
199   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
200
201   if (Subtarget->is64Bit()) {
202     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
203     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
204   } else if (!UseSoftFloat) {
205     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
206       // Expand FP_TO_UINT into a select.
207       // FIXME: We would like to use a Custom expander here eventually to do
208       // the optimal thing for SSE vs. the default expansion in the legalizer.
209       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
210     else
211       // With SSE3 we can use fisttpll to convert to a signed i64; without
212       // SSE, we're stuck with a fistpll.
213       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
214   }
215
216   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
217   if (!X86ScalarSSEf64) {
218     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
219     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
220     if (Subtarget->is64Bit()) {
221       setOperationAction(ISD::BIT_CONVERT      , MVT::f64  , Expand);
222       setOperationAction(ISD::BIT_CONVERT      , MVT::i64  , Expand);
223     }
224   }
225
226   // Scalar integer divide and remainder are lowered to use operations that
227   // produce two results, to match the available instructions. This exposes
228   // the two-result form to trivial CSE, which is able to combine x/y and x%y
229   // into a single instruction.
230   //
231   // Scalar integer multiply-high is also lowered to use two-result
232   // operations, to match the available instructions. However, plain multiply
233   // (low) operations are left as Legal, as there are single-result
234   // instructions for this in x86. Using the two-result multiply instructions
235   // when both high and low results are needed must be arranged by dagcombine.
236   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
237   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
238   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
239   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
240   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
241   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
242   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
243   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
244   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
245   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
246   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
247   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
248   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
249   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
250   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
251   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
252   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
253   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
254   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
255   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
256   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
257   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
258   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
259   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
260
261   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
262   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
263   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
264   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
265   if (Subtarget->is64Bit())
266     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
267   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
268   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
270   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
271   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
272   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
273   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
274   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
275
276   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
277   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
278   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
279   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
280   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
281   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
282   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
283   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
284   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
285   if (Subtarget->is64Bit()) {
286     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
287     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
288     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
289   }
290
291   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
292   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
293
294   // These should be promoted to a larger select which is supported.
295   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
296   // X86 wants to expand cmov itself.
297   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
298   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
299   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
300   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
301   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
302   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
303   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
304   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
305   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
306   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
307   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
308   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
309   if (Subtarget->is64Bit()) {
310     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
311     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
312   }
313   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
314
315   // Darwin ABI issue.
316   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
317   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
318   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
319   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
320   if (Subtarget->is64Bit())
321     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
322   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
323   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
324   if (Subtarget->is64Bit()) {
325     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
326     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
327     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
328     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
329     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
330   }
331   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
332   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
333   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
334   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
335   if (Subtarget->is64Bit()) {
336     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
337     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
338     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
339   }
340
341   if (Subtarget->hasSSE1())
342     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
343
344   if (!Subtarget->hasSSE2())
345     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
346
347   // Expand certain atomics
348   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
349   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
350   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
351   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
352
353   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
354   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
355   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
356   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
357
358   if (!Subtarget->is64Bit()) {
359     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
360     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
361     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
362     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
363     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
364     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
365     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
366   }
367
368   // FIXME - use subtarget debug flags
369   if (!Subtarget->isTargetDarwin() &&
370       !Subtarget->isTargetELF() &&
371       !Subtarget->isTargetCygMing()) {
372     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
373   }
374
375   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
376   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
377   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
378   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
379   if (Subtarget->is64Bit()) {
380     setExceptionPointerRegister(X86::RAX);
381     setExceptionSelectorRegister(X86::RDX);
382   } else {
383     setExceptionPointerRegister(X86::EAX);
384     setExceptionSelectorRegister(X86::EDX);
385   }
386   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
387   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
388
389   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
390
391   setOperationAction(ISD::TRAP, MVT::Other, Legal);
392
393   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
394   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
395   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
396   if (Subtarget->is64Bit()) {
397     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
398     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
399   } else {
400     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
401     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
402   }
403
404   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
405   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
406   if (Subtarget->is64Bit())
407     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
408   if (Subtarget->isTargetCygMing())
409     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
410   else
411     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
412
413   if (!UseSoftFloat && X86ScalarSSEf64) {
414     // f32 and f64 use SSE.
415     // Set up the FP register classes.
416     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
417     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
418
419     // Use ANDPD to simulate FABS.
420     setOperationAction(ISD::FABS , MVT::f64, Custom);
421     setOperationAction(ISD::FABS , MVT::f32, Custom);
422
423     // Use XORP to simulate FNEG.
424     setOperationAction(ISD::FNEG , MVT::f64, Custom);
425     setOperationAction(ISD::FNEG , MVT::f32, Custom);
426
427     // Use ANDPD and ORPD to simulate FCOPYSIGN.
428     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
429     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
430
431     // We don't support sin/cos/fmod
432     setOperationAction(ISD::FSIN , MVT::f64, Expand);
433     setOperationAction(ISD::FCOS , MVT::f64, Expand);
434     setOperationAction(ISD::FSIN , MVT::f32, Expand);
435     setOperationAction(ISD::FCOS , MVT::f32, Expand);
436
437     // Expand FP immediates into loads from the stack, except for the special
438     // cases we handle.
439     addLegalFPImmediate(APFloat(+0.0)); // xorpd
440     addLegalFPImmediate(APFloat(+0.0f)); // xorps
441   } else if (!UseSoftFloat && X86ScalarSSEf32) {
442     // Use SSE for f32, x87 for f64.
443     // Set up the FP register classes.
444     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
445     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
446
447     // Use ANDPS to simulate FABS.
448     setOperationAction(ISD::FABS , MVT::f32, Custom);
449
450     // Use XORP to simulate FNEG.
451     setOperationAction(ISD::FNEG , MVT::f32, Custom);
452
453     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
454
455     // Use ANDPS and ORPS to simulate FCOPYSIGN.
456     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
457     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
458
459     // We don't support sin/cos/fmod
460     setOperationAction(ISD::FSIN , MVT::f32, Expand);
461     setOperationAction(ISD::FCOS , MVT::f32, Expand);
462
463     // Special cases we handle for FP constants.
464     addLegalFPImmediate(APFloat(+0.0f)); // xorps
465     addLegalFPImmediate(APFloat(+0.0)); // FLD0
466     addLegalFPImmediate(APFloat(+1.0)); // FLD1
467     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
468     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
469
470     if (!UnsafeFPMath) {
471       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
472       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
473     }
474   } else if (!UseSoftFloat) {
475     // f32 and f64 in x87.
476     // Set up the FP register classes.
477     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
478     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
479
480     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
481     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
482     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
483     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
484
485     if (!UnsafeFPMath) {
486       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
487       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
488     }
489     addLegalFPImmediate(APFloat(+0.0)); // FLD0
490     addLegalFPImmediate(APFloat(+1.0)); // FLD1
491     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
492     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
493     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
494     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
495     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
496     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
497   }
498
499   // Long double always uses X87.
500   if (!UseSoftFloat) {
501     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
502     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
503     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
504     {
505       bool ignored;
506       APFloat TmpFlt(+0.0);
507       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
508                      &ignored);
509       addLegalFPImmediate(TmpFlt);  // FLD0
510       TmpFlt.changeSign();
511       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
512       APFloat TmpFlt2(+1.0);
513       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
514                       &ignored);
515       addLegalFPImmediate(TmpFlt2);  // FLD1
516       TmpFlt2.changeSign();
517       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
518     }
519
520     if (!UnsafeFPMath) {
521       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
522       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
523     }
524   }
525
526   // Always use a library call for pow.
527   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
528   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
529   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
530
531   setOperationAction(ISD::FLOG, MVT::f80, Expand);
532   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
533   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
534   setOperationAction(ISD::FEXP, MVT::f80, Expand);
535   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
536
537   // First set operation action for all vector types to either promote
538   // (for widening) or expand (for scalarization). Then we will selectively
539   // turn on ones that can be effectively codegen'd.
540   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
541        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
542     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
557     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
558     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
591     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
595     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
596          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
597       setTruncStoreAction((MVT::SimpleValueType)VT,
598                           (MVT::SimpleValueType)InnerVT, Expand);
599     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
600     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
601     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
602   }
603
604   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
605   // with -msoft-float, disable use of MMX as well.
606   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
607     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
608     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
609     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
610     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
611     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
612
613     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
614     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
615     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
616     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
617
618     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
619     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
620     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
621     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
622
623     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
624     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
625
626     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
627     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
628     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
629     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
630     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
631     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
632     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
633
634     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
635     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
636     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
637     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
638     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
639     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
640     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
641
642     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
643     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
644     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
645     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
646     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
647     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
648     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
649
650     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
651     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
652     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
653     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
654     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
655     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
656     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
657     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
658     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
659
660     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
661     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
662     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
663     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
664     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
665
666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
668     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
669     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
670
671     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
672     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
673     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
674     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
675
676     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
677
678     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
679     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
680     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
681     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
682     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
683     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
684     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
685   }
686
687   if (!UseSoftFloat && Subtarget->hasSSE1()) {
688     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
689
690     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
691     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
692     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
693     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
694     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
695     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
696     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
697     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
698     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
699     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
700     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
701     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
702   }
703
704   if (!UseSoftFloat && Subtarget->hasSSE2()) {
705     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
706
707     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
708     // registers cannot be used even for integer operations.
709     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
710     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
711     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
712     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
713
714     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
715     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
716     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
717     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
718     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
719     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
720     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
721     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
722     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
723     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
724     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
725     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
726     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
727     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
728     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
729     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
730
731     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
732     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
733     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
734     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
735
736     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
737     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
738     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
739     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
740     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
741
742     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
743     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
744     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
745     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
746     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
747
748     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
749     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
750       EVT VT = (MVT::SimpleValueType)i;
751       // Do not attempt to custom lower non-power-of-2 vectors
752       if (!isPowerOf2_32(VT.getVectorNumElements()))
753         continue;
754       // Do not attempt to custom lower non-128-bit vectors
755       if (!VT.is128BitVector())
756         continue;
757       setOperationAction(ISD::BUILD_VECTOR,
758                          VT.getSimpleVT().SimpleTy, Custom);
759       setOperationAction(ISD::VECTOR_SHUFFLE,
760                          VT.getSimpleVT().SimpleTy, Custom);
761       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
762                          VT.getSimpleVT().SimpleTy, Custom);
763     }
764
765     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
766     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
767     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
768     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
769     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
770     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
771
772     if (Subtarget->is64Bit()) {
773       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
774       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
775     }
776
777     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
778     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
779       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
780       EVT VT = SVT;
781
782       // Do not attempt to promote non-128-bit vectors
783       if (!VT.is128BitVector()) {
784         continue;
785       }
786       
787       setOperationAction(ISD::AND,    SVT, Promote);
788       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
789       setOperationAction(ISD::OR,     SVT, Promote);
790       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
791       setOperationAction(ISD::XOR,    SVT, Promote);
792       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
793       setOperationAction(ISD::LOAD,   SVT, Promote);
794       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
795       setOperationAction(ISD::SELECT, SVT, Promote);
796       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
797     }
798
799     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
800
801     // Custom lower v2i64 and v2f64 selects.
802     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
803     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
804     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
805     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
806
807     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
808     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
809     if (!DisableMMX && Subtarget->hasMMX()) {
810       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
811       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
812     }
813   }
814
815   if (Subtarget->hasSSE41()) {
816     // FIXME: Do we need to handle scalar-to-vector here?
817     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
818
819     // i8 and i16 vectors are custom , because the source register and source
820     // source memory operand types are not the same width.  f32 vectors are
821     // custom since the immediate controlling the insert encodes additional
822     // information.
823     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
824     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
825     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
826     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
827
828     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
829     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
830     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
832
833     if (Subtarget->is64Bit()) {
834       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
835       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
836     }
837   }
838
839   if (Subtarget->hasSSE42()) {
840     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
841   }
842
843   if (!UseSoftFloat && Subtarget->hasAVX()) {
844     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
845     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
846     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
847     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
848
849     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
850     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
851     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
852     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
853     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
854     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
855     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
856     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
857     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
858     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
859     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
860     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
861     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
862     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
863     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
864
865     // Operations to consider commented out -v16i16 v32i8
866     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
867     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
868     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
869     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
870     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
871     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
872     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
873     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
874     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
875     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
876     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
877     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
878     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
879     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
880
881     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
882     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
883     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
884     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
885
886     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
887     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
888     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
891
892     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
894     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
897     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
898
899 #if 0
900     // Not sure we want to do this since there are no 256-bit integer
901     // operations in AVX
902
903     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
904     // This includes 256-bit vectors
905     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
906       EVT VT = (MVT::SimpleValueType)i;
907
908       // Do not attempt to custom lower non-power-of-2 vectors
909       if (!isPowerOf2_32(VT.getVectorNumElements()))
910         continue;
911
912       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
913       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
914       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
915     }
916
917     if (Subtarget->is64Bit()) {
918       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
919       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
920     }
921 #endif
922
923 #if 0
924     // Not sure we want to do this since there are no 256-bit integer
925     // operations in AVX
926
927     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
928     // Including 256-bit vectors
929     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
930       EVT VT = (MVT::SimpleValueType)i;
931
932       if (!VT.is256BitVector()) {
933         continue;
934       }
935       setOperationAction(ISD::AND,    VT, Promote);
936       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
937       setOperationAction(ISD::OR,     VT, Promote);
938       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
939       setOperationAction(ISD::XOR,    VT, Promote);
940       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
941       setOperationAction(ISD::LOAD,   VT, Promote);
942       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
943       setOperationAction(ISD::SELECT, VT, Promote);
944       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
945     }
946
947     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
948 #endif
949   }
950
951   // We want to custom lower some of our intrinsics.
952   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
953
954   // Add/Sub/Mul with overflow operations are custom lowered.
955   setOperationAction(ISD::SADDO, MVT::i32, Custom);
956   setOperationAction(ISD::SADDO, MVT::i64, Custom);
957   setOperationAction(ISD::UADDO, MVT::i32, Custom);
958   setOperationAction(ISD::UADDO, MVT::i64, Custom);
959   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
960   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
961   setOperationAction(ISD::USUBO, MVT::i32, Custom);
962   setOperationAction(ISD::USUBO, MVT::i64, Custom);
963   setOperationAction(ISD::SMULO, MVT::i32, Custom);
964   setOperationAction(ISD::SMULO, MVT::i64, Custom);
965
966   if (!Subtarget->is64Bit()) {
967     // These libcalls are not available in 32-bit.
968     setLibcallName(RTLIB::SHL_I128, 0);
969     setLibcallName(RTLIB::SRL_I128, 0);
970     setLibcallName(RTLIB::SRA_I128, 0);
971   }
972
973   // We have target-specific dag combine patterns for the following nodes:
974   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
975   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
976   setTargetDAGCombine(ISD::BUILD_VECTOR);
977   setTargetDAGCombine(ISD::SELECT);
978   setTargetDAGCombine(ISD::SHL);
979   setTargetDAGCombine(ISD::SRA);
980   setTargetDAGCombine(ISD::SRL);
981   setTargetDAGCombine(ISD::OR);
982   setTargetDAGCombine(ISD::STORE);
983   setTargetDAGCombine(ISD::MEMBARRIER);
984   setTargetDAGCombine(ISD::ZERO_EXTEND);
985   if (Subtarget->is64Bit())
986     setTargetDAGCombine(ISD::MUL);
987
988   computeRegisterProperties();
989
990   // FIXME: These should be based on subtarget info. Plus, the values should
991   // be smaller when we are in optimizing for size mode.
992   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
993   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
994   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
995   setPrefLoopAlignment(16);
996   benefitFromCodePlacementOpt = true;
997 }
998
999
1000 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1001   return MVT::i8;
1002 }
1003
1004
1005 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1006 /// the desired ByVal argument alignment.
1007 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1008   if (MaxAlign == 16)
1009     return;
1010   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1011     if (VTy->getBitWidth() == 128)
1012       MaxAlign = 16;
1013   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1014     unsigned EltAlign = 0;
1015     getMaxByValAlign(ATy->getElementType(), EltAlign);
1016     if (EltAlign > MaxAlign)
1017       MaxAlign = EltAlign;
1018   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1019     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1020       unsigned EltAlign = 0;
1021       getMaxByValAlign(STy->getElementType(i), EltAlign);
1022       if (EltAlign > MaxAlign)
1023         MaxAlign = EltAlign;
1024       if (MaxAlign == 16)
1025         break;
1026     }
1027   }
1028   return;
1029 }
1030
1031 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1032 /// function arguments in the caller parameter area. For X86, aggregates
1033 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1034 /// are at 4-byte boundaries.
1035 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1036   if (Subtarget->is64Bit()) {
1037     // Max of 8 and alignment of type.
1038     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1039     if (TyAlign > 8)
1040       return TyAlign;
1041     return 8;
1042   }
1043
1044   unsigned Align = 4;
1045   if (Subtarget->hasSSE1())
1046     getMaxByValAlign(Ty, Align);
1047   return Align;
1048 }
1049
1050 /// getOptimalMemOpType - Returns the target specific optimal type for load
1051 /// and store operations as a result of memset, memcpy, and memmove
1052 /// lowering. If DstAlign is zero that means it's safe to destination
1053 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1054 /// means there isn't a need to check it against alignment requirement,
1055 /// probably because the source does not need to be loaded. If
1056 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1057 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1058 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1059 /// constant so it does not need to be loaded.
1060 /// It returns EVT::Other if the type should be determined using generic
1061 /// target-independent logic.
1062 EVT
1063 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1064                                        unsigned DstAlign, unsigned SrcAlign,
1065                                        bool NonScalarIntSafe,
1066                                        bool MemcpyStrSrc,
1067                                        MachineFunction &MF) const {
1068   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1069   // linux.  This is because the stack realignment code can't handle certain
1070   // cases like PR2962.  This should be removed when PR2962 is fixed.
1071   const Function *F = MF.getFunction();
1072   if (NonScalarIntSafe &&
1073       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1074     if (Size >= 16 &&
1075         (Subtarget->isUnalignedMemAccessFast() ||
1076          ((DstAlign == 0 || DstAlign >= 16) &&
1077           (SrcAlign == 0 || SrcAlign >= 16))) &&
1078         Subtarget->getStackAlignment() >= 16) {
1079       if (Subtarget->hasSSE2())
1080         return MVT::v4i32;
1081       if (Subtarget->hasSSE1())
1082         return MVT::v4f32;
1083     } else if (!MemcpyStrSrc && Size >= 8 &&
1084                !Subtarget->is64Bit() &&
1085                Subtarget->getStackAlignment() >= 8 &&
1086                Subtarget->hasSSE2()) {
1087       // Do not use f64 to lower memcpy if source is string constant. It's
1088       // better to use i32 to avoid the loads.
1089       return MVT::f64;
1090     }
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 /// getPICBaseSymbol - Return the X86-32 PIC base.
1112 MCSymbol *
1113 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1114                                     MCContext &Ctx) const {
1115   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1116   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1117                                Twine(MF->getFunctionNumber())+"$pb");
1118 }
1119
1120
1121 const MCExpr *
1122 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1123                                              const MachineBasicBlock *MBB,
1124                                              unsigned uid,MCContext &Ctx) const{
1125   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1126          Subtarget->isPICStyleGOT());
1127   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1128   // entries.
1129   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1130                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1131 }
1132
1133 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1134 /// jumptable.
1135 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1136                                                     SelectionDAG &DAG) const {
1137   if (!Subtarget->is64Bit())
1138     // This doesn't have DebugLoc associated with it, but is not really the
1139     // same as a Register.
1140     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1141   return Table;
1142 }
1143
1144 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1145 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1146 /// MCExpr.
1147 const MCExpr *X86TargetLowering::
1148 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1149                              MCContext &Ctx) const {
1150   // X86-64 uses RIP relative addressing based on the jump table label.
1151   if (Subtarget->isPICStyleRIPRel())
1152     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1153
1154   // Otherwise, the reference is relative to the PIC base.
1155   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1156 }
1157
1158 /// getFunctionAlignment - Return the Log2 alignment of this function.
1159 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1160   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1161 }
1162
1163 //===----------------------------------------------------------------------===//
1164 //               Return Value Calling Convention Implementation
1165 //===----------------------------------------------------------------------===//
1166
1167 #include "X86GenCallingConv.inc"
1168
1169 bool 
1170 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1171                         const SmallVectorImpl<EVT> &OutTys,
1172                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1173                         SelectionDAG &DAG) const {
1174   SmallVector<CCValAssign, 16> RVLocs;
1175   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1176                  RVLocs, *DAG.getContext());
1177   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1178 }
1179
1180 SDValue
1181 X86TargetLowering::LowerReturn(SDValue Chain,
1182                                CallingConv::ID CallConv, bool isVarArg,
1183                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1184                                DebugLoc dl, SelectionDAG &DAG) const {
1185   MachineFunction &MF = DAG.getMachineFunction();
1186   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1187
1188   SmallVector<CCValAssign, 16> RVLocs;
1189   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1190                  RVLocs, *DAG.getContext());
1191   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1192
1193   // Add the regs to the liveout set for the function.
1194   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1195   for (unsigned i = 0; i != RVLocs.size(); ++i)
1196     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1197       MRI.addLiveOut(RVLocs[i].getLocReg());
1198
1199   SDValue Flag;
1200
1201   SmallVector<SDValue, 6> RetOps;
1202   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1203   // Operand #1 = Bytes To Pop
1204   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1205                    MVT::i16));
1206
1207   // Copy the result values into the output registers.
1208   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1209     CCValAssign &VA = RVLocs[i];
1210     assert(VA.isRegLoc() && "Can only return in registers!");
1211     SDValue ValToCopy = Outs[i].Val;
1212
1213     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1214     // the RET instruction and handled by the FP Stackifier.
1215     if (VA.getLocReg() == X86::ST0 ||
1216         VA.getLocReg() == X86::ST1) {
1217       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1218       // change the value to the FP stack register class.
1219       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1220         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1221       RetOps.push_back(ValToCopy);
1222       // Don't emit a copytoreg.
1223       continue;
1224     }
1225
1226     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1227     // which is returned in RAX / RDX.
1228     if (Subtarget->is64Bit()) {
1229       EVT ValVT = ValToCopy.getValueType();
1230       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1231         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1232         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1233           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1234       }
1235     }
1236
1237     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1238     Flag = Chain.getValue(1);
1239   }
1240
1241   // The x86-64 ABI for returning structs by value requires that we copy
1242   // the sret argument into %rax for the return. We saved the argument into
1243   // a virtual register in the entry block, so now we copy the value out
1244   // and into %rax.
1245   if (Subtarget->is64Bit() &&
1246       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1247     MachineFunction &MF = DAG.getMachineFunction();
1248     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1249     unsigned Reg = FuncInfo->getSRetReturnReg();
1250     if (!Reg) {
1251       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1252       FuncInfo->setSRetReturnReg(Reg);
1253     }
1254     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1255
1256     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1257     Flag = Chain.getValue(1);
1258
1259     // RAX now acts like a return value.
1260     MRI.addLiveOut(X86::RAX);
1261   }
1262
1263   RetOps[0] = Chain;  // Update chain.
1264
1265   // Add the flag if we have it.
1266   if (Flag.getNode())
1267     RetOps.push_back(Flag);
1268
1269   return DAG.getNode(X86ISD::RET_FLAG, dl,
1270                      MVT::Other, &RetOps[0], RetOps.size());
1271 }
1272
1273 /// LowerCallResult - Lower the result values of a call into the
1274 /// appropriate copies out of appropriate physical registers.
1275 ///
1276 SDValue
1277 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1278                                    CallingConv::ID CallConv, bool isVarArg,
1279                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1280                                    DebugLoc dl, SelectionDAG &DAG,
1281                                    SmallVectorImpl<SDValue> &InVals) const {
1282
1283   // Assign locations to each value returned by this call.
1284   SmallVector<CCValAssign, 16> RVLocs;
1285   bool Is64Bit = Subtarget->is64Bit();
1286   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1287                  RVLocs, *DAG.getContext());
1288   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1289
1290   // Copy all of the result registers out of their specified physreg.
1291   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1292     CCValAssign &VA = RVLocs[i];
1293     EVT CopyVT = VA.getValVT();
1294
1295     // If this is x86-64, and we disabled SSE, we can't return FP values
1296     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1297         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1298       report_fatal_error("SSE register return with SSE disabled");
1299     }
1300
1301     // If this is a call to a function that returns an fp value on the floating
1302     // point stack, but where we prefer to use the value in xmm registers, copy
1303     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1304     if ((VA.getLocReg() == X86::ST0 ||
1305          VA.getLocReg() == X86::ST1) &&
1306         isScalarFPTypeInSSEReg(VA.getValVT())) {
1307       CopyVT = MVT::f80;
1308     }
1309
1310     SDValue Val;
1311     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1312       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1313       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1314         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1315                                    MVT::v2i64, InFlag).getValue(1);
1316         Val = Chain.getValue(0);
1317         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1318                           Val, DAG.getConstant(0, MVT::i64));
1319       } else {
1320         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1321                                    MVT::i64, InFlag).getValue(1);
1322         Val = Chain.getValue(0);
1323       }
1324       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1325     } else {
1326       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1327                                  CopyVT, InFlag).getValue(1);
1328       Val = Chain.getValue(0);
1329     }
1330     InFlag = Chain.getValue(2);
1331
1332     if (CopyVT != VA.getValVT()) {
1333       // Round the F80 the right size, which also moves to the appropriate xmm
1334       // register.
1335       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1336                         // This truncation won't change the value.
1337                         DAG.getIntPtrConstant(1));
1338     }
1339
1340     InVals.push_back(Val);
1341   }
1342
1343   return Chain;
1344 }
1345
1346
1347 //===----------------------------------------------------------------------===//
1348 //                C & StdCall & Fast Calling Convention implementation
1349 //===----------------------------------------------------------------------===//
1350 //  StdCall calling convention seems to be standard for many Windows' API
1351 //  routines and around. It differs from C calling convention just a little:
1352 //  callee should clean up the stack, not caller. Symbols should be also
1353 //  decorated in some fancy way :) It doesn't support any vector arguments.
1354 //  For info on fast calling convention see Fast Calling Convention (tail call)
1355 //  implementation LowerX86_32FastCCCallTo.
1356
1357 /// CallIsStructReturn - Determines whether a call uses struct return
1358 /// semantics.
1359 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1360   if (Outs.empty())
1361     return false;
1362
1363   return Outs[0].Flags.isSRet();
1364 }
1365
1366 /// ArgsAreStructReturn - Determines whether a function uses struct
1367 /// return semantics.
1368 static bool
1369 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1370   if (Ins.empty())
1371     return false;
1372
1373   return Ins[0].Flags.isSRet();
1374 }
1375
1376 /// IsCalleePop - Determines whether the callee is required to pop its
1377 /// own arguments. Callee pop is necessary to support tail calls.
1378 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1379                                     CallingConv::ID CallingConv) const {
1380   if (IsVarArg)
1381     return false;
1382
1383   switch (CallingConv) {
1384   default:
1385     return false;
1386   case CallingConv::X86_StdCall:
1387     return !Subtarget->is64Bit();
1388   case CallingConv::X86_FastCall:
1389     return !Subtarget->is64Bit();
1390   case CallingConv::X86_ThisCall:
1391     return !Subtarget->is64Bit();
1392   case CallingConv::Fast:
1393     return GuaranteedTailCallOpt;
1394   case CallingConv::GHC:
1395     return GuaranteedTailCallOpt;
1396   }
1397 }
1398
1399 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1400 /// given CallingConvention value.
1401 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1402   if (Subtarget->is64Bit()) {
1403     if (CC == CallingConv::GHC)
1404       return CC_X86_64_GHC;
1405     else if (Subtarget->isTargetWin64())
1406       return CC_X86_Win64_C;
1407     else
1408       return CC_X86_64_C;
1409   }
1410
1411   if (CC == CallingConv::X86_FastCall)
1412     return CC_X86_32_FastCall;
1413   else if (CC == CallingConv::X86_ThisCall)
1414     return CC_X86_32_ThisCall;
1415   else if (CC == CallingConv::Fast)
1416     return CC_X86_32_FastCC;
1417   else if (CC == CallingConv::GHC)
1418     return CC_X86_32_GHC;
1419   else
1420     return CC_X86_32_C;
1421 }
1422
1423 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1424 /// by "Src" to address "Dst" with size and alignment information specified by
1425 /// the specific parameter attribute. The copy will be passed as a byval
1426 /// function parameter.
1427 static SDValue
1428 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1429                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1430                           DebugLoc dl) {
1431   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1432   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1433                        /*isVolatile*/false, /*AlwaysInline=*/true,
1434                        NULL, 0, NULL, 0);
1435 }
1436
1437 /// IsTailCallConvention - Return true if the calling convention is one that
1438 /// supports tail call optimization.
1439 static bool IsTailCallConvention(CallingConv::ID CC) {
1440   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1441 }
1442
1443 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1444 /// a tailcall target by changing its ABI.
1445 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1446   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1447 }
1448
1449 SDValue
1450 X86TargetLowering::LowerMemArgument(SDValue Chain,
1451                                     CallingConv::ID CallConv,
1452                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1453                                     DebugLoc dl, SelectionDAG &DAG,
1454                                     const CCValAssign &VA,
1455                                     MachineFrameInfo *MFI,
1456                                     unsigned i) const {
1457   // Create the nodes corresponding to a load from this parameter slot.
1458   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1459   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1460   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1461   EVT ValVT;
1462
1463   // If value is passed by pointer we have address passed instead of the value
1464   // itself.
1465   if (VA.getLocInfo() == CCValAssign::Indirect)
1466     ValVT = VA.getLocVT();
1467   else
1468     ValVT = VA.getValVT();
1469
1470   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1471   // changed with more analysis.
1472   // In case of tail call optimization mark all arguments mutable. Since they
1473   // could be overwritten by lowering of arguments in case of a tail call.
1474   if (Flags.isByVal()) {
1475     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1476                                     VA.getLocMemOffset(), isImmutable, false);
1477     return DAG.getFrameIndex(FI, getPointerTy());
1478   } else {
1479     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1480                                     VA.getLocMemOffset(), isImmutable, false);
1481     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1482     return DAG.getLoad(ValVT, dl, Chain, FIN,
1483                        PseudoSourceValue::getFixedStack(FI), 0,
1484                        false, false, 0);
1485   }
1486 }
1487
1488 SDValue
1489 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1490                                         CallingConv::ID CallConv,
1491                                         bool isVarArg,
1492                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1493                                         DebugLoc dl,
1494                                         SelectionDAG &DAG,
1495                                         SmallVectorImpl<SDValue> &InVals)
1496                                           const {
1497   MachineFunction &MF = DAG.getMachineFunction();
1498   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1499
1500   const Function* Fn = MF.getFunction();
1501   if (Fn->hasExternalLinkage() &&
1502       Subtarget->isTargetCygMing() &&
1503       Fn->getName() == "main")
1504     FuncInfo->setForceFramePointer(true);
1505
1506   MachineFrameInfo *MFI = MF.getFrameInfo();
1507   bool Is64Bit = Subtarget->is64Bit();
1508   bool IsWin64 = Subtarget->isTargetWin64();
1509
1510   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1511          "Var args not supported with calling convention fastcc or ghc");
1512
1513   // Assign locations to all of the incoming arguments.
1514   SmallVector<CCValAssign, 16> ArgLocs;
1515   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1516                  ArgLocs, *DAG.getContext());
1517   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1518
1519   unsigned LastVal = ~0U;
1520   SDValue ArgValue;
1521   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1522     CCValAssign &VA = ArgLocs[i];
1523     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1524     // places.
1525     assert(VA.getValNo() != LastVal &&
1526            "Don't support value assigned to multiple locs yet");
1527     LastVal = VA.getValNo();
1528
1529     if (VA.isRegLoc()) {
1530       EVT RegVT = VA.getLocVT();
1531       TargetRegisterClass *RC = NULL;
1532       if (RegVT == MVT::i32)
1533         RC = X86::GR32RegisterClass;
1534       else if (Is64Bit && RegVT == MVT::i64)
1535         RC = X86::GR64RegisterClass;
1536       else if (RegVT == MVT::f32)
1537         RC = X86::FR32RegisterClass;
1538       else if (RegVT == MVT::f64)
1539         RC = X86::FR64RegisterClass;
1540       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1541         RC = X86::VR128RegisterClass;
1542       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1543         RC = X86::VR64RegisterClass;
1544       else
1545         llvm_unreachable("Unknown argument type!");
1546
1547       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1548       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1549
1550       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1551       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1552       // right size.
1553       if (VA.getLocInfo() == CCValAssign::SExt)
1554         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1555                                DAG.getValueType(VA.getValVT()));
1556       else if (VA.getLocInfo() == CCValAssign::ZExt)
1557         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1558                                DAG.getValueType(VA.getValVT()));
1559       else if (VA.getLocInfo() == CCValAssign::BCvt)
1560         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1561
1562       if (VA.isExtInLoc()) {
1563         // Handle MMX values passed in XMM regs.
1564         if (RegVT.isVector()) {
1565           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1566                                  ArgValue, DAG.getConstant(0, MVT::i64));
1567           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1568         } else
1569           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1570       }
1571     } else {
1572       assert(VA.isMemLoc());
1573       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1574     }
1575
1576     // If value is passed via pointer - do a load.
1577     if (VA.getLocInfo() == CCValAssign::Indirect)
1578       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1579                              false, false, 0);
1580
1581     InVals.push_back(ArgValue);
1582   }
1583
1584   // The x86-64 ABI for returning structs by value requires that we copy
1585   // the sret argument into %rax for the return. Save the argument into
1586   // a virtual register so that we can access it from the return points.
1587   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1588     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1589     unsigned Reg = FuncInfo->getSRetReturnReg();
1590     if (!Reg) {
1591       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1592       FuncInfo->setSRetReturnReg(Reg);
1593     }
1594     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1595     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1596   }
1597
1598   unsigned StackSize = CCInfo.getNextStackOffset();
1599   // Align stack specially for tail calls.
1600   if (FuncIsMadeTailCallSafe(CallConv))
1601     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1602
1603   // If the function takes variable number of arguments, make a frame index for
1604   // the start of the first vararg value... for expansion of llvm.va_start.
1605   if (isVarArg) {
1606     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1607                     CallConv != CallingConv::X86_ThisCall)) {
1608       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1609                                                             true, false));
1610     }
1611     if (Is64Bit) {
1612       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1613
1614       // FIXME: We should really autogenerate these arrays
1615       static const unsigned GPR64ArgRegsWin64[] = {
1616         X86::RCX, X86::RDX, X86::R8,  X86::R9
1617       };
1618       static const unsigned XMMArgRegsWin64[] = {
1619         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1620       };
1621       static const unsigned GPR64ArgRegs64Bit[] = {
1622         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1623       };
1624       static const unsigned XMMArgRegs64Bit[] = {
1625         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1626         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1627       };
1628       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1629
1630       if (IsWin64) {
1631         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1632         GPR64ArgRegs = GPR64ArgRegsWin64;
1633         XMMArgRegs = XMMArgRegsWin64;
1634       } else {
1635         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1636         GPR64ArgRegs = GPR64ArgRegs64Bit;
1637         XMMArgRegs = XMMArgRegs64Bit;
1638       }
1639       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1640                                                        TotalNumIntRegs);
1641       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1642                                                        TotalNumXMMRegs);
1643
1644       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1645       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1646              "SSE register cannot be used when SSE is disabled!");
1647       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1648              "SSE register cannot be used when SSE is disabled!");
1649       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1650         // Kernel mode asks for SSE to be disabled, so don't push them
1651         // on the stack.
1652         TotalNumXMMRegs = 0;
1653
1654       // For X86-64, if there are vararg parameters that are passed via
1655       // registers, then we must store them to their spots on the stack so they
1656       // may be loaded by deferencing the result of va_next.
1657       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1658       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1659       FuncInfo->setRegSaveFrameIndex(
1660         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1661                                false));
1662
1663       // Store the integer parameter registers.
1664       SmallVector<SDValue, 8> MemOps;
1665       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1666                                         getPointerTy());
1667       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1668       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1669         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1670                                   DAG.getIntPtrConstant(Offset));
1671         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1672                                      X86::GR64RegisterClass);
1673         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1674         SDValue Store =
1675           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1676                        PseudoSourceValue::getFixedStack(
1677                          FuncInfo->getRegSaveFrameIndex()),
1678                        Offset, false, false, 0);
1679         MemOps.push_back(Store);
1680         Offset += 8;
1681       }
1682
1683       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1684         // Now store the XMM (fp + vector) parameter registers.
1685         SmallVector<SDValue, 11> SaveXMMOps;
1686         SaveXMMOps.push_back(Chain);
1687
1688         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1689         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1690         SaveXMMOps.push_back(ALVal);
1691
1692         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1693                                FuncInfo->getRegSaveFrameIndex()));
1694         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1695                                FuncInfo->getVarArgsFPOffset()));
1696
1697         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1698           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1699                                        X86::VR128RegisterClass);
1700           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1701           SaveXMMOps.push_back(Val);
1702         }
1703         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1704                                      MVT::Other,
1705                                      &SaveXMMOps[0], SaveXMMOps.size()));
1706       }
1707
1708       if (!MemOps.empty())
1709         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1710                             &MemOps[0], MemOps.size());
1711     }
1712   }
1713
1714   // Some CCs need callee pop.
1715   if (IsCalleePop(isVarArg, CallConv)) {
1716     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1717   } else {
1718     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1719     // If this is an sret function, the return should pop the hidden pointer.
1720     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1721       FuncInfo->setBytesToPopOnReturn(4);
1722   }
1723
1724   if (!Is64Bit) {
1725     // RegSaveFrameIndex is X86-64 only.
1726     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1727     if (CallConv == CallingConv::X86_FastCall ||
1728         CallConv == CallingConv::X86_ThisCall)
1729       // fastcc functions can't have varargs.
1730       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1731   }
1732
1733   return Chain;
1734 }
1735
1736 SDValue
1737 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1738                                     SDValue StackPtr, SDValue Arg,
1739                                     DebugLoc dl, SelectionDAG &DAG,
1740                                     const CCValAssign &VA,
1741                                     ISD::ArgFlagsTy Flags) const {
1742   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1743   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1744   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1745   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1746   if (Flags.isByVal()) {
1747     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1748   }
1749   return DAG.getStore(Chain, dl, Arg, PtrOff,
1750                       PseudoSourceValue::getStack(), LocMemOffset,
1751                       false, false, 0);
1752 }
1753
1754 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1755 /// optimization is performed and it is required.
1756 SDValue
1757 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1758                                            SDValue &OutRetAddr, SDValue Chain,
1759                                            bool IsTailCall, bool Is64Bit,
1760                                            int FPDiff, DebugLoc dl) const {
1761   // Adjust the Return address stack slot.
1762   EVT VT = getPointerTy();
1763   OutRetAddr = getReturnAddressFrameIndex(DAG);
1764
1765   // Load the "old" Return address.
1766   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1767   return SDValue(OutRetAddr.getNode(), 1);
1768 }
1769
1770 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1771 /// optimization is performed and it is required (FPDiff!=0).
1772 static SDValue
1773 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1774                          SDValue Chain, SDValue RetAddrFrIdx,
1775                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1776   // Store the return address to the appropriate stack slot.
1777   if (!FPDiff) return Chain;
1778   // Calculate the new stack slot for the return address.
1779   int SlotSize = Is64Bit ? 8 : 4;
1780   int NewReturnAddrFI =
1781     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1782   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1783   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1784   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1785                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1786                        false, false, 0);
1787   return Chain;
1788 }
1789
1790 SDValue
1791 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1792                              CallingConv::ID CallConv, bool isVarArg,
1793                              bool &isTailCall,
1794                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1795                              const SmallVectorImpl<ISD::InputArg> &Ins,
1796                              DebugLoc dl, SelectionDAG &DAG,
1797                              SmallVectorImpl<SDValue> &InVals) const {
1798   MachineFunction &MF = DAG.getMachineFunction();
1799   bool Is64Bit        = Subtarget->is64Bit();
1800   bool IsStructRet    = CallIsStructReturn(Outs);
1801   bool IsSibcall      = false;
1802
1803   if (isTailCall) {
1804     // Check if it's really possible to do a tail call.
1805     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1806                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1807                                                    Outs, Ins, DAG);
1808
1809     // Sibcalls are automatically detected tailcalls which do not require
1810     // ABI changes.
1811     if (!GuaranteedTailCallOpt && isTailCall)
1812       IsSibcall = true;
1813
1814     if (isTailCall)
1815       ++NumTailCalls;
1816   }
1817
1818   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1819          "Var args not supported with calling convention fastcc or ghc");
1820
1821   // Analyze operands of the call, assigning locations to each operand.
1822   SmallVector<CCValAssign, 16> ArgLocs;
1823   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1824                  ArgLocs, *DAG.getContext());
1825   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1826
1827   // Get a count of how many bytes are to be pushed on the stack.
1828   unsigned NumBytes = CCInfo.getNextStackOffset();
1829   if (IsSibcall)
1830     // This is a sibcall. The memory operands are available in caller's
1831     // own caller's stack.
1832     NumBytes = 0;
1833   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1834     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1835
1836   int FPDiff = 0;
1837   if (isTailCall && !IsSibcall) {
1838     // Lower arguments at fp - stackoffset + fpdiff.
1839     unsigned NumBytesCallerPushed =
1840       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1841     FPDiff = NumBytesCallerPushed - NumBytes;
1842
1843     // Set the delta of movement of the returnaddr stackslot.
1844     // But only set if delta is greater than previous delta.
1845     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1846       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1847   }
1848
1849   if (!IsSibcall)
1850     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1851
1852   SDValue RetAddrFrIdx;
1853   // Load return adress for tail calls.
1854   if (isTailCall && FPDiff)
1855     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1856                                     Is64Bit, FPDiff, dl);
1857
1858   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1859   SmallVector<SDValue, 8> MemOpChains;
1860   SDValue StackPtr;
1861
1862   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1863   // of tail call optimization arguments are handle later.
1864   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865     CCValAssign &VA = ArgLocs[i];
1866     EVT RegVT = VA.getLocVT();
1867     SDValue Arg = Outs[i].Val;
1868     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1869     bool isByVal = Flags.isByVal();
1870
1871     // Promote the value if needed.
1872     switch (VA.getLocInfo()) {
1873     default: llvm_unreachable("Unknown loc info!");
1874     case CCValAssign::Full: break;
1875     case CCValAssign::SExt:
1876       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1877       break;
1878     case CCValAssign::ZExt:
1879       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1880       break;
1881     case CCValAssign::AExt:
1882       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1883         // Special case: passing MMX values in XMM registers.
1884         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1885         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1886         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1887       } else
1888         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1889       break;
1890     case CCValAssign::BCvt:
1891       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1892       break;
1893     case CCValAssign::Indirect: {
1894       // Store the argument.
1895       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1896       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1897       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1898                            PseudoSourceValue::getFixedStack(FI), 0,
1899                            false, false, 0);
1900       Arg = SpillSlot;
1901       break;
1902     }
1903     }
1904
1905     if (VA.isRegLoc()) {
1906       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1907     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1908       assert(VA.isMemLoc());
1909       if (StackPtr.getNode() == 0)
1910         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1911       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1912                                              dl, DAG, VA, Flags));
1913     }
1914   }
1915
1916   if (!MemOpChains.empty())
1917     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1918                         &MemOpChains[0], MemOpChains.size());
1919
1920   // Build a sequence of copy-to-reg nodes chained together with token chain
1921   // and flag operands which copy the outgoing args into registers.
1922   SDValue InFlag;
1923   // Tail call byval lowering might overwrite argument registers so in case of
1924   // tail call optimization the copies to registers are lowered later.
1925   if (!isTailCall)
1926     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1927       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1928                                RegsToPass[i].second, InFlag);
1929       InFlag = Chain.getValue(1);
1930     }
1931
1932   if (Subtarget->isPICStyleGOT()) {
1933     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1934     // GOT pointer.
1935     if (!isTailCall) {
1936       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1937                                DAG.getNode(X86ISD::GlobalBaseReg,
1938                                            DebugLoc(), getPointerTy()),
1939                                InFlag);
1940       InFlag = Chain.getValue(1);
1941     } else {
1942       // If we are tail calling and generating PIC/GOT style code load the
1943       // address of the callee into ECX. The value in ecx is used as target of
1944       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1945       // for tail calls on PIC/GOT architectures. Normally we would just put the
1946       // address of GOT into ebx and then call target@PLT. But for tail calls
1947       // ebx would be restored (since ebx is callee saved) before jumping to the
1948       // target@PLT.
1949
1950       // Note: The actual moving to ECX is done further down.
1951       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1952       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1953           !G->getGlobal()->hasProtectedVisibility())
1954         Callee = LowerGlobalAddress(Callee, DAG);
1955       else if (isa<ExternalSymbolSDNode>(Callee))
1956         Callee = LowerExternalSymbol(Callee, DAG);
1957     }
1958   }
1959
1960   if (Is64Bit && isVarArg) {
1961     // From AMD64 ABI document:
1962     // For calls that may call functions that use varargs or stdargs
1963     // (prototype-less calls or calls to functions containing ellipsis (...) in
1964     // the declaration) %al is used as hidden argument to specify the number
1965     // of SSE registers used. The contents of %al do not need to match exactly
1966     // the number of registers, but must be an ubound on the number of SSE
1967     // registers used and is in the range 0 - 8 inclusive.
1968
1969     // FIXME: Verify this on Win64
1970     // Count the number of XMM registers allocated.
1971     static const unsigned XMMArgRegs[] = {
1972       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1973       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1974     };
1975     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1976     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1977            && "SSE registers cannot be used when SSE is disabled");
1978
1979     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1980                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1981     InFlag = Chain.getValue(1);
1982   }
1983
1984
1985   // For tail calls lower the arguments to the 'real' stack slot.
1986   if (isTailCall) {
1987     // Force all the incoming stack arguments to be loaded from the stack
1988     // before any new outgoing arguments are stored to the stack, because the
1989     // outgoing stack slots may alias the incoming argument stack slots, and
1990     // the alias isn't otherwise explicit. This is slightly more conservative
1991     // than necessary, because it means that each store effectively depends
1992     // on every argument instead of just those arguments it would clobber.
1993     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1994
1995     SmallVector<SDValue, 8> MemOpChains2;
1996     SDValue FIN;
1997     int FI = 0;
1998     // Do not flag preceeding copytoreg stuff together with the following stuff.
1999     InFlag = SDValue();
2000     if (GuaranteedTailCallOpt) {
2001       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2002         CCValAssign &VA = ArgLocs[i];
2003         if (VA.isRegLoc())
2004           continue;
2005         assert(VA.isMemLoc());
2006         SDValue Arg = Outs[i].Val;
2007         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2008         // Create frame index.
2009         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2010         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2011         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2012         FIN = DAG.getFrameIndex(FI, getPointerTy());
2013
2014         if (Flags.isByVal()) {
2015           // Copy relative to framepointer.
2016           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2017           if (StackPtr.getNode() == 0)
2018             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2019                                           getPointerTy());
2020           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2021
2022           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2023                                                            ArgChain,
2024                                                            Flags, DAG, dl));
2025         } else {
2026           // Store relative to framepointer.
2027           MemOpChains2.push_back(
2028             DAG.getStore(ArgChain, dl, Arg, FIN,
2029                          PseudoSourceValue::getFixedStack(FI), 0,
2030                          false, false, 0));
2031         }
2032       }
2033     }
2034
2035     if (!MemOpChains2.empty())
2036       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2037                           &MemOpChains2[0], MemOpChains2.size());
2038
2039     // Copy arguments to their registers.
2040     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2041       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2042                                RegsToPass[i].second, InFlag);
2043       InFlag = Chain.getValue(1);
2044     }
2045     InFlag =SDValue();
2046
2047     // Store the return address to the appropriate stack slot.
2048     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2049                                      FPDiff, dl);
2050   }
2051
2052   bool WasGlobalOrExternal = false;
2053   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2054     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2055     // In the 64-bit large code model, we have to make all calls
2056     // through a register, since the call instruction's 32-bit
2057     // pc-relative offset may not be large enough to hold the whole
2058     // address.
2059   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2060     WasGlobalOrExternal = true;
2061     // If the callee is a GlobalAddress node (quite common, every direct call
2062     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2063     // it.
2064
2065     // We should use extra load for direct calls to dllimported functions in
2066     // non-JIT mode.
2067     const GlobalValue *GV = G->getGlobal();
2068     if (!GV->hasDLLImportLinkage()) {
2069       unsigned char OpFlags = 0;
2070
2071       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2072       // external symbols most go through the PLT in PIC mode.  If the symbol
2073       // has hidden or protected visibility, or if it is static or local, then
2074       // we don't need to use the PLT - we can directly call it.
2075       if (Subtarget->isTargetELF() &&
2076           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2077           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2078         OpFlags = X86II::MO_PLT;
2079       } else if (Subtarget->isPICStyleStubAny() &&
2080                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2081                Subtarget->getDarwinVers() < 9) {
2082         // PC-relative references to external symbols should go through $stub,
2083         // unless we're building with the leopard linker or later, which
2084         // automatically synthesizes these stubs.
2085         OpFlags = X86II::MO_DARWIN_STUB;
2086       }
2087
2088       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2089                                           G->getOffset(), OpFlags);
2090     }
2091   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2092     WasGlobalOrExternal = true;
2093     unsigned char OpFlags = 0;
2094
2095     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2096     // symbols should go through the PLT.
2097     if (Subtarget->isTargetELF() &&
2098         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2099       OpFlags = X86II::MO_PLT;
2100     } else if (Subtarget->isPICStyleStubAny() &&
2101              Subtarget->getDarwinVers() < 9) {
2102       // PC-relative references to external symbols should go through $stub,
2103       // unless we're building with the leopard linker or later, which
2104       // automatically synthesizes these stubs.
2105       OpFlags = X86II::MO_DARWIN_STUB;
2106     }
2107
2108     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2109                                          OpFlags);
2110   }
2111
2112   // Returns a chain & a flag for retval copy to use.
2113   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2114   SmallVector<SDValue, 8> Ops;
2115
2116   if (!IsSibcall && isTailCall) {
2117     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2118                            DAG.getIntPtrConstant(0, true), InFlag);
2119     InFlag = Chain.getValue(1);
2120   }
2121
2122   Ops.push_back(Chain);
2123   Ops.push_back(Callee);
2124
2125   if (isTailCall)
2126     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2127
2128   // Add argument registers to the end of the list so that they are known live
2129   // into the call.
2130   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2131     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2132                                   RegsToPass[i].second.getValueType()));
2133
2134   // Add an implicit use GOT pointer in EBX.
2135   if (!isTailCall && Subtarget->isPICStyleGOT())
2136     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2137
2138   // Add an implicit use of AL for x86 vararg functions.
2139   if (Is64Bit && isVarArg)
2140     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2141
2142   if (InFlag.getNode())
2143     Ops.push_back(InFlag);
2144
2145   if (isTailCall) {
2146     // If this is the first return lowered for this function, add the regs
2147     // to the liveout set for the function.
2148     if (MF.getRegInfo().liveout_empty()) {
2149       SmallVector<CCValAssign, 16> RVLocs;
2150       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2151                      *DAG.getContext());
2152       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2153       for (unsigned i = 0; i != RVLocs.size(); ++i)
2154         if (RVLocs[i].isRegLoc())
2155           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2156     }
2157     return DAG.getNode(X86ISD::TC_RETURN, dl,
2158                        NodeTys, &Ops[0], Ops.size());
2159   }
2160
2161   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2162   InFlag = Chain.getValue(1);
2163
2164   // Create the CALLSEQ_END node.
2165   unsigned NumBytesForCalleeToPush;
2166   if (IsCalleePop(isVarArg, CallConv))
2167     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2168   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2169     // If this is a call to a struct-return function, the callee
2170     // pops the hidden struct pointer, so we have to push it back.
2171     // This is common for Darwin/X86, Linux & Mingw32 targets.
2172     NumBytesForCalleeToPush = 4;
2173   else
2174     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2175
2176   // Returns a flag for retval copy to use.
2177   if (!IsSibcall) {
2178     Chain = DAG.getCALLSEQ_END(Chain,
2179                                DAG.getIntPtrConstant(NumBytes, true),
2180                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2181                                                      true),
2182                                InFlag);
2183     InFlag = Chain.getValue(1);
2184   }
2185
2186   // Handle result values, copying them out of physregs into vregs that we
2187   // return.
2188   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2189                          Ins, dl, DAG, InVals);
2190 }
2191
2192
2193 //===----------------------------------------------------------------------===//
2194 //                Fast Calling Convention (tail call) implementation
2195 //===----------------------------------------------------------------------===//
2196
2197 //  Like std call, callee cleans arguments, convention except that ECX is
2198 //  reserved for storing the tail called function address. Only 2 registers are
2199 //  free for argument passing (inreg). Tail call optimization is performed
2200 //  provided:
2201 //                * tailcallopt is enabled
2202 //                * caller/callee are fastcc
2203 //  On X86_64 architecture with GOT-style position independent code only local
2204 //  (within module) calls are supported at the moment.
2205 //  To keep the stack aligned according to platform abi the function
2206 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2207 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2208 //  If a tail called function callee has more arguments than the caller the
2209 //  caller needs to make sure that there is room to move the RETADDR to. This is
2210 //  achieved by reserving an area the size of the argument delta right after the
2211 //  original REtADDR, but before the saved framepointer or the spilled registers
2212 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2213 //  stack layout:
2214 //    arg1
2215 //    arg2
2216 //    RETADDR
2217 //    [ new RETADDR
2218 //      move area ]
2219 //    (possible EBP)
2220 //    ESI
2221 //    EDI
2222 //    local1 ..
2223
2224 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2225 /// for a 16 byte align requirement.
2226 unsigned
2227 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2228                                                SelectionDAG& DAG) const {
2229   MachineFunction &MF = DAG.getMachineFunction();
2230   const TargetMachine &TM = MF.getTarget();
2231   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2232   unsigned StackAlignment = TFI.getStackAlignment();
2233   uint64_t AlignMask = StackAlignment - 1;
2234   int64_t Offset = StackSize;
2235   uint64_t SlotSize = TD->getPointerSize();
2236   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2237     // Number smaller than 12 so just add the difference.
2238     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2239   } else {
2240     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2241     Offset = ((~AlignMask) & Offset) + StackAlignment +
2242       (StackAlignment-SlotSize);
2243   }
2244   return Offset;
2245 }
2246
2247 /// MatchingStackOffset - Return true if the given stack call argument is
2248 /// already available in the same position (relatively) of the caller's
2249 /// incoming argument stack.
2250 static
2251 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2252                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2253                          const X86InstrInfo *TII) {
2254   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2255   int FI = INT_MAX;
2256   if (Arg.getOpcode() == ISD::CopyFromReg) {
2257     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2258     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2259       return false;
2260     MachineInstr *Def = MRI->getVRegDef(VR);
2261     if (!Def)
2262       return false;
2263     if (!Flags.isByVal()) {
2264       if (!TII->isLoadFromStackSlot(Def, FI))
2265         return false;
2266     } else {
2267       unsigned Opcode = Def->getOpcode();
2268       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2269           Def->getOperand(1).isFI()) {
2270         FI = Def->getOperand(1).getIndex();
2271         Bytes = Flags.getByValSize();
2272       } else
2273         return false;
2274     }
2275   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2276     if (Flags.isByVal())
2277       // ByVal argument is passed in as a pointer but it's now being
2278       // dereferenced. e.g.
2279       // define @foo(%struct.X* %A) {
2280       //   tail call @bar(%struct.X* byval %A)
2281       // }
2282       return false;
2283     SDValue Ptr = Ld->getBasePtr();
2284     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2285     if (!FINode)
2286       return false;
2287     FI = FINode->getIndex();
2288   } else
2289     return false;
2290
2291   assert(FI != INT_MAX);
2292   if (!MFI->isFixedObjectIndex(FI))
2293     return false;
2294   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2295 }
2296
2297 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2298 /// for tail call optimization. Targets which want to do tail call
2299 /// optimization should implement this function.
2300 bool
2301 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2302                                                      CallingConv::ID CalleeCC,
2303                                                      bool isVarArg,
2304                                                      bool isCalleeStructRet,
2305                                                      bool isCallerStructRet,
2306                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2307                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2308                                                      SelectionDAG& DAG) const {
2309   if (!IsTailCallConvention(CalleeCC) &&
2310       CalleeCC != CallingConv::C)
2311     return false;
2312
2313   // If -tailcallopt is specified, make fastcc functions tail-callable.
2314   const MachineFunction &MF = DAG.getMachineFunction();
2315   const Function *CallerF = DAG.getMachineFunction().getFunction();
2316   CallingConv::ID CallerCC = CallerF->getCallingConv();
2317   bool CCMatch = CallerCC == CalleeCC;
2318
2319   if (GuaranteedTailCallOpt) {
2320     if (IsTailCallConvention(CalleeCC) && CCMatch)
2321       return true;
2322     return false;
2323   }
2324
2325   // Look for obvious safe cases to perform tail call optimization that does not
2326   // requite ABI changes. This is what gcc calls sibcall.
2327
2328   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2329   // emit a special epilogue.
2330   if (RegInfo->needsStackRealignment(MF))
2331     return false;
2332
2333   // Do not sibcall optimize vararg calls unless the call site is not passing any
2334   // arguments.
2335   if (isVarArg && !Outs.empty())
2336     return false;
2337
2338   // Also avoid sibcall optimization if either caller or callee uses struct
2339   // return semantics.
2340   if (isCalleeStructRet || isCallerStructRet)
2341     return false;
2342
2343   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2344   // Therefore if it's not used by the call it is not safe to optimize this into
2345   // a sibcall.
2346   bool Unused = false;
2347   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2348     if (!Ins[i].Used) {
2349       Unused = true;
2350       break;
2351     }
2352   }
2353   if (Unused) {
2354     SmallVector<CCValAssign, 16> RVLocs;
2355     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2356                    RVLocs, *DAG.getContext());
2357     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2358     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2359       CCValAssign &VA = RVLocs[i];
2360       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2361         return false;
2362     }
2363   }
2364
2365   // If the calling conventions do not match, then we'd better make sure the
2366   // results are returned in the same way as what the caller expects.
2367   if (!CCMatch) {
2368     SmallVector<CCValAssign, 16> RVLocs1;
2369     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2370                     RVLocs1, *DAG.getContext());
2371     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2372
2373     SmallVector<CCValAssign, 16> RVLocs2;
2374     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2375                     RVLocs2, *DAG.getContext());
2376     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2377
2378     if (RVLocs1.size() != RVLocs2.size())
2379       return false;
2380     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2381       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2382         return false;
2383       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2384         return false;
2385       if (RVLocs1[i].isRegLoc()) {
2386         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2387           return false;
2388       } else {
2389         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2390           return false;
2391       }
2392     }
2393   }
2394
2395   // If the callee takes no arguments then go on to check the results of the
2396   // call.
2397   if (!Outs.empty()) {
2398     // Check if stack adjustment is needed. For now, do not do this if any
2399     // argument is passed on the stack.
2400     SmallVector<CCValAssign, 16> ArgLocs;
2401     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2402                    ArgLocs, *DAG.getContext());
2403     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2404     if (CCInfo.getNextStackOffset()) {
2405       MachineFunction &MF = DAG.getMachineFunction();
2406       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2407         return false;
2408       if (Subtarget->isTargetWin64())
2409         // Win64 ABI has additional complications.
2410         return false;
2411
2412       // Check if the arguments are already laid out in the right way as
2413       // the caller's fixed stack objects.
2414       MachineFrameInfo *MFI = MF.getFrameInfo();
2415       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2416       const X86InstrInfo *TII =
2417         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2418       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2419         CCValAssign &VA = ArgLocs[i];
2420         EVT RegVT = VA.getLocVT();
2421         SDValue Arg = Outs[i].Val;
2422         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2423         if (VA.getLocInfo() == CCValAssign::Indirect)
2424           return false;
2425         if (!VA.isRegLoc()) {
2426           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2427                                    MFI, MRI, TII))
2428             return false;
2429         }
2430       }
2431     }
2432   }
2433
2434   return true;
2435 }
2436
2437 FastISel *
2438 X86TargetLowering::createFastISel(MachineFunction &mf,
2439                             DenseMap<const Value *, unsigned> &vm,
2440                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2441                             DenseMap<const AllocaInst *, int> &am,
2442                             std::vector<std::pair<MachineInstr*, unsigned> > &pn
2443 #ifndef NDEBUG
2444                           , SmallSet<const Instruction *, 8> &cil
2445 #endif
2446                                   ) const {
2447   return X86::createFastISel(mf, vm, bm, am, pn
2448 #ifndef NDEBUG
2449                              , cil
2450 #endif
2451                              );
2452 }
2453
2454
2455 //===----------------------------------------------------------------------===//
2456 //                           Other Lowering Hooks
2457 //===----------------------------------------------------------------------===//
2458
2459
2460 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2461   MachineFunction &MF = DAG.getMachineFunction();
2462   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2463   int ReturnAddrIndex = FuncInfo->getRAIndex();
2464
2465   if (ReturnAddrIndex == 0) {
2466     // Set up a frame object for the return address.
2467     uint64_t SlotSize = TD->getPointerSize();
2468     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2469                                                            false, false);
2470     FuncInfo->setRAIndex(ReturnAddrIndex);
2471   }
2472
2473   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2474 }
2475
2476
2477 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2478                                        bool hasSymbolicDisplacement) {
2479   // Offset should fit into 32 bit immediate field.
2480   if (!isInt<32>(Offset))
2481     return false;
2482
2483   // If we don't have a symbolic displacement - we don't have any extra
2484   // restrictions.
2485   if (!hasSymbolicDisplacement)
2486     return true;
2487
2488   // FIXME: Some tweaks might be needed for medium code model.
2489   if (M != CodeModel::Small && M != CodeModel::Kernel)
2490     return false;
2491
2492   // For small code model we assume that latest object is 16MB before end of 31
2493   // bits boundary. We may also accept pretty large negative constants knowing
2494   // that all objects are in the positive half of address space.
2495   if (M == CodeModel::Small && Offset < 16*1024*1024)
2496     return true;
2497
2498   // For kernel code model we know that all object resist in the negative half
2499   // of 32bits address space. We may not accept negative offsets, since they may
2500   // be just off and we may accept pretty large positive ones.
2501   if (M == CodeModel::Kernel && Offset > 0)
2502     return true;
2503
2504   return false;
2505 }
2506
2507 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2508 /// specific condition code, returning the condition code and the LHS/RHS of the
2509 /// comparison to make.
2510 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2511                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2512   if (!isFP) {
2513     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2514       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2515         // X > -1   -> X == 0, jump !sign.
2516         RHS = DAG.getConstant(0, RHS.getValueType());
2517         return X86::COND_NS;
2518       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2519         // X < 0   -> X == 0, jump on sign.
2520         return X86::COND_S;
2521       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2522         // X < 1   -> X <= 0
2523         RHS = DAG.getConstant(0, RHS.getValueType());
2524         return X86::COND_LE;
2525       }
2526     }
2527
2528     switch (SetCCOpcode) {
2529     default: llvm_unreachable("Invalid integer condition!");
2530     case ISD::SETEQ:  return X86::COND_E;
2531     case ISD::SETGT:  return X86::COND_G;
2532     case ISD::SETGE:  return X86::COND_GE;
2533     case ISD::SETLT:  return X86::COND_L;
2534     case ISD::SETLE:  return X86::COND_LE;
2535     case ISD::SETNE:  return X86::COND_NE;
2536     case ISD::SETULT: return X86::COND_B;
2537     case ISD::SETUGT: return X86::COND_A;
2538     case ISD::SETULE: return X86::COND_BE;
2539     case ISD::SETUGE: return X86::COND_AE;
2540     }
2541   }
2542
2543   // First determine if it is required or is profitable to flip the operands.
2544
2545   // If LHS is a foldable load, but RHS is not, flip the condition.
2546   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2547       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2548     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2549     std::swap(LHS, RHS);
2550   }
2551
2552   switch (SetCCOpcode) {
2553   default: break;
2554   case ISD::SETOLT:
2555   case ISD::SETOLE:
2556   case ISD::SETUGT:
2557   case ISD::SETUGE:
2558     std::swap(LHS, RHS);
2559     break;
2560   }
2561
2562   // On a floating point condition, the flags are set as follows:
2563   // ZF  PF  CF   op
2564   //  0 | 0 | 0 | X > Y
2565   //  0 | 0 | 1 | X < Y
2566   //  1 | 0 | 0 | X == Y
2567   //  1 | 1 | 1 | unordered
2568   switch (SetCCOpcode) {
2569   default: llvm_unreachable("Condcode should be pre-legalized away");
2570   case ISD::SETUEQ:
2571   case ISD::SETEQ:   return X86::COND_E;
2572   case ISD::SETOLT:              // flipped
2573   case ISD::SETOGT:
2574   case ISD::SETGT:   return X86::COND_A;
2575   case ISD::SETOLE:              // flipped
2576   case ISD::SETOGE:
2577   case ISD::SETGE:   return X86::COND_AE;
2578   case ISD::SETUGT:              // flipped
2579   case ISD::SETULT:
2580   case ISD::SETLT:   return X86::COND_B;
2581   case ISD::SETUGE:              // flipped
2582   case ISD::SETULE:
2583   case ISD::SETLE:   return X86::COND_BE;
2584   case ISD::SETONE:
2585   case ISD::SETNE:   return X86::COND_NE;
2586   case ISD::SETUO:   return X86::COND_P;
2587   case ISD::SETO:    return X86::COND_NP;
2588   case ISD::SETOEQ:
2589   case ISD::SETUNE:  return X86::COND_INVALID;
2590   }
2591 }
2592
2593 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2594 /// code. Current x86 isa includes the following FP cmov instructions:
2595 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2596 static bool hasFPCMov(unsigned X86CC) {
2597   switch (X86CC) {
2598   default:
2599     return false;
2600   case X86::COND_B:
2601   case X86::COND_BE:
2602   case X86::COND_E:
2603   case X86::COND_P:
2604   case X86::COND_A:
2605   case X86::COND_AE:
2606   case X86::COND_NE:
2607   case X86::COND_NP:
2608     return true;
2609   }
2610 }
2611
2612 /// isFPImmLegal - Returns true if the target can instruction select the
2613 /// specified FP immediate natively. If false, the legalizer will
2614 /// materialize the FP immediate as a load from a constant pool.
2615 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2616   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2617     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2618       return true;
2619   }
2620   return false;
2621 }
2622
2623 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2624 /// the specified range (L, H].
2625 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2626   return (Val < 0) || (Val >= Low && Val < Hi);
2627 }
2628
2629 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2630 /// specified value.
2631 static bool isUndefOrEqual(int Val, int CmpVal) {
2632   if (Val < 0 || Val == CmpVal)
2633     return true;
2634   return false;
2635 }
2636
2637 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2638 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2639 /// the second operand.
2640 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2641   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2642     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2643   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2644     return (Mask[0] < 2 && Mask[1] < 2);
2645   return false;
2646 }
2647
2648 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2649   SmallVector<int, 8> M;
2650   N->getMask(M);
2651   return ::isPSHUFDMask(M, N->getValueType(0));
2652 }
2653
2654 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2655 /// is suitable for input to PSHUFHW.
2656 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2657   if (VT != MVT::v8i16)
2658     return false;
2659
2660   // Lower quadword copied in order or undef.
2661   for (int i = 0; i != 4; ++i)
2662     if (Mask[i] >= 0 && Mask[i] != i)
2663       return false;
2664
2665   // Upper quadword shuffled.
2666   for (int i = 4; i != 8; ++i)
2667     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2668       return false;
2669
2670   return true;
2671 }
2672
2673 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2674   SmallVector<int, 8> M;
2675   N->getMask(M);
2676   return ::isPSHUFHWMask(M, N->getValueType(0));
2677 }
2678
2679 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2680 /// is suitable for input to PSHUFLW.
2681 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2682   if (VT != MVT::v8i16)
2683     return false;
2684
2685   // Upper quadword copied in order.
2686   for (int i = 4; i != 8; ++i)
2687     if (Mask[i] >= 0 && Mask[i] != i)
2688       return false;
2689
2690   // Lower quadword shuffled.
2691   for (int i = 0; i != 4; ++i)
2692     if (Mask[i] >= 4)
2693       return false;
2694
2695   return true;
2696 }
2697
2698 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2699   SmallVector<int, 8> M;
2700   N->getMask(M);
2701   return ::isPSHUFLWMask(M, N->getValueType(0));
2702 }
2703
2704 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2705 /// is suitable for input to PALIGNR.
2706 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2707                           bool hasSSSE3) {
2708   int i, e = VT.getVectorNumElements();
2709   
2710   // Do not handle v2i64 / v2f64 shuffles with palignr.
2711   if (e < 4 || !hasSSSE3)
2712     return false;
2713   
2714   for (i = 0; i != e; ++i)
2715     if (Mask[i] >= 0)
2716       break;
2717   
2718   // All undef, not a palignr.
2719   if (i == e)
2720     return false;
2721
2722   // Determine if it's ok to perform a palignr with only the LHS, since we
2723   // don't have access to the actual shuffle elements to see if RHS is undef.
2724   bool Unary = Mask[i] < (int)e;
2725   bool NeedsUnary = false;
2726
2727   int s = Mask[i] - i;
2728   
2729   // Check the rest of the elements to see if they are consecutive.
2730   for (++i; i != e; ++i) {
2731     int m = Mask[i];
2732     if (m < 0) 
2733       continue;
2734     
2735     Unary = Unary && (m < (int)e);
2736     NeedsUnary = NeedsUnary || (m < s);
2737
2738     if (NeedsUnary && !Unary)
2739       return false;
2740     if (Unary && m != ((s+i) & (e-1)))
2741       return false;
2742     if (!Unary && m != (s+i))
2743       return false;
2744   }
2745   return true;
2746 }
2747
2748 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2749   SmallVector<int, 8> M;
2750   N->getMask(M);
2751   return ::isPALIGNRMask(M, N->getValueType(0), true);
2752 }
2753
2754 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2755 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2756 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2757   int NumElems = VT.getVectorNumElements();
2758   if (NumElems != 2 && NumElems != 4)
2759     return false;
2760
2761   int Half = NumElems / 2;
2762   for (int i = 0; i < Half; ++i)
2763     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2764       return false;
2765   for (int i = Half; i < NumElems; ++i)
2766     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2767       return false;
2768
2769   return true;
2770 }
2771
2772 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2773   SmallVector<int, 8> M;
2774   N->getMask(M);
2775   return ::isSHUFPMask(M, N->getValueType(0));
2776 }
2777
2778 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2779 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2780 /// half elements to come from vector 1 (which would equal the dest.) and
2781 /// the upper half to come from vector 2.
2782 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2783   int NumElems = VT.getVectorNumElements();
2784
2785   if (NumElems != 2 && NumElems != 4)
2786     return false;
2787
2788   int Half = NumElems / 2;
2789   for (int i = 0; i < Half; ++i)
2790     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2791       return false;
2792   for (int i = Half; i < NumElems; ++i)
2793     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2794       return false;
2795   return true;
2796 }
2797
2798 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2799   SmallVector<int, 8> M;
2800   N->getMask(M);
2801   return isCommutedSHUFPMask(M, N->getValueType(0));
2802 }
2803
2804 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2805 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2806 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2807   if (N->getValueType(0).getVectorNumElements() != 4)
2808     return false;
2809
2810   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2811   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2812          isUndefOrEqual(N->getMaskElt(1), 7) &&
2813          isUndefOrEqual(N->getMaskElt(2), 2) &&
2814          isUndefOrEqual(N->getMaskElt(3), 3);
2815 }
2816
2817 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2818 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2819 /// <2, 3, 2, 3>
2820 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2821   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2822   
2823   if (NumElems != 4)
2824     return false;
2825   
2826   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2827   isUndefOrEqual(N->getMaskElt(1), 3) &&
2828   isUndefOrEqual(N->getMaskElt(2), 2) &&
2829   isUndefOrEqual(N->getMaskElt(3), 3);
2830 }
2831
2832 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2833 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2834 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2835   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2836
2837   if (NumElems != 2 && NumElems != 4)
2838     return false;
2839
2840   for (unsigned i = 0; i < NumElems/2; ++i)
2841     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2842       return false;
2843
2844   for (unsigned i = NumElems/2; i < NumElems; ++i)
2845     if (!isUndefOrEqual(N->getMaskElt(i), i))
2846       return false;
2847
2848   return true;
2849 }
2850
2851 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2852 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2853 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2854   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2855
2856   if (NumElems != 2 && NumElems != 4)
2857     return false;
2858
2859   for (unsigned i = 0; i < NumElems/2; ++i)
2860     if (!isUndefOrEqual(N->getMaskElt(i), i))
2861       return false;
2862
2863   for (unsigned i = 0; i < NumElems/2; ++i)
2864     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2865       return false;
2866
2867   return true;
2868 }
2869
2870 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2871 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2872 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2873                          bool V2IsSplat = false) {
2874   int NumElts = VT.getVectorNumElements();
2875   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2876     return false;
2877
2878   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2879     int BitI  = Mask[i];
2880     int BitI1 = Mask[i+1];
2881     if (!isUndefOrEqual(BitI, j))
2882       return false;
2883     if (V2IsSplat) {
2884       if (!isUndefOrEqual(BitI1, NumElts))
2885         return false;
2886     } else {
2887       if (!isUndefOrEqual(BitI1, j + NumElts))
2888         return false;
2889     }
2890   }
2891   return true;
2892 }
2893
2894 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2895   SmallVector<int, 8> M;
2896   N->getMask(M);
2897   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2898 }
2899
2900 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2901 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2902 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2903                          bool V2IsSplat = false) {
2904   int NumElts = VT.getVectorNumElements();
2905   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2906     return false;
2907
2908   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2909     int BitI  = Mask[i];
2910     int BitI1 = Mask[i+1];
2911     if (!isUndefOrEqual(BitI, j + NumElts/2))
2912       return false;
2913     if (V2IsSplat) {
2914       if (isUndefOrEqual(BitI1, NumElts))
2915         return false;
2916     } else {
2917       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2918         return false;
2919     }
2920   }
2921   return true;
2922 }
2923
2924 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2925   SmallVector<int, 8> M;
2926   N->getMask(M);
2927   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2928 }
2929
2930 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2931 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2932 /// <0, 0, 1, 1>
2933 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2934   int NumElems = VT.getVectorNumElements();
2935   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2936     return false;
2937
2938   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2939     int BitI  = Mask[i];
2940     int BitI1 = Mask[i+1];
2941     if (!isUndefOrEqual(BitI, j))
2942       return false;
2943     if (!isUndefOrEqual(BitI1, j))
2944       return false;
2945   }
2946   return true;
2947 }
2948
2949 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2950   SmallVector<int, 8> M;
2951   N->getMask(M);
2952   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2953 }
2954
2955 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2956 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2957 /// <2, 2, 3, 3>
2958 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2959   int NumElems = VT.getVectorNumElements();
2960   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2961     return false;
2962
2963   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2964     int BitI  = Mask[i];
2965     int BitI1 = Mask[i+1];
2966     if (!isUndefOrEqual(BitI, j))
2967       return false;
2968     if (!isUndefOrEqual(BitI1, j))
2969       return false;
2970   }
2971   return true;
2972 }
2973
2974 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2975   SmallVector<int, 8> M;
2976   N->getMask(M);
2977   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2978 }
2979
2980 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2981 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2982 /// MOVSD, and MOVD, i.e. setting the lowest element.
2983 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2984   if (VT.getVectorElementType().getSizeInBits() < 32)
2985     return false;
2986
2987   int NumElts = VT.getVectorNumElements();
2988
2989   if (!isUndefOrEqual(Mask[0], NumElts))
2990     return false;
2991
2992   for (int i = 1; i < NumElts; ++i)
2993     if (!isUndefOrEqual(Mask[i], i))
2994       return false;
2995
2996   return true;
2997 }
2998
2999 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3000   SmallVector<int, 8> M;
3001   N->getMask(M);
3002   return ::isMOVLMask(M, N->getValueType(0));
3003 }
3004
3005 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3006 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3007 /// element of vector 2 and the other elements to come from vector 1 in order.
3008 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3009                                bool V2IsSplat = false, bool V2IsUndef = false) {
3010   int NumOps = VT.getVectorNumElements();
3011   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3012     return false;
3013
3014   if (!isUndefOrEqual(Mask[0], 0))
3015     return false;
3016
3017   for (int i = 1; i < NumOps; ++i)
3018     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3019           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3020           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3021       return false;
3022
3023   return true;
3024 }
3025
3026 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3027                            bool V2IsUndef = false) {
3028   SmallVector<int, 8> M;
3029   N->getMask(M);
3030   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3031 }
3032
3033 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3034 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3035 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3036   if (N->getValueType(0).getVectorNumElements() != 4)
3037     return false;
3038
3039   // Expect 1, 1, 3, 3
3040   for (unsigned i = 0; i < 2; ++i) {
3041     int Elt = N->getMaskElt(i);
3042     if (Elt >= 0 && Elt != 1)
3043       return false;
3044   }
3045
3046   bool HasHi = false;
3047   for (unsigned i = 2; i < 4; ++i) {
3048     int Elt = N->getMaskElt(i);
3049     if (Elt >= 0 && Elt != 3)
3050       return false;
3051     if (Elt == 3)
3052       HasHi = true;
3053   }
3054   // Don't use movshdup if it can be done with a shufps.
3055   // FIXME: verify that matching u, u, 3, 3 is what we want.
3056   return HasHi;
3057 }
3058
3059 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3060 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3061 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3062   if (N->getValueType(0).getVectorNumElements() != 4)
3063     return false;
3064
3065   // Expect 0, 0, 2, 2
3066   for (unsigned i = 0; i < 2; ++i)
3067     if (N->getMaskElt(i) > 0)
3068       return false;
3069
3070   bool HasHi = false;
3071   for (unsigned i = 2; i < 4; ++i) {
3072     int Elt = N->getMaskElt(i);
3073     if (Elt >= 0 && Elt != 2)
3074       return false;
3075     if (Elt == 2)
3076       HasHi = true;
3077   }
3078   // Don't use movsldup if it can be done with a shufps.
3079   return HasHi;
3080 }
3081
3082 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3083 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3084 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3085   int e = N->getValueType(0).getVectorNumElements() / 2;
3086
3087   for (int i = 0; i < e; ++i)
3088     if (!isUndefOrEqual(N->getMaskElt(i), i))
3089       return false;
3090   for (int i = 0; i < e; ++i)
3091     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3092       return false;
3093   return true;
3094 }
3095
3096 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3097 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3098 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3099   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3100   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3101
3102   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3103   unsigned Mask = 0;
3104   for (int i = 0; i < NumOperands; ++i) {
3105     int Val = SVOp->getMaskElt(NumOperands-i-1);
3106     if (Val < 0) Val = 0;
3107     if (Val >= NumOperands) Val -= NumOperands;
3108     Mask |= Val;
3109     if (i != NumOperands - 1)
3110       Mask <<= Shift;
3111   }
3112   return Mask;
3113 }
3114
3115 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3116 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3117 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3118   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3119   unsigned Mask = 0;
3120   // 8 nodes, but we only care about the last 4.
3121   for (unsigned i = 7; i >= 4; --i) {
3122     int Val = SVOp->getMaskElt(i);
3123     if (Val >= 0)
3124       Mask |= (Val - 4);
3125     if (i != 4)
3126       Mask <<= 2;
3127   }
3128   return Mask;
3129 }
3130
3131 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3132 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3133 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3134   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3135   unsigned Mask = 0;
3136   // 8 nodes, but we only care about the first 4.
3137   for (int i = 3; i >= 0; --i) {
3138     int Val = SVOp->getMaskElt(i);
3139     if (Val >= 0)
3140       Mask |= Val;
3141     if (i != 0)
3142       Mask <<= 2;
3143   }
3144   return Mask;
3145 }
3146
3147 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3148 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3149 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3150   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3151   EVT VVT = N->getValueType(0);
3152   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3153   int Val = 0;
3154
3155   unsigned i, e;
3156   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3157     Val = SVOp->getMaskElt(i);
3158     if (Val >= 0)
3159       break;
3160   }
3161   return (Val - i) * EltSize;
3162 }
3163
3164 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3165 /// constant +0.0.
3166 bool X86::isZeroNode(SDValue Elt) {
3167   return ((isa<ConstantSDNode>(Elt) &&
3168            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3169           (isa<ConstantFPSDNode>(Elt) &&
3170            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3171 }
3172
3173 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3174 /// their permute mask.
3175 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3176                                     SelectionDAG &DAG) {
3177   EVT VT = SVOp->getValueType(0);
3178   unsigned NumElems = VT.getVectorNumElements();
3179   SmallVector<int, 8> MaskVec;
3180
3181   for (unsigned i = 0; i != NumElems; ++i) {
3182     int idx = SVOp->getMaskElt(i);
3183     if (idx < 0)
3184       MaskVec.push_back(idx);
3185     else if (idx < (int)NumElems)
3186       MaskVec.push_back(idx + NumElems);
3187     else
3188       MaskVec.push_back(idx - NumElems);
3189   }
3190   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3191                               SVOp->getOperand(0), &MaskVec[0]);
3192 }
3193
3194 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3195 /// the two vector operands have swapped position.
3196 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3197   unsigned NumElems = VT.getVectorNumElements();
3198   for (unsigned i = 0; i != NumElems; ++i) {
3199     int idx = Mask[i];
3200     if (idx < 0)
3201       continue;
3202     else if (idx < (int)NumElems)
3203       Mask[i] = idx + NumElems;
3204     else
3205       Mask[i] = idx - NumElems;
3206   }
3207 }
3208
3209 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3210 /// match movhlps. The lower half elements should come from upper half of
3211 /// V1 (and in order), and the upper half elements should come from the upper
3212 /// half of V2 (and in order).
3213 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3214   if (Op->getValueType(0).getVectorNumElements() != 4)
3215     return false;
3216   for (unsigned i = 0, e = 2; i != e; ++i)
3217     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3218       return false;
3219   for (unsigned i = 2; i != 4; ++i)
3220     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3221       return false;
3222   return true;
3223 }
3224
3225 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3226 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3227 /// required.
3228 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3229   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3230     return false;
3231   N = N->getOperand(0).getNode();
3232   if (!ISD::isNON_EXTLoad(N))
3233     return false;
3234   if (LD)
3235     *LD = cast<LoadSDNode>(N);
3236   return true;
3237 }
3238
3239 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3240 /// match movlp{s|d}. The lower half elements should come from lower half of
3241 /// V1 (and in order), and the upper half elements should come from the upper
3242 /// half of V2 (and in order). And since V1 will become the source of the
3243 /// MOVLP, it must be either a vector load or a scalar load to vector.
3244 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3245                                ShuffleVectorSDNode *Op) {
3246   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3247     return false;
3248   // Is V2 is a vector load, don't do this transformation. We will try to use
3249   // load folding shufps op.
3250   if (ISD::isNON_EXTLoad(V2))
3251     return false;
3252
3253   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3254
3255   if (NumElems != 2 && NumElems != 4)
3256     return false;
3257   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3258     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3259       return false;
3260   for (unsigned i = NumElems/2; i != NumElems; ++i)
3261     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3262       return false;
3263   return true;
3264 }
3265
3266 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3267 /// all the same.
3268 static bool isSplatVector(SDNode *N) {
3269   if (N->getOpcode() != ISD::BUILD_VECTOR)
3270     return false;
3271
3272   SDValue SplatValue = N->getOperand(0);
3273   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3274     if (N->getOperand(i) != SplatValue)
3275       return false;
3276   return true;
3277 }
3278
3279 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3280 /// to an zero vector.
3281 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3282 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3283   SDValue V1 = N->getOperand(0);
3284   SDValue V2 = N->getOperand(1);
3285   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3286   for (unsigned i = 0; i != NumElems; ++i) {
3287     int Idx = N->getMaskElt(i);
3288     if (Idx >= (int)NumElems) {
3289       unsigned Opc = V2.getOpcode();
3290       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3291         continue;
3292       if (Opc != ISD::BUILD_VECTOR ||
3293           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3294         return false;
3295     } else if (Idx >= 0) {
3296       unsigned Opc = V1.getOpcode();
3297       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3298         continue;
3299       if (Opc != ISD::BUILD_VECTOR ||
3300           !X86::isZeroNode(V1.getOperand(Idx)))
3301         return false;
3302     }
3303   }
3304   return true;
3305 }
3306
3307 /// getZeroVector - Returns a vector of specified type with all zero elements.
3308 ///
3309 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3310                              DebugLoc dl) {
3311   assert(VT.isVector() && "Expected a vector type");
3312
3313   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3314   // type.  This ensures they get CSE'd.
3315   SDValue Vec;
3316   if (VT.getSizeInBits() == 64) { // MMX
3317     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3318     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3319   } else if (HasSSE2) {  // SSE2
3320     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3321     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3322   } else { // SSE1
3323     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3324     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3325   }
3326   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3327 }
3328
3329 /// getOnesVector - Returns a vector of specified type with all bits set.
3330 ///
3331 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3332   assert(VT.isVector() && "Expected a vector type");
3333
3334   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3335   // type.  This ensures they get CSE'd.
3336   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3337   SDValue Vec;
3338   if (VT.getSizeInBits() == 64)  // MMX
3339     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3340   else                                              // SSE
3341     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3342   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3343 }
3344
3345
3346 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3347 /// that point to V2 points to its first element.
3348 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3349   EVT VT = SVOp->getValueType(0);
3350   unsigned NumElems = VT.getVectorNumElements();
3351
3352   bool Changed = false;
3353   SmallVector<int, 8> MaskVec;
3354   SVOp->getMask(MaskVec);
3355
3356   for (unsigned i = 0; i != NumElems; ++i) {
3357     if (MaskVec[i] > (int)NumElems) {
3358       MaskVec[i] = NumElems;
3359       Changed = true;
3360     }
3361   }
3362   if (Changed)
3363     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3364                                 SVOp->getOperand(1), &MaskVec[0]);
3365   return SDValue(SVOp, 0);
3366 }
3367
3368 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3369 /// operation of specified width.
3370 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3371                        SDValue V2) {
3372   unsigned NumElems = VT.getVectorNumElements();
3373   SmallVector<int, 8> Mask;
3374   Mask.push_back(NumElems);
3375   for (unsigned i = 1; i != NumElems; ++i)
3376     Mask.push_back(i);
3377   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3378 }
3379
3380 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3381 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3382                           SDValue V2) {
3383   unsigned NumElems = VT.getVectorNumElements();
3384   SmallVector<int, 8> Mask;
3385   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3386     Mask.push_back(i);
3387     Mask.push_back(i + NumElems);
3388   }
3389   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3390 }
3391
3392 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3393 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3394                           SDValue V2) {
3395   unsigned NumElems = VT.getVectorNumElements();
3396   unsigned Half = NumElems/2;
3397   SmallVector<int, 8> Mask;
3398   for (unsigned i = 0; i != Half; ++i) {
3399     Mask.push_back(i + Half);
3400     Mask.push_back(i + NumElems + Half);
3401   }
3402   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3403 }
3404
3405 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3406 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3407                             bool HasSSE2) {
3408   if (SV->getValueType(0).getVectorNumElements() <= 4)
3409     return SDValue(SV, 0);
3410
3411   EVT PVT = MVT::v4f32;
3412   EVT VT = SV->getValueType(0);
3413   DebugLoc dl = SV->getDebugLoc();
3414   SDValue V1 = SV->getOperand(0);
3415   int NumElems = VT.getVectorNumElements();
3416   int EltNo = SV->getSplatIndex();
3417
3418   // unpack elements to the correct location
3419   while (NumElems > 4) {
3420     if (EltNo < NumElems/2) {
3421       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3422     } else {
3423       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3424       EltNo -= NumElems/2;
3425     }
3426     NumElems >>= 1;
3427   }
3428
3429   // Perform the splat.
3430   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3431   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3432   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3433   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3434 }
3435
3436 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3437 /// vector of zero or undef vector.  This produces a shuffle where the low
3438 /// element of V2 is swizzled into the zero/undef vector, landing at element
3439 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3440 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3441                                              bool isZero, bool HasSSE2,
3442                                              SelectionDAG &DAG) {
3443   EVT VT = V2.getValueType();
3444   SDValue V1 = isZero
3445     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3446   unsigned NumElems = VT.getVectorNumElements();
3447   SmallVector<int, 16> MaskVec;
3448   for (unsigned i = 0; i != NumElems; ++i)
3449     // If this is the insertion idx, put the low elt of V2 here.
3450     MaskVec.push_back(i == Idx ? NumElems : i);
3451   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3452 }
3453
3454 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3455 /// a shuffle that is zero.
3456 static
3457 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3458                                   bool Low, SelectionDAG &DAG) {
3459   unsigned NumZeros = 0;
3460   for (int i = 0; i < NumElems; ++i) {
3461     unsigned Index = Low ? i : NumElems-i-1;
3462     int Idx = SVOp->getMaskElt(Index);
3463     if (Idx < 0) {
3464       ++NumZeros;
3465       continue;
3466     }
3467     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3468     if (Elt.getNode() && X86::isZeroNode(Elt))
3469       ++NumZeros;
3470     else
3471       break;
3472   }
3473   return NumZeros;
3474 }
3475
3476 /// isVectorShift - Returns true if the shuffle can be implemented as a
3477 /// logical left or right shift of a vector.
3478 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3479 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3480                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3481   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3482
3483   isLeft = true;
3484   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3485   if (!NumZeros) {
3486     isLeft = false;
3487     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3488     if (!NumZeros)
3489       return false;
3490   }
3491   bool SeenV1 = false;
3492   bool SeenV2 = false;
3493   for (unsigned i = NumZeros; i < NumElems; ++i) {
3494     unsigned Val = isLeft ? (i - NumZeros) : i;
3495     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3496     if (Idx_ < 0)
3497       continue;
3498     unsigned Idx = (unsigned) Idx_;
3499     if (Idx < NumElems)
3500       SeenV1 = true;
3501     else {
3502       Idx -= NumElems;
3503       SeenV2 = true;
3504     }
3505     if (Idx != Val)
3506       return false;
3507   }
3508   if (SeenV1 && SeenV2)
3509     return false;
3510
3511   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3512   ShAmt = NumZeros;
3513   return true;
3514 }
3515
3516
3517 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3518 ///
3519 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3520                                        unsigned NumNonZero, unsigned NumZero,
3521                                        SelectionDAG &DAG,
3522                                        const TargetLowering &TLI) {
3523   if (NumNonZero > 8)
3524     return SDValue();
3525
3526   DebugLoc dl = Op.getDebugLoc();
3527   SDValue V(0, 0);
3528   bool First = true;
3529   for (unsigned i = 0; i < 16; ++i) {
3530     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3531     if (ThisIsNonZero && First) {
3532       if (NumZero)
3533         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3534       else
3535         V = DAG.getUNDEF(MVT::v8i16);
3536       First = false;
3537     }
3538
3539     if ((i & 1) != 0) {
3540       SDValue ThisElt(0, 0), LastElt(0, 0);
3541       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3542       if (LastIsNonZero) {
3543         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3544                               MVT::i16, Op.getOperand(i-1));
3545       }
3546       if (ThisIsNonZero) {
3547         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3548         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3549                               ThisElt, DAG.getConstant(8, MVT::i8));
3550         if (LastIsNonZero)
3551           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3552       } else
3553         ThisElt = LastElt;
3554
3555       if (ThisElt.getNode())
3556         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3557                         DAG.getIntPtrConstant(i/2));
3558     }
3559   }
3560
3561   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3562 }
3563
3564 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3565 ///
3566 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3567                                      unsigned NumNonZero, unsigned NumZero,
3568                                      SelectionDAG &DAG,
3569                                      const TargetLowering &TLI) {
3570   if (NumNonZero > 4)
3571     return SDValue();
3572
3573   DebugLoc dl = Op.getDebugLoc();
3574   SDValue V(0, 0);
3575   bool First = true;
3576   for (unsigned i = 0; i < 8; ++i) {
3577     bool isNonZero = (NonZeros & (1 << i)) != 0;
3578     if (isNonZero) {
3579       if (First) {
3580         if (NumZero)
3581           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3582         else
3583           V = DAG.getUNDEF(MVT::v8i16);
3584         First = false;
3585       }
3586       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3587                       MVT::v8i16, V, Op.getOperand(i),
3588                       DAG.getIntPtrConstant(i));
3589     }
3590   }
3591
3592   return V;
3593 }
3594
3595 /// getVShift - Return a vector logical shift node.
3596 ///
3597 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3598                          unsigned NumBits, SelectionDAG &DAG,
3599                          const TargetLowering &TLI, DebugLoc dl) {
3600   bool isMMX = VT.getSizeInBits() == 64;
3601   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3602   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3603   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3604   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3605                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3606                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3607 }
3608
3609 SDValue
3610 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3611                                           SelectionDAG &DAG) const {
3612   
3613   // Check if the scalar load can be widened into a vector load. And if
3614   // the address is "base + cst" see if the cst can be "absorbed" into
3615   // the shuffle mask.
3616   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3617     SDValue Ptr = LD->getBasePtr();
3618     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3619       return SDValue();
3620     EVT PVT = LD->getValueType(0);
3621     if (PVT != MVT::i32 && PVT != MVT::f32)
3622       return SDValue();
3623
3624     int FI = -1;
3625     int64_t Offset = 0;
3626     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3627       FI = FINode->getIndex();
3628       Offset = 0;
3629     } else if (Ptr.getOpcode() == ISD::ADD &&
3630                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3631                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3632       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3633       Offset = Ptr.getConstantOperandVal(1);
3634       Ptr = Ptr.getOperand(0);
3635     } else {
3636       return SDValue();
3637     }
3638
3639     SDValue Chain = LD->getChain();
3640     // Make sure the stack object alignment is at least 16.
3641     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3642     if (DAG.InferPtrAlignment(Ptr) < 16) {
3643       if (MFI->isFixedObjectIndex(FI)) {
3644         // Can't change the alignment. FIXME: It's possible to compute
3645         // the exact stack offset and reference FI + adjust offset instead.
3646         // If someone *really* cares about this. That's the way to implement it.
3647         return SDValue();
3648       } else {
3649         MFI->setObjectAlignment(FI, 16);
3650       }
3651     }
3652
3653     // (Offset % 16) must be multiple of 4. Then address is then
3654     // Ptr + (Offset & ~15).
3655     if (Offset < 0)
3656       return SDValue();
3657     if ((Offset % 16) & 3)
3658       return SDValue();
3659     int64_t StartOffset = Offset & ~15;
3660     if (StartOffset)
3661       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3662                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3663
3664     int EltNo = (Offset - StartOffset) >> 2;
3665     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3666     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3667     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3668                              false, false, 0);
3669     // Canonicalize it to a v4i32 shuffle.
3670     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3671     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3672                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3673                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3674   }
3675
3676   return SDValue();
3677 }
3678
3679 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3680 /// vector of type 'VT', see if the elements can be replaced by a single large 
3681 /// load which has the same value as a build_vector whose operands are 'elts'.
3682 ///
3683 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3684 /// 
3685 /// FIXME: we'd also like to handle the case where the last elements are zero
3686 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3687 /// There's even a handy isZeroNode for that purpose.
3688 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3689                                         DebugLoc &dl, SelectionDAG &DAG) {
3690   EVT EltVT = VT.getVectorElementType();
3691   unsigned NumElems = Elts.size();
3692   
3693   LoadSDNode *LDBase = NULL;
3694   unsigned LastLoadedElt = -1U;
3695   
3696   // For each element in the initializer, see if we've found a load or an undef.
3697   // If we don't find an initial load element, or later load elements are 
3698   // non-consecutive, bail out.
3699   for (unsigned i = 0; i < NumElems; ++i) {
3700     SDValue Elt = Elts[i];
3701     
3702     if (!Elt.getNode() ||
3703         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3704       return SDValue();
3705     if (!LDBase) {
3706       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3707         return SDValue();
3708       LDBase = cast<LoadSDNode>(Elt.getNode());
3709       LastLoadedElt = i;
3710       continue;
3711     }
3712     if (Elt.getOpcode() == ISD::UNDEF)
3713       continue;
3714
3715     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3716     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3717       return SDValue();
3718     LastLoadedElt = i;
3719   }
3720
3721   // If we have found an entire vector of loads and undefs, then return a large
3722   // load of the entire vector width starting at the base pointer.  If we found
3723   // consecutive loads for the low half, generate a vzext_load node.
3724   if (LastLoadedElt == NumElems - 1) {
3725     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3726       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3727                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3728                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3729     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3730                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3731                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3732                        LDBase->getAlignment());
3733   } else if (NumElems == 4 && LastLoadedElt == 1) {
3734     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3735     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3736     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3737     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3738   }
3739   return SDValue();
3740 }
3741
3742 SDValue
3743 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3744   DebugLoc dl = Op.getDebugLoc();
3745   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3746   if (ISD::isBuildVectorAllZeros(Op.getNode())
3747       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3748     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3749     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3750     // eliminated on x86-32 hosts.
3751     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3752       return Op;
3753
3754     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3755       return getOnesVector(Op.getValueType(), DAG, dl);
3756     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3757   }
3758
3759   EVT VT = Op.getValueType();
3760   EVT ExtVT = VT.getVectorElementType();
3761   unsigned EVTBits = ExtVT.getSizeInBits();
3762
3763   unsigned NumElems = Op.getNumOperands();
3764   unsigned NumZero  = 0;
3765   unsigned NumNonZero = 0;
3766   unsigned NonZeros = 0;
3767   bool IsAllConstants = true;
3768   SmallSet<SDValue, 8> Values;
3769   for (unsigned i = 0; i < NumElems; ++i) {
3770     SDValue Elt = Op.getOperand(i);
3771     if (Elt.getOpcode() == ISD::UNDEF)
3772       continue;
3773     Values.insert(Elt);
3774     if (Elt.getOpcode() != ISD::Constant &&
3775         Elt.getOpcode() != ISD::ConstantFP)
3776       IsAllConstants = false;
3777     if (X86::isZeroNode(Elt))
3778       NumZero++;
3779     else {
3780       NonZeros |= (1 << i);
3781       NumNonZero++;
3782     }
3783   }
3784
3785   if (NumNonZero == 0) {
3786     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3787     return DAG.getUNDEF(VT);
3788   }
3789
3790   // Special case for single non-zero, non-undef, element.
3791   if (NumNonZero == 1) {
3792     unsigned Idx = CountTrailingZeros_32(NonZeros);
3793     SDValue Item = Op.getOperand(Idx);
3794
3795     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3796     // the value are obviously zero, truncate the value to i32 and do the
3797     // insertion that way.  Only do this if the value is non-constant or if the
3798     // value is a constant being inserted into element 0.  It is cheaper to do
3799     // a constant pool load than it is to do a movd + shuffle.
3800     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3801         (!IsAllConstants || Idx == 0)) {
3802       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3803         // Handle MMX and SSE both.
3804         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3805         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3806
3807         // Truncate the value (which may itself be a constant) to i32, and
3808         // convert it to a vector with movd (S2V+shuffle to zero extend).
3809         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3810         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3811         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3812                                            Subtarget->hasSSE2(), DAG);
3813
3814         // Now we have our 32-bit value zero extended in the low element of
3815         // a vector.  If Idx != 0, swizzle it into place.
3816         if (Idx != 0) {
3817           SmallVector<int, 4> Mask;
3818           Mask.push_back(Idx);
3819           for (unsigned i = 1; i != VecElts; ++i)
3820             Mask.push_back(i);
3821           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3822                                       DAG.getUNDEF(Item.getValueType()),
3823                                       &Mask[0]);
3824         }
3825         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3826       }
3827     }
3828
3829     // If we have a constant or non-constant insertion into the low element of
3830     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3831     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3832     // depending on what the source datatype is.
3833     if (Idx == 0) {
3834       if (NumZero == 0) {
3835         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3836       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3837           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3838         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3839         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3840         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3841                                            DAG);
3842       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3843         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3844         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3845         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3846         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3847                                            Subtarget->hasSSE2(), DAG);
3848         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3849       }
3850     }
3851
3852     // Is it a vector logical left shift?
3853     if (NumElems == 2 && Idx == 1 &&
3854         X86::isZeroNode(Op.getOperand(0)) &&
3855         !X86::isZeroNode(Op.getOperand(1))) {
3856       unsigned NumBits = VT.getSizeInBits();
3857       return getVShift(true, VT,
3858                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3859                                    VT, Op.getOperand(1)),
3860                        NumBits/2, DAG, *this, dl);
3861     }
3862
3863     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3864       return SDValue();
3865
3866     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3867     // is a non-constant being inserted into an element other than the low one,
3868     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3869     // movd/movss) to move this into the low element, then shuffle it into
3870     // place.
3871     if (EVTBits == 32) {
3872       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3873
3874       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3875       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3876                                          Subtarget->hasSSE2(), DAG);
3877       SmallVector<int, 8> MaskVec;
3878       for (unsigned i = 0; i < NumElems; i++)
3879         MaskVec.push_back(i == Idx ? 0 : 1);
3880       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3881     }
3882   }
3883
3884   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3885   if (Values.size() == 1) {
3886     if (EVTBits == 32) {
3887       // Instead of a shuffle like this:
3888       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3889       // Check if it's possible to issue this instead.
3890       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3891       unsigned Idx = CountTrailingZeros_32(NonZeros);
3892       SDValue Item = Op.getOperand(Idx);
3893       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3894         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3895     }
3896     return SDValue();
3897   }
3898
3899   // A vector full of immediates; various special cases are already
3900   // handled, so this is best done with a single constant-pool load.
3901   if (IsAllConstants)
3902     return SDValue();
3903
3904   // Let legalizer expand 2-wide build_vectors.
3905   if (EVTBits == 64) {
3906     if (NumNonZero == 1) {
3907       // One half is zero or undef.
3908       unsigned Idx = CountTrailingZeros_32(NonZeros);
3909       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3910                                  Op.getOperand(Idx));
3911       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3912                                          Subtarget->hasSSE2(), DAG);
3913     }
3914     return SDValue();
3915   }
3916
3917   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3918   if (EVTBits == 8 && NumElems == 16) {
3919     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3920                                         *this);
3921     if (V.getNode()) return V;
3922   }
3923
3924   if (EVTBits == 16 && NumElems == 8) {
3925     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3926                                         *this);
3927     if (V.getNode()) return V;
3928   }
3929
3930   // If element VT is == 32 bits, turn it into a number of shuffles.
3931   SmallVector<SDValue, 8> V;
3932   V.resize(NumElems);
3933   if (NumElems == 4 && NumZero > 0) {
3934     for (unsigned i = 0; i < 4; ++i) {
3935       bool isZero = !(NonZeros & (1 << i));
3936       if (isZero)
3937         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3938       else
3939         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3940     }
3941
3942     for (unsigned i = 0; i < 2; ++i) {
3943       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3944         default: break;
3945         case 0:
3946           V[i] = V[i*2];  // Must be a zero vector.
3947           break;
3948         case 1:
3949           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3950           break;
3951         case 2:
3952           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3953           break;
3954         case 3:
3955           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3956           break;
3957       }
3958     }
3959
3960     SmallVector<int, 8> MaskVec;
3961     bool Reverse = (NonZeros & 0x3) == 2;
3962     for (unsigned i = 0; i < 2; ++i)
3963       MaskVec.push_back(Reverse ? 1-i : i);
3964     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3965     for (unsigned i = 0; i < 2; ++i)
3966       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3967     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3968   }
3969
3970   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3971     // Check for a build vector of consecutive loads.
3972     for (unsigned i = 0; i < NumElems; ++i)
3973       V[i] = Op.getOperand(i);
3974     
3975     // Check for elements which are consecutive loads.
3976     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3977     if (LD.getNode())
3978       return LD;
3979     
3980     // For SSE 4.1, use inserts into undef.  
3981     if (getSubtarget()->hasSSE41()) {
3982       V[0] = DAG.getUNDEF(VT);
3983       for (unsigned i = 0; i < NumElems; ++i)
3984         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3985           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3986                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3987       return V[0];
3988     }
3989     
3990     // Otherwise, expand into a number of unpckl*
3991     // e.g. for v4f32
3992     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3993     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3994     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3995     for (unsigned i = 0; i < NumElems; ++i)
3996       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3997     NumElems >>= 1;
3998     while (NumElems != 0) {
3999       for (unsigned i = 0; i < NumElems; ++i)
4000         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4001       NumElems >>= 1;
4002     }
4003     return V[0];
4004   }
4005   return SDValue();
4006 }
4007
4008 SDValue
4009 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4010   // We support concatenate two MMX registers and place them in a MMX
4011   // register.  This is better than doing a stack convert.
4012   DebugLoc dl = Op.getDebugLoc();
4013   EVT ResVT = Op.getValueType();
4014   assert(Op.getNumOperands() == 2);
4015   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4016          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4017   int Mask[2];
4018   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4019   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4020   InVec = Op.getOperand(1);
4021   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4022     unsigned NumElts = ResVT.getVectorNumElements();
4023     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4024     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4025                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4026   } else {
4027     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4028     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4029     Mask[0] = 0; Mask[1] = 2;
4030     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4031   }
4032   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4033 }
4034
4035 // v8i16 shuffles - Prefer shuffles in the following order:
4036 // 1. [all]   pshuflw, pshufhw, optional move
4037 // 2. [ssse3] 1 x pshufb
4038 // 3. [ssse3] 2 x pshufb + 1 x por
4039 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4040 static
4041 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4042                                  SelectionDAG &DAG,
4043                                  const X86TargetLowering &TLI) {
4044   SDValue V1 = SVOp->getOperand(0);
4045   SDValue V2 = SVOp->getOperand(1);
4046   DebugLoc dl = SVOp->getDebugLoc();
4047   SmallVector<int, 8> MaskVals;
4048
4049   // Determine if more than 1 of the words in each of the low and high quadwords
4050   // of the result come from the same quadword of one of the two inputs.  Undef
4051   // mask values count as coming from any quadword, for better codegen.
4052   SmallVector<unsigned, 4> LoQuad(4);
4053   SmallVector<unsigned, 4> HiQuad(4);
4054   BitVector InputQuads(4);
4055   for (unsigned i = 0; i < 8; ++i) {
4056     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4057     int EltIdx = SVOp->getMaskElt(i);
4058     MaskVals.push_back(EltIdx);
4059     if (EltIdx < 0) {
4060       ++Quad[0];
4061       ++Quad[1];
4062       ++Quad[2];
4063       ++Quad[3];
4064       continue;
4065     }
4066     ++Quad[EltIdx / 4];
4067     InputQuads.set(EltIdx / 4);
4068   }
4069
4070   int BestLoQuad = -1;
4071   unsigned MaxQuad = 1;
4072   for (unsigned i = 0; i < 4; ++i) {
4073     if (LoQuad[i] > MaxQuad) {
4074       BestLoQuad = i;
4075       MaxQuad = LoQuad[i];
4076     }
4077   }
4078
4079   int BestHiQuad = -1;
4080   MaxQuad = 1;
4081   for (unsigned i = 0; i < 4; ++i) {
4082     if (HiQuad[i] > MaxQuad) {
4083       BestHiQuad = i;
4084       MaxQuad = HiQuad[i];
4085     }
4086   }
4087
4088   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4089   // of the two input vectors, shuffle them into one input vector so only a
4090   // single pshufb instruction is necessary. If There are more than 2 input
4091   // quads, disable the next transformation since it does not help SSSE3.
4092   bool V1Used = InputQuads[0] || InputQuads[1];
4093   bool V2Used = InputQuads[2] || InputQuads[3];
4094   if (TLI.getSubtarget()->hasSSSE3()) {
4095     if (InputQuads.count() == 2 && V1Used && V2Used) {
4096       BestLoQuad = InputQuads.find_first();
4097       BestHiQuad = InputQuads.find_next(BestLoQuad);
4098     }
4099     if (InputQuads.count() > 2) {
4100       BestLoQuad = -1;
4101       BestHiQuad = -1;
4102     }
4103   }
4104
4105   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4106   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4107   // words from all 4 input quadwords.
4108   SDValue NewV;
4109   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4110     SmallVector<int, 8> MaskV;
4111     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4112     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4113     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4114                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4115                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4116     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4117
4118     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4119     // source words for the shuffle, to aid later transformations.
4120     bool AllWordsInNewV = true;
4121     bool InOrder[2] = { true, true };
4122     for (unsigned i = 0; i != 8; ++i) {
4123       int idx = MaskVals[i];
4124       if (idx != (int)i)
4125         InOrder[i/4] = false;
4126       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4127         continue;
4128       AllWordsInNewV = false;
4129       break;
4130     }
4131
4132     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4133     if (AllWordsInNewV) {
4134       for (int i = 0; i != 8; ++i) {
4135         int idx = MaskVals[i];
4136         if (idx < 0)
4137           continue;
4138         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4139         if ((idx != i) && idx < 4)
4140           pshufhw = false;
4141         if ((idx != i) && idx > 3)
4142           pshuflw = false;
4143       }
4144       V1 = NewV;
4145       V2Used = false;
4146       BestLoQuad = 0;
4147       BestHiQuad = 1;
4148     }
4149
4150     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4151     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4152     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4153       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4154                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4155     }
4156   }
4157
4158   // If we have SSSE3, and all words of the result are from 1 input vector,
4159   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4160   // is present, fall back to case 4.
4161   if (TLI.getSubtarget()->hasSSSE3()) {
4162     SmallVector<SDValue,16> pshufbMask;
4163
4164     // If we have elements from both input vectors, set the high bit of the
4165     // shuffle mask element to zero out elements that come from V2 in the V1
4166     // mask, and elements that come from V1 in the V2 mask, so that the two
4167     // results can be OR'd together.
4168     bool TwoInputs = V1Used && V2Used;
4169     for (unsigned i = 0; i != 8; ++i) {
4170       int EltIdx = MaskVals[i] * 2;
4171       if (TwoInputs && (EltIdx >= 16)) {
4172         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4173         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4174         continue;
4175       }
4176       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4177       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4178     }
4179     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4180     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4181                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4182                                  MVT::v16i8, &pshufbMask[0], 16));
4183     if (!TwoInputs)
4184       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4185
4186     // Calculate the shuffle mask for the second input, shuffle it, and
4187     // OR it with the first shuffled input.
4188     pshufbMask.clear();
4189     for (unsigned i = 0; i != 8; ++i) {
4190       int EltIdx = MaskVals[i] * 2;
4191       if (EltIdx < 16) {
4192         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4193         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4194         continue;
4195       }
4196       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4197       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4198     }
4199     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4200     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4201                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4202                                  MVT::v16i8, &pshufbMask[0], 16));
4203     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4204     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4205   }
4206
4207   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4208   // and update MaskVals with new element order.
4209   BitVector InOrder(8);
4210   if (BestLoQuad >= 0) {
4211     SmallVector<int, 8> MaskV;
4212     for (int i = 0; i != 4; ++i) {
4213       int idx = MaskVals[i];
4214       if (idx < 0) {
4215         MaskV.push_back(-1);
4216         InOrder.set(i);
4217       } else if ((idx / 4) == BestLoQuad) {
4218         MaskV.push_back(idx & 3);
4219         InOrder.set(i);
4220       } else {
4221         MaskV.push_back(-1);
4222       }
4223     }
4224     for (unsigned i = 4; i != 8; ++i)
4225       MaskV.push_back(i);
4226     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4227                                 &MaskV[0]);
4228   }
4229
4230   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4231   // and update MaskVals with the new element order.
4232   if (BestHiQuad >= 0) {
4233     SmallVector<int, 8> MaskV;
4234     for (unsigned i = 0; i != 4; ++i)
4235       MaskV.push_back(i);
4236     for (unsigned i = 4; i != 8; ++i) {
4237       int idx = MaskVals[i];
4238       if (idx < 0) {
4239         MaskV.push_back(-1);
4240         InOrder.set(i);
4241       } else if ((idx / 4) == BestHiQuad) {
4242         MaskV.push_back((idx & 3) + 4);
4243         InOrder.set(i);
4244       } else {
4245         MaskV.push_back(-1);
4246       }
4247     }
4248     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4249                                 &MaskV[0]);
4250   }
4251
4252   // In case BestHi & BestLo were both -1, which means each quadword has a word
4253   // from each of the four input quadwords, calculate the InOrder bitvector now
4254   // before falling through to the insert/extract cleanup.
4255   if (BestLoQuad == -1 && BestHiQuad == -1) {
4256     NewV = V1;
4257     for (int i = 0; i != 8; ++i)
4258       if (MaskVals[i] < 0 || MaskVals[i] == i)
4259         InOrder.set(i);
4260   }
4261
4262   // The other elements are put in the right place using pextrw and pinsrw.
4263   for (unsigned i = 0; i != 8; ++i) {
4264     if (InOrder[i])
4265       continue;
4266     int EltIdx = MaskVals[i];
4267     if (EltIdx < 0)
4268       continue;
4269     SDValue ExtOp = (EltIdx < 8)
4270     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4271                   DAG.getIntPtrConstant(EltIdx))
4272     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4273                   DAG.getIntPtrConstant(EltIdx - 8));
4274     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4275                        DAG.getIntPtrConstant(i));
4276   }
4277   return NewV;
4278 }
4279
4280 // v16i8 shuffles - Prefer shuffles in the following order:
4281 // 1. [ssse3] 1 x pshufb
4282 // 2. [ssse3] 2 x pshufb + 1 x por
4283 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4284 static
4285 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4286                                  SelectionDAG &DAG,
4287                                  const X86TargetLowering &TLI) {
4288   SDValue V1 = SVOp->getOperand(0);
4289   SDValue V2 = SVOp->getOperand(1);
4290   DebugLoc dl = SVOp->getDebugLoc();
4291   SmallVector<int, 16> MaskVals;
4292   SVOp->getMask(MaskVals);
4293
4294   // If we have SSSE3, case 1 is generated when all result bytes come from
4295   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4296   // present, fall back to case 3.
4297   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4298   bool V1Only = true;
4299   bool V2Only = true;
4300   for (unsigned i = 0; i < 16; ++i) {
4301     int EltIdx = MaskVals[i];
4302     if (EltIdx < 0)
4303       continue;
4304     if (EltIdx < 16)
4305       V2Only = false;
4306     else
4307       V1Only = false;
4308   }
4309
4310   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4311   if (TLI.getSubtarget()->hasSSSE3()) {
4312     SmallVector<SDValue,16> pshufbMask;
4313
4314     // If all result elements are from one input vector, then only translate
4315     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4316     //
4317     // Otherwise, we have elements from both input vectors, and must zero out
4318     // elements that come from V2 in the first mask, and V1 in the second mask
4319     // so that we can OR them together.
4320     bool TwoInputs = !(V1Only || V2Only);
4321     for (unsigned i = 0; i != 16; ++i) {
4322       int EltIdx = MaskVals[i];
4323       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4324         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4325         continue;
4326       }
4327       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4328     }
4329     // If all the elements are from V2, assign it to V1 and return after
4330     // building the first pshufb.
4331     if (V2Only)
4332       V1 = V2;
4333     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4334                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4335                                  MVT::v16i8, &pshufbMask[0], 16));
4336     if (!TwoInputs)
4337       return V1;
4338
4339     // Calculate the shuffle mask for the second input, shuffle it, and
4340     // OR it with the first shuffled input.
4341     pshufbMask.clear();
4342     for (unsigned i = 0; i != 16; ++i) {
4343       int EltIdx = MaskVals[i];
4344       if (EltIdx < 16) {
4345         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4346         continue;
4347       }
4348       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4349     }
4350     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4351                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4352                                  MVT::v16i8, &pshufbMask[0], 16));
4353     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4354   }
4355
4356   // No SSSE3 - Calculate in place words and then fix all out of place words
4357   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4358   // the 16 different words that comprise the two doublequadword input vectors.
4359   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4360   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4361   SDValue NewV = V2Only ? V2 : V1;
4362   for (int i = 0; i != 8; ++i) {
4363     int Elt0 = MaskVals[i*2];
4364     int Elt1 = MaskVals[i*2+1];
4365
4366     // This word of the result is all undef, skip it.
4367     if (Elt0 < 0 && Elt1 < 0)
4368       continue;
4369
4370     // This word of the result is already in the correct place, skip it.
4371     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4372       continue;
4373     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4374       continue;
4375
4376     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4377     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4378     SDValue InsElt;
4379
4380     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4381     // using a single extract together, load it and store it.
4382     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4383       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4384                            DAG.getIntPtrConstant(Elt1 / 2));
4385       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4386                         DAG.getIntPtrConstant(i));
4387       continue;
4388     }
4389
4390     // If Elt1 is defined, extract it from the appropriate source.  If the
4391     // source byte is not also odd, shift the extracted word left 8 bits
4392     // otherwise clear the bottom 8 bits if we need to do an or.
4393     if (Elt1 >= 0) {
4394       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4395                            DAG.getIntPtrConstant(Elt1 / 2));
4396       if ((Elt1 & 1) == 0)
4397         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4398                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4399       else if (Elt0 >= 0)
4400         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4401                              DAG.getConstant(0xFF00, MVT::i16));
4402     }
4403     // If Elt0 is defined, extract it from the appropriate source.  If the
4404     // source byte is not also even, shift the extracted word right 8 bits. If
4405     // Elt1 was also defined, OR the extracted values together before
4406     // inserting them in the result.
4407     if (Elt0 >= 0) {
4408       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4409                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4410       if ((Elt0 & 1) != 0)
4411         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4412                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4413       else if (Elt1 >= 0)
4414         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4415                              DAG.getConstant(0x00FF, MVT::i16));
4416       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4417                          : InsElt0;
4418     }
4419     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4420                        DAG.getIntPtrConstant(i));
4421   }
4422   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4423 }
4424
4425 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4426 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4427 /// done when every pair / quad of shuffle mask elements point to elements in
4428 /// the right sequence. e.g.
4429 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4430 static
4431 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4432                                  SelectionDAG &DAG,
4433                                  const TargetLowering &TLI, DebugLoc dl) {
4434   EVT VT = SVOp->getValueType(0);
4435   SDValue V1 = SVOp->getOperand(0);
4436   SDValue V2 = SVOp->getOperand(1);
4437   unsigned NumElems = VT.getVectorNumElements();
4438   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4439   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4440   EVT MaskEltVT = MaskVT.getVectorElementType();
4441   EVT NewVT = MaskVT;
4442   switch (VT.getSimpleVT().SimpleTy) {
4443   default: assert(false && "Unexpected!");
4444   case MVT::v4f32: NewVT = MVT::v2f64; break;
4445   case MVT::v4i32: NewVT = MVT::v2i64; break;
4446   case MVT::v8i16: NewVT = MVT::v4i32; break;
4447   case MVT::v16i8: NewVT = MVT::v4i32; break;
4448   }
4449
4450   if (NewWidth == 2) {
4451     if (VT.isInteger())
4452       NewVT = MVT::v2i64;
4453     else
4454       NewVT = MVT::v2f64;
4455   }
4456   int Scale = NumElems / NewWidth;
4457   SmallVector<int, 8> MaskVec;
4458   for (unsigned i = 0; i < NumElems; i += Scale) {
4459     int StartIdx = -1;
4460     for (int j = 0; j < Scale; ++j) {
4461       int EltIdx = SVOp->getMaskElt(i+j);
4462       if (EltIdx < 0)
4463         continue;
4464       if (StartIdx == -1)
4465         StartIdx = EltIdx - (EltIdx % Scale);
4466       if (EltIdx != StartIdx + j)
4467         return SDValue();
4468     }
4469     if (StartIdx == -1)
4470       MaskVec.push_back(-1);
4471     else
4472       MaskVec.push_back(StartIdx / Scale);
4473   }
4474
4475   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4476   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4477   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4478 }
4479
4480 /// getVZextMovL - Return a zero-extending vector move low node.
4481 ///
4482 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4483                             SDValue SrcOp, SelectionDAG &DAG,
4484                             const X86Subtarget *Subtarget, DebugLoc dl) {
4485   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4486     LoadSDNode *LD = NULL;
4487     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4488       LD = dyn_cast<LoadSDNode>(SrcOp);
4489     if (!LD) {
4490       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4491       // instead.
4492       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4493       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4494           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4495           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4496           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4497         // PR2108
4498         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4499         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4500                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4501                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4502                                                    OpVT,
4503                                                    SrcOp.getOperand(0)
4504                                                           .getOperand(0))));
4505       }
4506     }
4507   }
4508
4509   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4510                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4511                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4512                                              OpVT, SrcOp)));
4513 }
4514
4515 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4516 /// shuffles.
4517 static SDValue
4518 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4519   SDValue V1 = SVOp->getOperand(0);
4520   SDValue V2 = SVOp->getOperand(1);
4521   DebugLoc dl = SVOp->getDebugLoc();
4522   EVT VT = SVOp->getValueType(0);
4523
4524   SmallVector<std::pair<int, int>, 8> Locs;
4525   Locs.resize(4);
4526   SmallVector<int, 8> Mask1(4U, -1);
4527   SmallVector<int, 8> PermMask;
4528   SVOp->getMask(PermMask);
4529
4530   unsigned NumHi = 0;
4531   unsigned NumLo = 0;
4532   for (unsigned i = 0; i != 4; ++i) {
4533     int Idx = PermMask[i];
4534     if (Idx < 0) {
4535       Locs[i] = std::make_pair(-1, -1);
4536     } else {
4537       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4538       if (Idx < 4) {
4539         Locs[i] = std::make_pair(0, NumLo);
4540         Mask1[NumLo] = Idx;
4541         NumLo++;
4542       } else {
4543         Locs[i] = std::make_pair(1, NumHi);
4544         if (2+NumHi < 4)
4545           Mask1[2+NumHi] = Idx;
4546         NumHi++;
4547       }
4548     }
4549   }
4550
4551   if (NumLo <= 2 && NumHi <= 2) {
4552     // If no more than two elements come from either vector. This can be
4553     // implemented with two shuffles. First shuffle gather the elements.
4554     // The second shuffle, which takes the first shuffle as both of its
4555     // vector operands, put the elements into the right order.
4556     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4557
4558     SmallVector<int, 8> Mask2(4U, -1);
4559
4560     for (unsigned i = 0; i != 4; ++i) {
4561       if (Locs[i].first == -1)
4562         continue;
4563       else {
4564         unsigned Idx = (i < 2) ? 0 : 4;
4565         Idx += Locs[i].first * 2 + Locs[i].second;
4566         Mask2[i] = Idx;
4567       }
4568     }
4569
4570     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4571   } else if (NumLo == 3 || NumHi == 3) {
4572     // Otherwise, we must have three elements from one vector, call it X, and
4573     // one element from the other, call it Y.  First, use a shufps to build an
4574     // intermediate vector with the one element from Y and the element from X
4575     // that will be in the same half in the final destination (the indexes don't
4576     // matter). Then, use a shufps to build the final vector, taking the half
4577     // containing the element from Y from the intermediate, and the other half
4578     // from X.
4579     if (NumHi == 3) {
4580       // Normalize it so the 3 elements come from V1.
4581       CommuteVectorShuffleMask(PermMask, VT);
4582       std::swap(V1, V2);
4583     }
4584
4585     // Find the element from V2.
4586     unsigned HiIndex;
4587     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4588       int Val = PermMask[HiIndex];
4589       if (Val < 0)
4590         continue;
4591       if (Val >= 4)
4592         break;
4593     }
4594
4595     Mask1[0] = PermMask[HiIndex];
4596     Mask1[1] = -1;
4597     Mask1[2] = PermMask[HiIndex^1];
4598     Mask1[3] = -1;
4599     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4600
4601     if (HiIndex >= 2) {
4602       Mask1[0] = PermMask[0];
4603       Mask1[1] = PermMask[1];
4604       Mask1[2] = HiIndex & 1 ? 6 : 4;
4605       Mask1[3] = HiIndex & 1 ? 4 : 6;
4606       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4607     } else {
4608       Mask1[0] = HiIndex & 1 ? 2 : 0;
4609       Mask1[1] = HiIndex & 1 ? 0 : 2;
4610       Mask1[2] = PermMask[2];
4611       Mask1[3] = PermMask[3];
4612       if (Mask1[2] >= 0)
4613         Mask1[2] += 4;
4614       if (Mask1[3] >= 0)
4615         Mask1[3] += 4;
4616       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4617     }
4618   }
4619
4620   // Break it into (shuffle shuffle_hi, shuffle_lo).
4621   Locs.clear();
4622   SmallVector<int,8> LoMask(4U, -1);
4623   SmallVector<int,8> HiMask(4U, -1);
4624
4625   SmallVector<int,8> *MaskPtr = &LoMask;
4626   unsigned MaskIdx = 0;
4627   unsigned LoIdx = 0;
4628   unsigned HiIdx = 2;
4629   for (unsigned i = 0; i != 4; ++i) {
4630     if (i == 2) {
4631       MaskPtr = &HiMask;
4632       MaskIdx = 1;
4633       LoIdx = 0;
4634       HiIdx = 2;
4635     }
4636     int Idx = PermMask[i];
4637     if (Idx < 0) {
4638       Locs[i] = std::make_pair(-1, -1);
4639     } else if (Idx < 4) {
4640       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4641       (*MaskPtr)[LoIdx] = Idx;
4642       LoIdx++;
4643     } else {
4644       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4645       (*MaskPtr)[HiIdx] = Idx;
4646       HiIdx++;
4647     }
4648   }
4649
4650   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4651   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4652   SmallVector<int, 8> MaskOps;
4653   for (unsigned i = 0; i != 4; ++i) {
4654     if (Locs[i].first == -1) {
4655       MaskOps.push_back(-1);
4656     } else {
4657       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4658       MaskOps.push_back(Idx);
4659     }
4660   }
4661   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4662 }
4663
4664 SDValue
4665 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4667   SDValue V1 = Op.getOperand(0);
4668   SDValue V2 = Op.getOperand(1);
4669   EVT VT = Op.getValueType();
4670   DebugLoc dl = Op.getDebugLoc();
4671   unsigned NumElems = VT.getVectorNumElements();
4672   bool isMMX = VT.getSizeInBits() == 64;
4673   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4674   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4675   bool V1IsSplat = false;
4676   bool V2IsSplat = false;
4677
4678   if (isZeroShuffle(SVOp))
4679     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4680
4681   // Promote splats to v4f32.
4682   if (SVOp->isSplat()) {
4683     if (isMMX || NumElems < 4)
4684       return Op;
4685     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4686   }
4687
4688   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4689   // do it!
4690   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4691     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4692     if (NewOp.getNode())
4693       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4694                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4695   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4696     // FIXME: Figure out a cleaner way to do this.
4697     // Try to make use of movq to zero out the top part.
4698     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4699       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4700       if (NewOp.getNode()) {
4701         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4702           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4703                               DAG, Subtarget, dl);
4704       }
4705     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4706       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4707       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4708         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4709                             DAG, Subtarget, dl);
4710     }
4711   }
4712
4713   if (X86::isPSHUFDMask(SVOp))
4714     return Op;
4715
4716   // Check if this can be converted into a logical shift.
4717   bool isLeft = false;
4718   unsigned ShAmt = 0;
4719   SDValue ShVal;
4720   bool isShift = getSubtarget()->hasSSE2() &&
4721     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4722   if (isShift && ShVal.hasOneUse()) {
4723     // If the shifted value has multiple uses, it may be cheaper to use
4724     // v_set0 + movlhps or movhlps, etc.
4725     EVT EltVT = VT.getVectorElementType();
4726     ShAmt *= EltVT.getSizeInBits();
4727     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4728   }
4729
4730   if (X86::isMOVLMask(SVOp)) {
4731     if (V1IsUndef)
4732       return V2;
4733     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4734       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4735     if (!isMMX)
4736       return Op;
4737   }
4738
4739   // FIXME: fold these into legal mask.
4740   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4741                  X86::isMOVSLDUPMask(SVOp) ||
4742                  X86::isMOVHLPSMask(SVOp) ||
4743                  X86::isMOVLHPSMask(SVOp) ||
4744                  X86::isMOVLPMask(SVOp)))
4745     return Op;
4746
4747   if (ShouldXformToMOVHLPS(SVOp) ||
4748       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4749     return CommuteVectorShuffle(SVOp, DAG);
4750
4751   if (isShift) {
4752     // No better options. Use a vshl / vsrl.
4753     EVT EltVT = VT.getVectorElementType();
4754     ShAmt *= EltVT.getSizeInBits();
4755     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4756   }
4757
4758   bool Commuted = false;
4759   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4760   // 1,1,1,1 -> v8i16 though.
4761   V1IsSplat = isSplatVector(V1.getNode());
4762   V2IsSplat = isSplatVector(V2.getNode());
4763
4764   // Canonicalize the splat or undef, if present, to be on the RHS.
4765   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4766     Op = CommuteVectorShuffle(SVOp, DAG);
4767     SVOp = cast<ShuffleVectorSDNode>(Op);
4768     V1 = SVOp->getOperand(0);
4769     V2 = SVOp->getOperand(1);
4770     std::swap(V1IsSplat, V2IsSplat);
4771     std::swap(V1IsUndef, V2IsUndef);
4772     Commuted = true;
4773   }
4774
4775   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4776     // Shuffling low element of v1 into undef, just return v1.
4777     if (V2IsUndef)
4778       return V1;
4779     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4780     // the instruction selector will not match, so get a canonical MOVL with
4781     // swapped operands to undo the commute.
4782     return getMOVL(DAG, dl, VT, V2, V1);
4783   }
4784
4785   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4786       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4787       X86::isUNPCKLMask(SVOp) ||
4788       X86::isUNPCKHMask(SVOp))
4789     return Op;
4790
4791   if (V2IsSplat) {
4792     // Normalize mask so all entries that point to V2 points to its first
4793     // element then try to match unpck{h|l} again. If match, return a
4794     // new vector_shuffle with the corrected mask.
4795     SDValue NewMask = NormalizeMask(SVOp, DAG);
4796     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4797     if (NSVOp != SVOp) {
4798       if (X86::isUNPCKLMask(NSVOp, true)) {
4799         return NewMask;
4800       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4801         return NewMask;
4802       }
4803     }
4804   }
4805
4806   if (Commuted) {
4807     // Commute is back and try unpck* again.
4808     // FIXME: this seems wrong.
4809     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4810     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4811     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4812         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4813         X86::isUNPCKLMask(NewSVOp) ||
4814         X86::isUNPCKHMask(NewSVOp))
4815       return NewOp;
4816   }
4817
4818   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4819
4820   // Normalize the node to match x86 shuffle ops if needed
4821   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4822     return CommuteVectorShuffle(SVOp, DAG);
4823
4824   // Check for legal shuffle and return?
4825   SmallVector<int, 16> PermMask;
4826   SVOp->getMask(PermMask);
4827   if (isShuffleMaskLegal(PermMask, VT))
4828     return Op;
4829
4830   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4831   if (VT == MVT::v8i16) {
4832     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4833     if (NewOp.getNode())
4834       return NewOp;
4835   }
4836
4837   if (VT == MVT::v16i8) {
4838     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4839     if (NewOp.getNode())
4840       return NewOp;
4841   }
4842
4843   // Handle all 4 wide cases with a number of shuffles except for MMX.
4844   if (NumElems == 4 && !isMMX)
4845     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4846
4847   return SDValue();
4848 }
4849
4850 SDValue
4851 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4852                                                 SelectionDAG &DAG) const {
4853   EVT VT = Op.getValueType();
4854   DebugLoc dl = Op.getDebugLoc();
4855   if (VT.getSizeInBits() == 8) {
4856     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4857                                     Op.getOperand(0), Op.getOperand(1));
4858     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4859                                     DAG.getValueType(VT));
4860     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4861   } else if (VT.getSizeInBits() == 16) {
4862     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4863     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4864     if (Idx == 0)
4865       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4866                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4867                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4868                                                  MVT::v4i32,
4869                                                  Op.getOperand(0)),
4870                                      Op.getOperand(1)));
4871     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4872                                     Op.getOperand(0), Op.getOperand(1));
4873     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4874                                     DAG.getValueType(VT));
4875     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4876   } else if (VT == MVT::f32) {
4877     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4878     // the result back to FR32 register. It's only worth matching if the
4879     // result has a single use which is a store or a bitcast to i32.  And in
4880     // the case of a store, it's not worth it if the index is a constant 0,
4881     // because a MOVSSmr can be used instead, which is smaller and faster.
4882     if (!Op.hasOneUse())
4883       return SDValue();
4884     SDNode *User = *Op.getNode()->use_begin();
4885     if ((User->getOpcode() != ISD::STORE ||
4886          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4887           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4888         (User->getOpcode() != ISD::BIT_CONVERT ||
4889          User->getValueType(0) != MVT::i32))
4890       return SDValue();
4891     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4892                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4893                                               Op.getOperand(0)),
4894                                               Op.getOperand(1));
4895     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4896   } else if (VT == MVT::i32) {
4897     // ExtractPS works with constant index.
4898     if (isa<ConstantSDNode>(Op.getOperand(1)))
4899       return Op;
4900   }
4901   return SDValue();
4902 }
4903
4904
4905 SDValue
4906 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4907                                            SelectionDAG &DAG) const {
4908   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4909     return SDValue();
4910
4911   if (Subtarget->hasSSE41()) {
4912     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4913     if (Res.getNode())
4914       return Res;
4915   }
4916
4917   EVT VT = Op.getValueType();
4918   DebugLoc dl = Op.getDebugLoc();
4919   // TODO: handle v16i8.
4920   if (VT.getSizeInBits() == 16) {
4921     SDValue Vec = Op.getOperand(0);
4922     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4923     if (Idx == 0)
4924       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4925                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4926                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4927                                                  MVT::v4i32, Vec),
4928                                      Op.getOperand(1)));
4929     // Transform it so it match pextrw which produces a 32-bit result.
4930     EVT EltVT = MVT::i32;
4931     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4932                                     Op.getOperand(0), Op.getOperand(1));
4933     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4934                                     DAG.getValueType(VT));
4935     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4936   } else if (VT.getSizeInBits() == 32) {
4937     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4938     if (Idx == 0)
4939       return Op;
4940
4941     // SHUFPS the element to the lowest double word, then movss.
4942     int Mask[4] = { Idx, -1, -1, -1 };
4943     EVT VVT = Op.getOperand(0).getValueType();
4944     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4945                                        DAG.getUNDEF(VVT), Mask);
4946     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4947                        DAG.getIntPtrConstant(0));
4948   } else if (VT.getSizeInBits() == 64) {
4949     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4950     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4951     //        to match extract_elt for f64.
4952     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4953     if (Idx == 0)
4954       return Op;
4955
4956     // UNPCKHPD the element to the lowest double word, then movsd.
4957     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4958     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4959     int Mask[2] = { 1, -1 };
4960     EVT VVT = Op.getOperand(0).getValueType();
4961     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4962                                        DAG.getUNDEF(VVT), Mask);
4963     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4964                        DAG.getIntPtrConstant(0));
4965   }
4966
4967   return SDValue();
4968 }
4969
4970 SDValue
4971 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4972                                                SelectionDAG &DAG) const {
4973   EVT VT = Op.getValueType();
4974   EVT EltVT = VT.getVectorElementType();
4975   DebugLoc dl = Op.getDebugLoc();
4976
4977   SDValue N0 = Op.getOperand(0);
4978   SDValue N1 = Op.getOperand(1);
4979   SDValue N2 = Op.getOperand(2);
4980
4981   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4982       isa<ConstantSDNode>(N2)) {
4983     unsigned Opc;
4984     if (VT == MVT::v8i16)
4985       Opc = X86ISD::PINSRW;
4986     else if (VT == MVT::v4i16)
4987       Opc = X86ISD::MMX_PINSRW;
4988     else if (VT == MVT::v16i8)
4989       Opc = X86ISD::PINSRB;
4990     else
4991       Opc = X86ISD::PINSRB;
4992
4993     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4994     // argument.
4995     if (N1.getValueType() != MVT::i32)
4996       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4997     if (N2.getValueType() != MVT::i32)
4998       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4999     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5000   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5001     // Bits [7:6] of the constant are the source select.  This will always be
5002     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5003     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5004     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5005     // Bits [5:4] of the constant are the destination select.  This is the
5006     //  value of the incoming immediate.
5007     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5008     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5009     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5010     // Create this as a scalar to vector..
5011     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5012     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5013   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5014     // PINSR* works with constant index.
5015     return Op;
5016   }
5017   return SDValue();
5018 }
5019
5020 SDValue
5021 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5022   EVT VT = Op.getValueType();
5023   EVT EltVT = VT.getVectorElementType();
5024
5025   if (Subtarget->hasSSE41())
5026     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5027
5028   if (EltVT == MVT::i8)
5029     return SDValue();
5030
5031   DebugLoc dl = Op.getDebugLoc();
5032   SDValue N0 = Op.getOperand(0);
5033   SDValue N1 = Op.getOperand(1);
5034   SDValue N2 = Op.getOperand(2);
5035
5036   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5037     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5038     // as its second argument.
5039     if (N1.getValueType() != MVT::i32)
5040       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5041     if (N2.getValueType() != MVT::i32)
5042       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5043     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5044                        dl, VT, N0, N1, N2);
5045   }
5046   return SDValue();
5047 }
5048
5049 SDValue
5050 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5051   DebugLoc dl = Op.getDebugLoc();
5052   if (Op.getValueType() == MVT::v2f32)
5053     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5054                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5055                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5056                                                Op.getOperand(0))));
5057
5058   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5059     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5060
5061   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5062   EVT VT = MVT::v2i32;
5063   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5064   default: break;
5065   case MVT::v16i8:
5066   case MVT::v8i16:
5067     VT = MVT::v4i32;
5068     break;
5069   }
5070   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5071                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5072 }
5073
5074 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5075 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5076 // one of the above mentioned nodes. It has to be wrapped because otherwise
5077 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5078 // be used to form addressing mode. These wrapped nodes will be selected
5079 // into MOV32ri.
5080 SDValue
5081 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5082   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5083
5084   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5085   // global base reg.
5086   unsigned char OpFlag = 0;
5087   unsigned WrapperKind = X86ISD::Wrapper;
5088   CodeModel::Model M = getTargetMachine().getCodeModel();
5089
5090   if (Subtarget->isPICStyleRIPRel() &&
5091       (M == CodeModel::Small || M == CodeModel::Kernel))
5092     WrapperKind = X86ISD::WrapperRIP;
5093   else if (Subtarget->isPICStyleGOT())
5094     OpFlag = X86II::MO_GOTOFF;
5095   else if (Subtarget->isPICStyleStubPIC())
5096     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5097
5098   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5099                                              CP->getAlignment(),
5100                                              CP->getOffset(), OpFlag);
5101   DebugLoc DL = CP->getDebugLoc();
5102   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5103   // With PIC, the address is actually $g + Offset.
5104   if (OpFlag) {
5105     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5106                          DAG.getNode(X86ISD::GlobalBaseReg,
5107                                      DebugLoc(), getPointerTy()),
5108                          Result);
5109   }
5110
5111   return Result;
5112 }
5113
5114 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5115   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5116
5117   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5118   // global base reg.
5119   unsigned char OpFlag = 0;
5120   unsigned WrapperKind = X86ISD::Wrapper;
5121   CodeModel::Model M = getTargetMachine().getCodeModel();
5122
5123   if (Subtarget->isPICStyleRIPRel() &&
5124       (M == CodeModel::Small || M == CodeModel::Kernel))
5125     WrapperKind = X86ISD::WrapperRIP;
5126   else if (Subtarget->isPICStyleGOT())
5127     OpFlag = X86II::MO_GOTOFF;
5128   else if (Subtarget->isPICStyleStubPIC())
5129     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5130
5131   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5132                                           OpFlag);
5133   DebugLoc DL = JT->getDebugLoc();
5134   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5135
5136   // With PIC, the address is actually $g + Offset.
5137   if (OpFlag) {
5138     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5139                          DAG.getNode(X86ISD::GlobalBaseReg,
5140                                      DebugLoc(), getPointerTy()),
5141                          Result);
5142   }
5143
5144   return Result;
5145 }
5146
5147 SDValue
5148 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5149   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5150
5151   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5152   // global base reg.
5153   unsigned char OpFlag = 0;
5154   unsigned WrapperKind = X86ISD::Wrapper;
5155   CodeModel::Model M = getTargetMachine().getCodeModel();
5156
5157   if (Subtarget->isPICStyleRIPRel() &&
5158       (M == CodeModel::Small || M == CodeModel::Kernel))
5159     WrapperKind = X86ISD::WrapperRIP;
5160   else if (Subtarget->isPICStyleGOT())
5161     OpFlag = X86II::MO_GOTOFF;
5162   else if (Subtarget->isPICStyleStubPIC())
5163     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5164
5165   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5166
5167   DebugLoc DL = Op.getDebugLoc();
5168   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5169
5170
5171   // With PIC, the address is actually $g + Offset.
5172   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5173       !Subtarget->is64Bit()) {
5174     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5175                          DAG.getNode(X86ISD::GlobalBaseReg,
5176                                      DebugLoc(), getPointerTy()),
5177                          Result);
5178   }
5179
5180   return Result;
5181 }
5182
5183 SDValue
5184 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5185   // Create the TargetBlockAddressAddress node.
5186   unsigned char OpFlags =
5187     Subtarget->ClassifyBlockAddressReference();
5188   CodeModel::Model M = getTargetMachine().getCodeModel();
5189   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5190   DebugLoc dl = Op.getDebugLoc();
5191   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5192                                        /*isTarget=*/true, OpFlags);
5193
5194   if (Subtarget->isPICStyleRIPRel() &&
5195       (M == CodeModel::Small || M == CodeModel::Kernel))
5196     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5197   else
5198     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5199
5200   // With PIC, the address is actually $g + Offset.
5201   if (isGlobalRelativeToPICBase(OpFlags)) {
5202     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5203                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5204                          Result);
5205   }
5206
5207   return Result;
5208 }
5209
5210 SDValue
5211 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5212                                       int64_t Offset,
5213                                       SelectionDAG &DAG) const {
5214   // Create the TargetGlobalAddress node, folding in the constant
5215   // offset if it is legal.
5216   unsigned char OpFlags =
5217     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5218   CodeModel::Model M = getTargetMachine().getCodeModel();
5219   SDValue Result;
5220   if (OpFlags == X86II::MO_NO_FLAG &&
5221       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5222     // A direct static reference to a global.
5223     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5224     Offset = 0;
5225   } else {
5226     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5227   }
5228
5229   if (Subtarget->isPICStyleRIPRel() &&
5230       (M == CodeModel::Small || M == CodeModel::Kernel))
5231     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5232   else
5233     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5234
5235   // With PIC, the address is actually $g + Offset.
5236   if (isGlobalRelativeToPICBase(OpFlags)) {
5237     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5238                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5239                          Result);
5240   }
5241
5242   // For globals that require a load from a stub to get the address, emit the
5243   // load.
5244   if (isGlobalStubReference(OpFlags))
5245     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5246                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5247
5248   // If there was a non-zero offset that we didn't fold, create an explicit
5249   // addition for it.
5250   if (Offset != 0)
5251     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5252                          DAG.getConstant(Offset, getPointerTy()));
5253
5254   return Result;
5255 }
5256
5257 SDValue
5258 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5259   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5260   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5261   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5262 }
5263
5264 static SDValue
5265 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5266            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5267            unsigned char OperandFlags) {
5268   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5269   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5270   DebugLoc dl = GA->getDebugLoc();
5271   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5272                                            GA->getValueType(0),
5273                                            GA->getOffset(),
5274                                            OperandFlags);
5275   if (InFlag) {
5276     SDValue Ops[] = { Chain,  TGA, *InFlag };
5277     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5278   } else {
5279     SDValue Ops[]  = { Chain, TGA };
5280     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5281   }
5282
5283   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5284   MFI->setAdjustsStack(true);
5285
5286   SDValue Flag = Chain.getValue(1);
5287   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5288 }
5289
5290 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5291 static SDValue
5292 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5293                                 const EVT PtrVT) {
5294   SDValue InFlag;
5295   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5296   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5297                                      DAG.getNode(X86ISD::GlobalBaseReg,
5298                                                  DebugLoc(), PtrVT), InFlag);
5299   InFlag = Chain.getValue(1);
5300
5301   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5302 }
5303
5304 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5305 static SDValue
5306 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5307                                 const EVT PtrVT) {
5308   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5309                     X86::RAX, X86II::MO_TLSGD);
5310 }
5311
5312 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5313 // "local exec" model.
5314 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5315                                    const EVT PtrVT, TLSModel::Model model,
5316                                    bool is64Bit) {
5317   DebugLoc dl = GA->getDebugLoc();
5318   // Get the Thread Pointer
5319   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5320                              DebugLoc(), PtrVT,
5321                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5322                                              MVT::i32));
5323
5324   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5325                                       NULL, 0, false, false, 0);
5326
5327   unsigned char OperandFlags = 0;
5328   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5329   // initialexec.
5330   unsigned WrapperKind = X86ISD::Wrapper;
5331   if (model == TLSModel::LocalExec) {
5332     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5333   } else if (is64Bit) {
5334     assert(model == TLSModel::InitialExec);
5335     OperandFlags = X86II::MO_GOTTPOFF;
5336     WrapperKind = X86ISD::WrapperRIP;
5337   } else {
5338     assert(model == TLSModel::InitialExec);
5339     OperandFlags = X86II::MO_INDNTPOFF;
5340   }
5341
5342   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5343   // exec)
5344   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5345                                            GA->getOffset(), OperandFlags);
5346   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5347
5348   if (model == TLSModel::InitialExec)
5349     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5350                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5351
5352   // The address of the thread local variable is the add of the thread
5353   // pointer with the offset of the variable.
5354   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5355 }
5356
5357 SDValue
5358 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5359   // TODO: implement the "local dynamic" model
5360   // TODO: implement the "initial exec"model for pic executables
5361   assert(Subtarget->isTargetELF() &&
5362          "TLS not implemented for non-ELF targets");
5363   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5364   const GlobalValue *GV = GA->getGlobal();
5365
5366   // If GV is an alias then use the aliasee for determining
5367   // thread-localness.
5368   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5369     GV = GA->resolveAliasedGlobal(false);
5370
5371   TLSModel::Model model = getTLSModel(GV,
5372                                       getTargetMachine().getRelocationModel());
5373
5374   switch (model) {
5375   case TLSModel::GeneralDynamic:
5376   case TLSModel::LocalDynamic: // not implemented
5377     if (Subtarget->is64Bit())
5378       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5379     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5380
5381   case TLSModel::InitialExec:
5382   case TLSModel::LocalExec:
5383     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5384                                Subtarget->is64Bit());
5385   }
5386
5387   llvm_unreachable("Unreachable");
5388   return SDValue();
5389 }
5390
5391
5392 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5393 /// take a 2 x i32 value to shift plus a shift amount.
5394 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5395   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5396   EVT VT = Op.getValueType();
5397   unsigned VTBits = VT.getSizeInBits();
5398   DebugLoc dl = Op.getDebugLoc();
5399   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5400   SDValue ShOpLo = Op.getOperand(0);
5401   SDValue ShOpHi = Op.getOperand(1);
5402   SDValue ShAmt  = Op.getOperand(2);
5403   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5404                                      DAG.getConstant(VTBits - 1, MVT::i8))
5405                        : DAG.getConstant(0, VT);
5406
5407   SDValue Tmp2, Tmp3;
5408   if (Op.getOpcode() == ISD::SHL_PARTS) {
5409     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5410     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5411   } else {
5412     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5413     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5414   }
5415
5416   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5417                                 DAG.getConstant(VTBits, MVT::i8));
5418   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5419                              AndNode, DAG.getConstant(0, MVT::i8));
5420
5421   SDValue Hi, Lo;
5422   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5423   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5424   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5425
5426   if (Op.getOpcode() == ISD::SHL_PARTS) {
5427     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5428     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5429   } else {
5430     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5431     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5432   }
5433
5434   SDValue Ops[2] = { Lo, Hi };
5435   return DAG.getMergeValues(Ops, 2, dl);
5436 }
5437
5438 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5439                                            SelectionDAG &DAG) const {
5440   EVT SrcVT = Op.getOperand(0).getValueType();
5441
5442   if (SrcVT.isVector()) {
5443     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5444       return Op;
5445     }
5446     return SDValue();
5447   }
5448
5449   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5450          "Unknown SINT_TO_FP to lower!");
5451
5452   // These are really Legal; return the operand so the caller accepts it as
5453   // Legal.
5454   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5455     return Op;
5456   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5457       Subtarget->is64Bit()) {
5458     return Op;
5459   }
5460
5461   DebugLoc dl = Op.getDebugLoc();
5462   unsigned Size = SrcVT.getSizeInBits()/8;
5463   MachineFunction &MF = DAG.getMachineFunction();
5464   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5465   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5466   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5467                                StackSlot,
5468                                PseudoSourceValue::getFixedStack(SSFI), 0,
5469                                false, false, 0);
5470   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5471 }
5472
5473 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5474                                      SDValue StackSlot, 
5475                                      SelectionDAG &DAG) const {
5476   // Build the FILD
5477   DebugLoc dl = Op.getDebugLoc();
5478   SDVTList Tys;
5479   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5480   if (useSSE)
5481     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5482   else
5483     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5484   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5485   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5486                                Tys, Ops, array_lengthof(Ops));
5487
5488   if (useSSE) {
5489     Chain = Result.getValue(1);
5490     SDValue InFlag = Result.getValue(2);
5491
5492     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5493     // shouldn't be necessary except that RFP cannot be live across
5494     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5495     MachineFunction &MF = DAG.getMachineFunction();
5496     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5497     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5498     Tys = DAG.getVTList(MVT::Other);
5499     SDValue Ops[] = {
5500       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5501     };
5502     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5503     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5504                          PseudoSourceValue::getFixedStack(SSFI), 0,
5505                          false, false, 0);
5506   }
5507
5508   return Result;
5509 }
5510
5511 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5512 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5513                                                SelectionDAG &DAG) const {
5514   // This algorithm is not obvious. Here it is in C code, more or less:
5515   /*
5516     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5517       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5518       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5519
5520       // Copy ints to xmm registers.
5521       __m128i xh = _mm_cvtsi32_si128( hi );
5522       __m128i xl = _mm_cvtsi32_si128( lo );
5523
5524       // Combine into low half of a single xmm register.
5525       __m128i x = _mm_unpacklo_epi32( xh, xl );
5526       __m128d d;
5527       double sd;
5528
5529       // Merge in appropriate exponents to give the integer bits the right
5530       // magnitude.
5531       x = _mm_unpacklo_epi32( x, exp );
5532
5533       // Subtract away the biases to deal with the IEEE-754 double precision
5534       // implicit 1.
5535       d = _mm_sub_pd( (__m128d) x, bias );
5536
5537       // All conversions up to here are exact. The correctly rounded result is
5538       // calculated using the current rounding mode using the following
5539       // horizontal add.
5540       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5541       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5542                                 // store doesn't really need to be here (except
5543                                 // maybe to zero the other double)
5544       return sd;
5545     }
5546   */
5547
5548   DebugLoc dl = Op.getDebugLoc();
5549   LLVMContext *Context = DAG.getContext();
5550
5551   // Build some magic constants.
5552   std::vector<Constant*> CV0;
5553   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5554   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5555   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5556   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5557   Constant *C0 = ConstantVector::get(CV0);
5558   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5559
5560   std::vector<Constant*> CV1;
5561   CV1.push_back(
5562     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5563   CV1.push_back(
5564     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5565   Constant *C1 = ConstantVector::get(CV1);
5566   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5567
5568   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5569                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5570                                         Op.getOperand(0),
5571                                         DAG.getIntPtrConstant(1)));
5572   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5573                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5574                                         Op.getOperand(0),
5575                                         DAG.getIntPtrConstant(0)));
5576   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5577   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5578                               PseudoSourceValue::getConstantPool(), 0,
5579                               false, false, 16);
5580   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5581   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5582   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5583                               PseudoSourceValue::getConstantPool(), 0,
5584                               false, false, 16);
5585   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5586
5587   // Add the halves; easiest way is to swap them into another reg first.
5588   int ShufMask[2] = { 1, -1 };
5589   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5590                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5591   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5592   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5593                      DAG.getIntPtrConstant(0));
5594 }
5595
5596 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5597 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5598                                                SelectionDAG &DAG) const {
5599   DebugLoc dl = Op.getDebugLoc();
5600   // FP constant to bias correct the final result.
5601   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5602                                    MVT::f64);
5603
5604   // Load the 32-bit value into an XMM register.
5605   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5606                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5607                                          Op.getOperand(0),
5608                                          DAG.getIntPtrConstant(0)));
5609
5610   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5611                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5612                      DAG.getIntPtrConstant(0));
5613
5614   // Or the load with the bias.
5615   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5616                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5617                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5618                                                    MVT::v2f64, Load)),
5619                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5620                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5621                                                    MVT::v2f64, Bias)));
5622   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5623                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5624                    DAG.getIntPtrConstant(0));
5625
5626   // Subtract the bias.
5627   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5628
5629   // Handle final rounding.
5630   EVT DestVT = Op.getValueType();
5631
5632   if (DestVT.bitsLT(MVT::f64)) {
5633     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5634                        DAG.getIntPtrConstant(0));
5635   } else if (DestVT.bitsGT(MVT::f64)) {
5636     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5637   }
5638
5639   // Handle final rounding.
5640   return Sub;
5641 }
5642
5643 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5644                                            SelectionDAG &DAG) const {
5645   SDValue N0 = Op.getOperand(0);
5646   DebugLoc dl = Op.getDebugLoc();
5647
5648   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5649   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5650   // the optimization here.
5651   if (DAG.SignBitIsZero(N0))
5652     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5653
5654   EVT SrcVT = N0.getValueType();
5655   EVT DstVT = Op.getValueType();
5656   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5657     return LowerUINT_TO_FP_i64(Op, DAG);
5658   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5659     return LowerUINT_TO_FP_i32(Op, DAG);
5660
5661   // Make a 64-bit buffer, and use it to build an FILD.
5662   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5663   if (SrcVT == MVT::i32) {
5664     SDValue WordOff = DAG.getConstant(4, getPointerTy());
5665     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5666                                      getPointerTy(), StackSlot, WordOff);
5667     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5668                                   StackSlot, NULL, 0, false, false, 0);
5669     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5670                                   OffsetSlot, NULL, 0, false, false, 0);
5671     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5672     return Fild;
5673   }
5674
5675   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5676   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5677                                 StackSlot, NULL, 0, false, false, 0);
5678   // For i64 source, we need to add the appropriate power of 2 if the input
5679   // was negative.  This is the same as the optimization in
5680   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5681   // we must be careful to do the computation in x87 extended precision, not
5682   // in SSE. (The generic code can't know it's OK to do this, or how to.)
5683   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5684   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5685   SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5686
5687   APInt FF(32, 0x5F800000ULL);
5688
5689   // Check whether the sign bit is set.
5690   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5691                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5692                                  ISD::SETLT);
5693
5694   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5695   SDValue FudgePtr = DAG.getConstantPool(
5696                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5697                                          getPointerTy());
5698
5699   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5700   SDValue Zero = DAG.getIntPtrConstant(0);
5701   SDValue Four = DAG.getIntPtrConstant(4);
5702   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5703                                Zero, Four);
5704   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5705
5706   // Load the value out, extending it from f32 to f80.
5707   // FIXME: Avoid the extend by constructing the right constant pool?
5708   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5709                                  FudgePtr, PseudoSourceValue::getConstantPool(),
5710                                  0, MVT::f32, false, false, 4);
5711   // Extend everything to 80 bits to force it to be done on x87.
5712   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5713   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5714 }
5715
5716 std::pair<SDValue,SDValue> X86TargetLowering::
5717 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5718   DebugLoc dl = Op.getDebugLoc();
5719
5720   EVT DstTy = Op.getValueType();
5721
5722   if (!IsSigned) {
5723     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5724     DstTy = MVT::i64;
5725   }
5726
5727   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5728          DstTy.getSimpleVT() >= MVT::i16 &&
5729          "Unknown FP_TO_SINT to lower!");
5730
5731   // These are really Legal.
5732   if (DstTy == MVT::i32 &&
5733       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5734     return std::make_pair(SDValue(), SDValue());
5735   if (Subtarget->is64Bit() &&
5736       DstTy == MVT::i64 &&
5737       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5738     return std::make_pair(SDValue(), SDValue());
5739
5740   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5741   // stack slot.
5742   MachineFunction &MF = DAG.getMachineFunction();
5743   unsigned MemSize = DstTy.getSizeInBits()/8;
5744   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5745   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5746
5747   unsigned Opc;
5748   switch (DstTy.getSimpleVT().SimpleTy) {
5749   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5750   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5751   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5752   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5753   }
5754
5755   SDValue Chain = DAG.getEntryNode();
5756   SDValue Value = Op.getOperand(0);
5757   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5758     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5759     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5760                          PseudoSourceValue::getFixedStack(SSFI), 0,
5761                          false, false, 0);
5762     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5763     SDValue Ops[] = {
5764       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5765     };
5766     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5767     Chain = Value.getValue(1);
5768     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5769     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5770   }
5771
5772   // Build the FP_TO_INT*_IN_MEM
5773   SDValue Ops[] = { Chain, Value, StackSlot };
5774   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5775
5776   return std::make_pair(FIST, StackSlot);
5777 }
5778
5779 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5780                                            SelectionDAG &DAG) const {
5781   if (Op.getValueType().isVector()) {
5782     if (Op.getValueType() == MVT::v2i32 &&
5783         Op.getOperand(0).getValueType() == MVT::v2f64) {
5784       return Op;
5785     }
5786     return SDValue();
5787   }
5788
5789   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5790   SDValue FIST = Vals.first, StackSlot = Vals.second;
5791   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5792   if (FIST.getNode() == 0) return Op;
5793
5794   // Load the result.
5795   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5796                      FIST, StackSlot, NULL, 0, false, false, 0);
5797 }
5798
5799 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5800                                            SelectionDAG &DAG) const {
5801   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5802   SDValue FIST = Vals.first, StackSlot = Vals.second;
5803   assert(FIST.getNode() && "Unexpected failure");
5804
5805   // Load the result.
5806   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5807                      FIST, StackSlot, NULL, 0, false, false, 0);
5808 }
5809
5810 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5811                                      SelectionDAG &DAG) const {
5812   LLVMContext *Context = DAG.getContext();
5813   DebugLoc dl = Op.getDebugLoc();
5814   EVT VT = Op.getValueType();
5815   EVT EltVT = VT;
5816   if (VT.isVector())
5817     EltVT = VT.getVectorElementType();
5818   std::vector<Constant*> CV;
5819   if (EltVT == MVT::f64) {
5820     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5821     CV.push_back(C);
5822     CV.push_back(C);
5823   } else {
5824     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5825     CV.push_back(C);
5826     CV.push_back(C);
5827     CV.push_back(C);
5828     CV.push_back(C);
5829   }
5830   Constant *C = ConstantVector::get(CV);
5831   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5832   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5833                              PseudoSourceValue::getConstantPool(), 0,
5834                              false, false, 16);
5835   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5836 }
5837
5838 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5839   LLVMContext *Context = DAG.getContext();
5840   DebugLoc dl = Op.getDebugLoc();
5841   EVT VT = Op.getValueType();
5842   EVT EltVT = VT;
5843   if (VT.isVector())
5844     EltVT = VT.getVectorElementType();
5845   std::vector<Constant*> CV;
5846   if (EltVT == MVT::f64) {
5847     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5848     CV.push_back(C);
5849     CV.push_back(C);
5850   } else {
5851     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5852     CV.push_back(C);
5853     CV.push_back(C);
5854     CV.push_back(C);
5855     CV.push_back(C);
5856   }
5857   Constant *C = ConstantVector::get(CV);
5858   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5859   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5860                              PseudoSourceValue::getConstantPool(), 0,
5861                              false, false, 16);
5862   if (VT.isVector()) {
5863     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5864                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5865                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5866                                 Op.getOperand(0)),
5867                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5868   } else {
5869     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5870   }
5871 }
5872
5873 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5874   LLVMContext *Context = DAG.getContext();
5875   SDValue Op0 = Op.getOperand(0);
5876   SDValue Op1 = Op.getOperand(1);
5877   DebugLoc dl = Op.getDebugLoc();
5878   EVT VT = Op.getValueType();
5879   EVT SrcVT = Op1.getValueType();
5880
5881   // If second operand is smaller, extend it first.
5882   if (SrcVT.bitsLT(VT)) {
5883     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5884     SrcVT = VT;
5885   }
5886   // And if it is bigger, shrink it first.
5887   if (SrcVT.bitsGT(VT)) {
5888     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5889     SrcVT = VT;
5890   }
5891
5892   // At this point the operands and the result should have the same
5893   // type, and that won't be f80 since that is not custom lowered.
5894
5895   // First get the sign bit of second operand.
5896   std::vector<Constant*> CV;
5897   if (SrcVT == MVT::f64) {
5898     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5899     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5900   } else {
5901     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5902     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5903     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5904     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5905   }
5906   Constant *C = ConstantVector::get(CV);
5907   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5908   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5909                               PseudoSourceValue::getConstantPool(), 0,
5910                               false, false, 16);
5911   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5912
5913   // Shift sign bit right or left if the two operands have different types.
5914   if (SrcVT.bitsGT(VT)) {
5915     // Op0 is MVT::f32, Op1 is MVT::f64.
5916     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5917     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5918                           DAG.getConstant(32, MVT::i32));
5919     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5920     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5921                           DAG.getIntPtrConstant(0));
5922   }
5923
5924   // Clear first operand sign bit.
5925   CV.clear();
5926   if (VT == MVT::f64) {
5927     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5928     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5929   } else {
5930     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5931     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5932     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5933     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5934   }
5935   C = ConstantVector::get(CV);
5936   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5937   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5938                               PseudoSourceValue::getConstantPool(), 0,
5939                               false, false, 16);
5940   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5941
5942   // Or the value with the sign bit.
5943   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5944 }
5945
5946 /// Emit nodes that will be selected as "test Op0,Op0", or something
5947 /// equivalent.
5948 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5949                                     SelectionDAG &DAG) const {
5950   DebugLoc dl = Op.getDebugLoc();
5951
5952   // CF and OF aren't always set the way we want. Determine which
5953   // of these we need.
5954   bool NeedCF = false;
5955   bool NeedOF = false;
5956   switch (X86CC) {
5957   case X86::COND_A: case X86::COND_AE:
5958   case X86::COND_B: case X86::COND_BE:
5959     NeedCF = true;
5960     break;
5961   case X86::COND_G: case X86::COND_GE:
5962   case X86::COND_L: case X86::COND_LE:
5963   case X86::COND_O: case X86::COND_NO:
5964     NeedOF = true;
5965     break;
5966   default: break;
5967   }
5968
5969   // See if we can use the EFLAGS value from the operand instead of
5970   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5971   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5972   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5973     unsigned Opcode = 0;
5974     unsigned NumOperands = 0;
5975     switch (Op.getNode()->getOpcode()) {
5976     case ISD::ADD:
5977       // Due to an isel shortcoming, be conservative if this add is
5978       // likely to be selected as part of a load-modify-store
5979       // instruction. When the root node in a match is a store, isel
5980       // doesn't know how to remap non-chain non-flag uses of other
5981       // nodes in the match, such as the ADD in this case. This leads
5982       // to the ADD being left around and reselected, with the result
5983       // being two adds in the output.  Alas, even if none our users
5984       // are stores, that doesn't prove we're O.K.  Ergo, if we have
5985       // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5986       // A better fix seems to require climbing the DAG back to the
5987       // root, and it doesn't seem to be worth the effort.
5988       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5989              UE = Op.getNode()->use_end(); UI != UE; ++UI)
5990         if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5991           goto default_case;
5992       if (ConstantSDNode *C =
5993             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5994         // An add of one will be selected as an INC.
5995         if (C->getAPIntValue() == 1) {
5996           Opcode = X86ISD::INC;
5997           NumOperands = 1;
5998           break;
5999         }
6000         // An add of negative one (subtract of one) will be selected as a DEC.
6001         if (C->getAPIntValue().isAllOnesValue()) {
6002           Opcode = X86ISD::DEC;
6003           NumOperands = 1;
6004           break;
6005         }
6006       }
6007       // Otherwise use a regular EFLAGS-setting add.
6008       Opcode = X86ISD::ADD;
6009       NumOperands = 2;
6010       break;
6011     case ISD::AND: {
6012       // If the primary and result isn't used, don't bother using X86ISD::AND,
6013       // because a TEST instruction will be better.
6014       bool NonFlagUse = false;
6015       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6016              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6017         SDNode *User = *UI;
6018         unsigned UOpNo = UI.getOperandNo();
6019         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6020           // Look pass truncate.
6021           UOpNo = User->use_begin().getOperandNo();
6022           User = *User->use_begin();
6023         }
6024         if (User->getOpcode() != ISD::BRCOND &&
6025             User->getOpcode() != ISD::SETCC &&
6026             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6027           NonFlagUse = true;
6028           break;
6029         }
6030       }
6031       if (!NonFlagUse)
6032         break;
6033     }
6034     // FALL THROUGH
6035     case ISD::SUB:
6036     case ISD::OR:
6037     case ISD::XOR:
6038       // Due to the ISEL shortcoming noted above, be conservative if this op is
6039       // likely to be selected as part of a load-modify-store instruction.
6040       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6041            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6042         if (UI->getOpcode() == ISD::STORE)
6043           goto default_case;
6044       // Otherwise use a regular EFLAGS-setting instruction.
6045       switch (Op.getNode()->getOpcode()) {
6046       case ISD::SUB: Opcode = X86ISD::SUB; break;
6047       case ISD::OR:  Opcode = X86ISD::OR;  break;
6048       case ISD::XOR: Opcode = X86ISD::XOR; break;
6049       case ISD::AND: Opcode = X86ISD::AND; break;
6050       default: llvm_unreachable("unexpected operator!");
6051       }
6052       NumOperands = 2;
6053       break;
6054     case X86ISD::ADD:
6055     case X86ISD::SUB:
6056     case X86ISD::INC:
6057     case X86ISD::DEC:
6058     case X86ISD::OR:
6059     case X86ISD::XOR:
6060     case X86ISD::AND:
6061       return SDValue(Op.getNode(), 1);
6062     default:
6063     default_case:
6064       break;
6065     }
6066     if (Opcode != 0) {
6067       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6068       SmallVector<SDValue, 4> Ops;
6069       for (unsigned i = 0; i != NumOperands; ++i)
6070         Ops.push_back(Op.getOperand(i));
6071       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6072       DAG.ReplaceAllUsesWith(Op, New);
6073       return SDValue(New.getNode(), 1);
6074     }
6075   }
6076
6077   // Otherwise just emit a CMP with 0, which is the TEST pattern.
6078   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6079                      DAG.getConstant(0, Op.getValueType()));
6080 }
6081
6082 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6083 /// equivalent.
6084 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6085                                    SelectionDAG &DAG) const {
6086   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6087     if (C->getAPIntValue() == 0)
6088       return EmitTest(Op0, X86CC, DAG);
6089
6090   DebugLoc dl = Op0.getDebugLoc();
6091   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6092 }
6093
6094 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6095 /// if it's possible.
6096 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6097                                      DebugLoc dl, SelectionDAG &DAG) const {
6098   SDValue Op0 = And.getOperand(0);
6099   SDValue Op1 = And.getOperand(1);
6100   if (Op0.getOpcode() == ISD::TRUNCATE)
6101     Op0 = Op0.getOperand(0);
6102   if (Op1.getOpcode() == ISD::TRUNCATE)
6103     Op1 = Op1.getOperand(0);
6104
6105   SDValue LHS, RHS;
6106   if (Op1.getOpcode() == ISD::SHL) {
6107     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6108       if (And10C->getZExtValue() == 1) {
6109         LHS = Op0;
6110         RHS = Op1.getOperand(1);
6111       }
6112   } else if (Op0.getOpcode() == ISD::SHL) {
6113     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6114       if (And00C->getZExtValue() == 1) {
6115         LHS = Op1;
6116         RHS = Op0.getOperand(1);
6117       }
6118   } else if (Op1.getOpcode() == ISD::Constant) {
6119     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6120     SDValue AndLHS = Op0;
6121     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6122       LHS = AndLHS.getOperand(0);
6123       RHS = AndLHS.getOperand(1);
6124     }
6125   }
6126
6127   if (LHS.getNode()) {
6128     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6129     // instruction.  Since the shift amount is in-range-or-undefined, we know
6130     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6131     // the encoding for the i16 version is larger than the i32 version.
6132     // Also promote i16 to i32 for performance / code size reason.
6133     if (LHS.getValueType() == MVT::i8 ||
6134         LHS.getValueType() == MVT::i16)
6135       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6136
6137     // If the operand types disagree, extend the shift amount to match.  Since
6138     // BT ignores high bits (like shifts) we can use anyextend.
6139     if (LHS.getValueType() != RHS.getValueType())
6140       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6141
6142     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6143     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6144     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6145                        DAG.getConstant(Cond, MVT::i8), BT);
6146   }
6147
6148   return SDValue();
6149 }
6150
6151 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6152   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6153   SDValue Op0 = Op.getOperand(0);
6154   SDValue Op1 = Op.getOperand(1);
6155   DebugLoc dl = Op.getDebugLoc();
6156   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6157
6158   // Optimize to BT if possible.
6159   // Lower (X & (1 << N)) == 0 to BT(X, N).
6160   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6161   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6162   if (Op0.getOpcode() == ISD::AND &&
6163       Op0.hasOneUse() &&
6164       Op1.getOpcode() == ISD::Constant &&
6165       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6166       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6167     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6168     if (NewSetCC.getNode())
6169       return NewSetCC;
6170   }
6171
6172   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6173   if (Op0.getOpcode() == X86ISD::SETCC &&
6174       Op1.getOpcode() == ISD::Constant &&
6175       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6176        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6177       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6178     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6179     bool Invert = (CC == ISD::SETNE) ^
6180       cast<ConstantSDNode>(Op1)->isNullValue();
6181     if (Invert)
6182       CCode = X86::GetOppositeBranchCondition(CCode);
6183     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6184                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6185   }
6186
6187   bool isFP = Op1.getValueType().isFloatingPoint();
6188   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6189   if (X86CC == X86::COND_INVALID)
6190     return SDValue();
6191
6192   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6193
6194   // Use sbb x, x to materialize carry bit into a GPR.
6195   if (X86CC == X86::COND_B)
6196     return DAG.getNode(ISD::AND, dl, MVT::i8,
6197                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6198                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6199                        DAG.getConstant(1, MVT::i8));
6200
6201   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6202                      DAG.getConstant(X86CC, MVT::i8), Cond);
6203 }
6204
6205 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6206   SDValue Cond;
6207   SDValue Op0 = Op.getOperand(0);
6208   SDValue Op1 = Op.getOperand(1);
6209   SDValue CC = Op.getOperand(2);
6210   EVT VT = Op.getValueType();
6211   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6212   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6213   DebugLoc dl = Op.getDebugLoc();
6214
6215   if (isFP) {
6216     unsigned SSECC = 8;
6217     EVT VT0 = Op0.getValueType();
6218     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6219     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6220     bool Swap = false;
6221
6222     switch (SetCCOpcode) {
6223     default: break;
6224     case ISD::SETOEQ:
6225     case ISD::SETEQ:  SSECC = 0; break;
6226     case ISD::SETOGT:
6227     case ISD::SETGT: Swap = true; // Fallthrough
6228     case ISD::SETLT:
6229     case ISD::SETOLT: SSECC = 1; break;
6230     case ISD::SETOGE:
6231     case ISD::SETGE: Swap = true; // Fallthrough
6232     case ISD::SETLE:
6233     case ISD::SETOLE: SSECC = 2; break;
6234     case ISD::SETUO:  SSECC = 3; break;
6235     case ISD::SETUNE:
6236     case ISD::SETNE:  SSECC = 4; break;
6237     case ISD::SETULE: Swap = true;
6238     case ISD::SETUGE: SSECC = 5; break;
6239     case ISD::SETULT: Swap = true;
6240     case ISD::SETUGT: SSECC = 6; break;
6241     case ISD::SETO:   SSECC = 7; break;
6242     }
6243     if (Swap)
6244       std::swap(Op0, Op1);
6245
6246     // In the two special cases we can't handle, emit two comparisons.
6247     if (SSECC == 8) {
6248       if (SetCCOpcode == ISD::SETUEQ) {
6249         SDValue UNORD, EQ;
6250         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6251         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6252         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6253       }
6254       else if (SetCCOpcode == ISD::SETONE) {
6255         SDValue ORD, NEQ;
6256         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6257         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6258         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6259       }
6260       llvm_unreachable("Illegal FP comparison");
6261     }
6262     // Handle all other FP comparisons here.
6263     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6264   }
6265
6266   // We are handling one of the integer comparisons here.  Since SSE only has
6267   // GT and EQ comparisons for integer, swapping operands and multiple
6268   // operations may be required for some comparisons.
6269   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6270   bool Swap = false, Invert = false, FlipSigns = false;
6271
6272   switch (VT.getSimpleVT().SimpleTy) {
6273   default: break;
6274   case MVT::v8i8:
6275   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6276   case MVT::v4i16:
6277   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6278   case MVT::v2i32:
6279   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6280   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6281   }
6282
6283   switch (SetCCOpcode) {
6284   default: break;
6285   case ISD::SETNE:  Invert = true;
6286   case ISD::SETEQ:  Opc = EQOpc; break;
6287   case ISD::SETLT:  Swap = true;
6288   case ISD::SETGT:  Opc = GTOpc; break;
6289   case ISD::SETGE:  Swap = true;
6290   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6291   case ISD::SETULT: Swap = true;
6292   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6293   case ISD::SETUGE: Swap = true;
6294   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6295   }
6296   if (Swap)
6297     std::swap(Op0, Op1);
6298
6299   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6300   // bits of the inputs before performing those operations.
6301   if (FlipSigns) {
6302     EVT EltVT = VT.getVectorElementType();
6303     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6304                                       EltVT);
6305     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6306     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6307                                     SignBits.size());
6308     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6309     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6310   }
6311
6312   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6313
6314   // If the logical-not of the result is required, perform that now.
6315   if (Invert)
6316     Result = DAG.getNOT(dl, Result, VT);
6317
6318   return Result;
6319 }
6320
6321 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6322 static bool isX86LogicalCmp(SDValue Op) {
6323   unsigned Opc = Op.getNode()->getOpcode();
6324   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6325     return true;
6326   if (Op.getResNo() == 1 &&
6327       (Opc == X86ISD::ADD ||
6328        Opc == X86ISD::SUB ||
6329        Opc == X86ISD::SMUL ||
6330        Opc == X86ISD::UMUL ||
6331        Opc == X86ISD::INC ||
6332        Opc == X86ISD::DEC ||
6333        Opc == X86ISD::OR ||
6334        Opc == X86ISD::XOR ||
6335        Opc == X86ISD::AND))
6336     return true;
6337
6338   return false;
6339 }
6340
6341 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6342   bool addTest = true;
6343   SDValue Cond  = Op.getOperand(0);
6344   DebugLoc dl = Op.getDebugLoc();
6345   SDValue CC;
6346
6347   if (Cond.getOpcode() == ISD::SETCC) {
6348     SDValue NewCond = LowerSETCC(Cond, DAG);
6349     if (NewCond.getNode())
6350       Cond = NewCond;
6351   }
6352
6353   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6354   SDValue Op1 = Op.getOperand(1);
6355   SDValue Op2 = Op.getOperand(2);
6356   if (Cond.getOpcode() == X86ISD::SETCC &&
6357       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6358     SDValue Cmp = Cond.getOperand(1);
6359     if (Cmp.getOpcode() == X86ISD::CMP) {
6360       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6361       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6362       ConstantSDNode *RHSC =
6363         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6364       if (N1C && N1C->isAllOnesValue() &&
6365           N2C && N2C->isNullValue() &&
6366           RHSC && RHSC->isNullValue()) {
6367         SDValue CmpOp0 = Cmp.getOperand(0);
6368         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6369                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6370         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6371                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6372       }
6373     }
6374   }
6375
6376   // Look pass (and (setcc_carry (cmp ...)), 1).
6377   if (Cond.getOpcode() == ISD::AND &&
6378       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6379     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6380     if (C && C->getAPIntValue() == 1) 
6381       Cond = Cond.getOperand(0);
6382   }
6383
6384   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6385   // setting operand in place of the X86ISD::SETCC.
6386   if (Cond.getOpcode() == X86ISD::SETCC ||
6387       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6388     CC = Cond.getOperand(0);
6389
6390     SDValue Cmp = Cond.getOperand(1);
6391     unsigned Opc = Cmp.getOpcode();
6392     EVT VT = Op.getValueType();
6393
6394     bool IllegalFPCMov = false;
6395     if (VT.isFloatingPoint() && !VT.isVector() &&
6396         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6397       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6398
6399     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6400         Opc == X86ISD::BT) { // FIXME
6401       Cond = Cmp;
6402       addTest = false;
6403     }
6404   }
6405
6406   if (addTest) {
6407     // Look pass the truncate.
6408     if (Cond.getOpcode() == ISD::TRUNCATE)
6409       Cond = Cond.getOperand(0);
6410
6411     // We know the result of AND is compared against zero. Try to match
6412     // it to BT.
6413     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6414       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6415       if (NewSetCC.getNode()) {
6416         CC = NewSetCC.getOperand(0);
6417         Cond = NewSetCC.getOperand(1);
6418         addTest = false;
6419       }
6420     }
6421   }
6422
6423   if (addTest) {
6424     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6425     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6426   }
6427
6428   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6429   // condition is true.
6430   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6431   SDValue Ops[] = { Op2, Op1, CC, Cond };
6432   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6433 }
6434
6435 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6436 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6437 // from the AND / OR.
6438 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6439   Opc = Op.getOpcode();
6440   if (Opc != ISD::OR && Opc != ISD::AND)
6441     return false;
6442   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6443           Op.getOperand(0).hasOneUse() &&
6444           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6445           Op.getOperand(1).hasOneUse());
6446 }
6447
6448 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6449 // 1 and that the SETCC node has a single use.
6450 static bool isXor1OfSetCC(SDValue Op) {
6451   if (Op.getOpcode() != ISD::XOR)
6452     return false;
6453   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6454   if (N1C && N1C->getAPIntValue() == 1) {
6455     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6456       Op.getOperand(0).hasOneUse();
6457   }
6458   return false;
6459 }
6460
6461 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6462   bool addTest = true;
6463   SDValue Chain = Op.getOperand(0);
6464   SDValue Cond  = Op.getOperand(1);
6465   SDValue Dest  = Op.getOperand(2);
6466   DebugLoc dl = Op.getDebugLoc();
6467   SDValue CC;
6468
6469   if (Cond.getOpcode() == ISD::SETCC) {
6470     SDValue NewCond = LowerSETCC(Cond, DAG);
6471     if (NewCond.getNode())
6472       Cond = NewCond;
6473   }
6474 #if 0
6475   // FIXME: LowerXALUO doesn't handle these!!
6476   else if (Cond.getOpcode() == X86ISD::ADD  ||
6477            Cond.getOpcode() == X86ISD::SUB  ||
6478            Cond.getOpcode() == X86ISD::SMUL ||
6479            Cond.getOpcode() == X86ISD::UMUL)
6480     Cond = LowerXALUO(Cond, DAG);
6481 #endif
6482
6483   // Look pass (and (setcc_carry (cmp ...)), 1).
6484   if (Cond.getOpcode() == ISD::AND &&
6485       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6486     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6487     if (C && C->getAPIntValue() == 1) 
6488       Cond = Cond.getOperand(0);
6489   }
6490
6491   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6492   // setting operand in place of the X86ISD::SETCC.
6493   if (Cond.getOpcode() == X86ISD::SETCC ||
6494       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6495     CC = Cond.getOperand(0);
6496
6497     SDValue Cmp = Cond.getOperand(1);
6498     unsigned Opc = Cmp.getOpcode();
6499     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6500     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6501       Cond = Cmp;
6502       addTest = false;
6503     } else {
6504       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6505       default: break;
6506       case X86::COND_O:
6507       case X86::COND_B:
6508         // These can only come from an arithmetic instruction with overflow,
6509         // e.g. SADDO, UADDO.
6510         Cond = Cond.getNode()->getOperand(1);
6511         addTest = false;
6512         break;
6513       }
6514     }
6515   } else {
6516     unsigned CondOpc;
6517     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6518       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6519       if (CondOpc == ISD::OR) {
6520         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6521         // two branches instead of an explicit OR instruction with a
6522         // separate test.
6523         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6524             isX86LogicalCmp(Cmp)) {
6525           CC = Cond.getOperand(0).getOperand(0);
6526           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6527                               Chain, Dest, CC, Cmp);
6528           CC = Cond.getOperand(1).getOperand(0);
6529           Cond = Cmp;
6530           addTest = false;
6531         }
6532       } else { // ISD::AND
6533         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6534         // two branches instead of an explicit AND instruction with a
6535         // separate test. However, we only do this if this block doesn't
6536         // have a fall-through edge, because this requires an explicit
6537         // jmp when the condition is false.
6538         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6539             isX86LogicalCmp(Cmp) &&
6540             Op.getNode()->hasOneUse()) {
6541           X86::CondCode CCode =
6542             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6543           CCode = X86::GetOppositeBranchCondition(CCode);
6544           CC = DAG.getConstant(CCode, MVT::i8);
6545           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6546           // Look for an unconditional branch following this conditional branch.
6547           // We need this because we need to reverse the successors in order
6548           // to implement FCMP_OEQ.
6549           if (User.getOpcode() == ISD::BR) {
6550             SDValue FalseBB = User.getOperand(1);
6551             SDValue NewBR =
6552               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6553             assert(NewBR == User);
6554             Dest = FalseBB;
6555
6556             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6557                                 Chain, Dest, CC, Cmp);
6558             X86::CondCode CCode =
6559               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6560             CCode = X86::GetOppositeBranchCondition(CCode);
6561             CC = DAG.getConstant(CCode, MVT::i8);
6562             Cond = Cmp;
6563             addTest = false;
6564           }
6565         }
6566       }
6567     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6568       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6569       // It should be transformed during dag combiner except when the condition
6570       // is set by a arithmetics with overflow node.
6571       X86::CondCode CCode =
6572         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6573       CCode = X86::GetOppositeBranchCondition(CCode);
6574       CC = DAG.getConstant(CCode, MVT::i8);
6575       Cond = Cond.getOperand(0).getOperand(1);
6576       addTest = false;
6577     }
6578   }
6579
6580   if (addTest) {
6581     // Look pass the truncate.
6582     if (Cond.getOpcode() == ISD::TRUNCATE)
6583       Cond = Cond.getOperand(0);
6584
6585     // We know the result of AND is compared against zero. Try to match
6586     // it to BT.
6587     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6588       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6589       if (NewSetCC.getNode()) {
6590         CC = NewSetCC.getOperand(0);
6591         Cond = NewSetCC.getOperand(1);
6592         addTest = false;
6593       }
6594     }
6595   }
6596
6597   if (addTest) {
6598     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6599     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6600   }
6601   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6602                      Chain, Dest, CC, Cond);
6603 }
6604
6605
6606 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6607 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6608 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6609 // that the guard pages used by the OS virtual memory manager are allocated in
6610 // correct sequence.
6611 SDValue
6612 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6613                                            SelectionDAG &DAG) const {
6614   assert(Subtarget->isTargetCygMing() &&
6615          "This should be used only on Cygwin/Mingw targets");
6616   DebugLoc dl = Op.getDebugLoc();
6617
6618   // Get the inputs.
6619   SDValue Chain = Op.getOperand(0);
6620   SDValue Size  = Op.getOperand(1);
6621   // FIXME: Ensure alignment here
6622
6623   SDValue Flag;
6624
6625   EVT IntPtr = getPointerTy();
6626   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6627
6628   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6629   Flag = Chain.getValue(1);
6630
6631   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6632
6633   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6634   Flag = Chain.getValue(1);
6635
6636   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6637
6638   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6639   return DAG.getMergeValues(Ops1, 2, dl);
6640 }
6641
6642 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6643   MachineFunction &MF = DAG.getMachineFunction();
6644   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6645
6646   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6647   DebugLoc dl = Op.getDebugLoc();
6648
6649   if (!Subtarget->is64Bit()) {
6650     // vastart just stores the address of the VarArgsFrameIndex slot into the
6651     // memory location argument.
6652     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6653                                    getPointerTy());
6654     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6655                         false, false, 0);
6656   }
6657
6658   // __va_list_tag:
6659   //   gp_offset         (0 - 6 * 8)
6660   //   fp_offset         (48 - 48 + 8 * 16)
6661   //   overflow_arg_area (point to parameters coming in memory).
6662   //   reg_save_area
6663   SmallVector<SDValue, 8> MemOps;
6664   SDValue FIN = Op.getOperand(1);
6665   // Store gp_offset
6666   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6667                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6668                                                MVT::i32),
6669                                FIN, SV, 0, false, false, 0);
6670   MemOps.push_back(Store);
6671
6672   // Store fp_offset
6673   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6674                     FIN, DAG.getIntPtrConstant(4));
6675   Store = DAG.getStore(Op.getOperand(0), dl,
6676                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6677                                        MVT::i32),
6678                        FIN, SV, 0, false, false, 0);
6679   MemOps.push_back(Store);
6680
6681   // Store ptr to overflow_arg_area
6682   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6683                     FIN, DAG.getIntPtrConstant(4));
6684   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6685                                     getPointerTy());
6686   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6687                        false, false, 0);
6688   MemOps.push_back(Store);
6689
6690   // Store ptr to reg_save_area.
6691   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6692                     FIN, DAG.getIntPtrConstant(8));
6693   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6694                                     getPointerTy());
6695   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6696                        false, false, 0);
6697   MemOps.push_back(Store);
6698   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6699                      &MemOps[0], MemOps.size());
6700 }
6701
6702 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6703   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6704   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6705   SDValue Chain = Op.getOperand(0);
6706   SDValue SrcPtr = Op.getOperand(1);
6707   SDValue SrcSV = Op.getOperand(2);
6708
6709   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6710   return SDValue();
6711 }
6712
6713 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6714   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6715   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6716   SDValue Chain = Op.getOperand(0);
6717   SDValue DstPtr = Op.getOperand(1);
6718   SDValue SrcPtr = Op.getOperand(2);
6719   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6720   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6721   DebugLoc dl = Op.getDebugLoc();
6722
6723   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6724                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6725                        false, DstSV, 0, SrcSV, 0);
6726 }
6727
6728 SDValue
6729 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6730   DebugLoc dl = Op.getDebugLoc();
6731   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6732   switch (IntNo) {
6733   default: return SDValue();    // Don't custom lower most intrinsics.
6734   // Comparison intrinsics.
6735   case Intrinsic::x86_sse_comieq_ss:
6736   case Intrinsic::x86_sse_comilt_ss:
6737   case Intrinsic::x86_sse_comile_ss:
6738   case Intrinsic::x86_sse_comigt_ss:
6739   case Intrinsic::x86_sse_comige_ss:
6740   case Intrinsic::x86_sse_comineq_ss:
6741   case Intrinsic::x86_sse_ucomieq_ss:
6742   case Intrinsic::x86_sse_ucomilt_ss:
6743   case Intrinsic::x86_sse_ucomile_ss:
6744   case Intrinsic::x86_sse_ucomigt_ss:
6745   case Intrinsic::x86_sse_ucomige_ss:
6746   case Intrinsic::x86_sse_ucomineq_ss:
6747   case Intrinsic::x86_sse2_comieq_sd:
6748   case Intrinsic::x86_sse2_comilt_sd:
6749   case Intrinsic::x86_sse2_comile_sd:
6750   case Intrinsic::x86_sse2_comigt_sd:
6751   case Intrinsic::x86_sse2_comige_sd:
6752   case Intrinsic::x86_sse2_comineq_sd:
6753   case Intrinsic::x86_sse2_ucomieq_sd:
6754   case Intrinsic::x86_sse2_ucomilt_sd:
6755   case Intrinsic::x86_sse2_ucomile_sd:
6756   case Intrinsic::x86_sse2_ucomigt_sd:
6757   case Intrinsic::x86_sse2_ucomige_sd:
6758   case Intrinsic::x86_sse2_ucomineq_sd: {
6759     unsigned Opc = 0;
6760     ISD::CondCode CC = ISD::SETCC_INVALID;
6761     switch (IntNo) {
6762     default: break;
6763     case Intrinsic::x86_sse_comieq_ss:
6764     case Intrinsic::x86_sse2_comieq_sd:
6765       Opc = X86ISD::COMI;
6766       CC = ISD::SETEQ;
6767       break;
6768     case Intrinsic::x86_sse_comilt_ss:
6769     case Intrinsic::x86_sse2_comilt_sd:
6770       Opc = X86ISD::COMI;
6771       CC = ISD::SETLT;
6772       break;
6773     case Intrinsic::x86_sse_comile_ss:
6774     case Intrinsic::x86_sse2_comile_sd:
6775       Opc = X86ISD::COMI;
6776       CC = ISD::SETLE;
6777       break;
6778     case Intrinsic::x86_sse_comigt_ss:
6779     case Intrinsic::x86_sse2_comigt_sd:
6780       Opc = X86ISD::COMI;
6781       CC = ISD::SETGT;
6782       break;
6783     case Intrinsic::x86_sse_comige_ss:
6784     case Intrinsic::x86_sse2_comige_sd:
6785       Opc = X86ISD::COMI;
6786       CC = ISD::SETGE;
6787       break;
6788     case Intrinsic::x86_sse_comineq_ss:
6789     case Intrinsic::x86_sse2_comineq_sd:
6790       Opc = X86ISD::COMI;
6791       CC = ISD::SETNE;
6792       break;
6793     case Intrinsic::x86_sse_ucomieq_ss:
6794     case Intrinsic::x86_sse2_ucomieq_sd:
6795       Opc = X86ISD::UCOMI;
6796       CC = ISD::SETEQ;
6797       break;
6798     case Intrinsic::x86_sse_ucomilt_ss:
6799     case Intrinsic::x86_sse2_ucomilt_sd:
6800       Opc = X86ISD::UCOMI;
6801       CC = ISD::SETLT;
6802       break;
6803     case Intrinsic::x86_sse_ucomile_ss:
6804     case Intrinsic::x86_sse2_ucomile_sd:
6805       Opc = X86ISD::UCOMI;
6806       CC = ISD::SETLE;
6807       break;
6808     case Intrinsic::x86_sse_ucomigt_ss:
6809     case Intrinsic::x86_sse2_ucomigt_sd:
6810       Opc = X86ISD::UCOMI;
6811       CC = ISD::SETGT;
6812       break;
6813     case Intrinsic::x86_sse_ucomige_ss:
6814     case Intrinsic::x86_sse2_ucomige_sd:
6815       Opc = X86ISD::UCOMI;
6816       CC = ISD::SETGE;
6817       break;
6818     case Intrinsic::x86_sse_ucomineq_ss:
6819     case Intrinsic::x86_sse2_ucomineq_sd:
6820       Opc = X86ISD::UCOMI;
6821       CC = ISD::SETNE;
6822       break;
6823     }
6824
6825     SDValue LHS = Op.getOperand(1);
6826     SDValue RHS = Op.getOperand(2);
6827     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6828     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6829     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6830     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6831                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6832     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6833   }
6834   // ptest intrinsics. The intrinsic these come from are designed to return
6835   // an integer value, not just an instruction so lower it to the ptest
6836   // pattern and a setcc for the result.
6837   case Intrinsic::x86_sse41_ptestz:
6838   case Intrinsic::x86_sse41_ptestc:
6839   case Intrinsic::x86_sse41_ptestnzc:{
6840     unsigned X86CC = 0;
6841     switch (IntNo) {
6842     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6843     case Intrinsic::x86_sse41_ptestz:
6844       // ZF = 1
6845       X86CC = X86::COND_E;
6846       break;
6847     case Intrinsic::x86_sse41_ptestc:
6848       // CF = 1
6849       X86CC = X86::COND_B;
6850       break;
6851     case Intrinsic::x86_sse41_ptestnzc:
6852       // ZF and CF = 0
6853       X86CC = X86::COND_A;
6854       break;
6855     }
6856
6857     SDValue LHS = Op.getOperand(1);
6858     SDValue RHS = Op.getOperand(2);
6859     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6860     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6861     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6862     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6863   }
6864
6865   // Fix vector shift instructions where the last operand is a non-immediate
6866   // i32 value.
6867   case Intrinsic::x86_sse2_pslli_w:
6868   case Intrinsic::x86_sse2_pslli_d:
6869   case Intrinsic::x86_sse2_pslli_q:
6870   case Intrinsic::x86_sse2_psrli_w:
6871   case Intrinsic::x86_sse2_psrli_d:
6872   case Intrinsic::x86_sse2_psrli_q:
6873   case Intrinsic::x86_sse2_psrai_w:
6874   case Intrinsic::x86_sse2_psrai_d:
6875   case Intrinsic::x86_mmx_pslli_w:
6876   case Intrinsic::x86_mmx_pslli_d:
6877   case Intrinsic::x86_mmx_pslli_q:
6878   case Intrinsic::x86_mmx_psrli_w:
6879   case Intrinsic::x86_mmx_psrli_d:
6880   case Intrinsic::x86_mmx_psrli_q:
6881   case Intrinsic::x86_mmx_psrai_w:
6882   case Intrinsic::x86_mmx_psrai_d: {
6883     SDValue ShAmt = Op.getOperand(2);
6884     if (isa<ConstantSDNode>(ShAmt))
6885       return SDValue();
6886
6887     unsigned NewIntNo = 0;
6888     EVT ShAmtVT = MVT::v4i32;
6889     switch (IntNo) {
6890     case Intrinsic::x86_sse2_pslli_w:
6891       NewIntNo = Intrinsic::x86_sse2_psll_w;
6892       break;
6893     case Intrinsic::x86_sse2_pslli_d:
6894       NewIntNo = Intrinsic::x86_sse2_psll_d;
6895       break;
6896     case Intrinsic::x86_sse2_pslli_q:
6897       NewIntNo = Intrinsic::x86_sse2_psll_q;
6898       break;
6899     case Intrinsic::x86_sse2_psrli_w:
6900       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6901       break;
6902     case Intrinsic::x86_sse2_psrli_d:
6903       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6904       break;
6905     case Intrinsic::x86_sse2_psrli_q:
6906       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6907       break;
6908     case Intrinsic::x86_sse2_psrai_w:
6909       NewIntNo = Intrinsic::x86_sse2_psra_w;
6910       break;
6911     case Intrinsic::x86_sse2_psrai_d:
6912       NewIntNo = Intrinsic::x86_sse2_psra_d;
6913       break;
6914     default: {
6915       ShAmtVT = MVT::v2i32;
6916       switch (IntNo) {
6917       case Intrinsic::x86_mmx_pslli_w:
6918         NewIntNo = Intrinsic::x86_mmx_psll_w;
6919         break;
6920       case Intrinsic::x86_mmx_pslli_d:
6921         NewIntNo = Intrinsic::x86_mmx_psll_d;
6922         break;
6923       case Intrinsic::x86_mmx_pslli_q:
6924         NewIntNo = Intrinsic::x86_mmx_psll_q;
6925         break;
6926       case Intrinsic::x86_mmx_psrli_w:
6927         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6928         break;
6929       case Intrinsic::x86_mmx_psrli_d:
6930         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6931         break;
6932       case Intrinsic::x86_mmx_psrli_q:
6933         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6934         break;
6935       case Intrinsic::x86_mmx_psrai_w:
6936         NewIntNo = Intrinsic::x86_mmx_psra_w;
6937         break;
6938       case Intrinsic::x86_mmx_psrai_d:
6939         NewIntNo = Intrinsic::x86_mmx_psra_d;
6940         break;
6941       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6942       }
6943       break;
6944     }
6945     }
6946
6947     // The vector shift intrinsics with scalars uses 32b shift amounts but
6948     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6949     // to be zero.
6950     SDValue ShOps[4];
6951     ShOps[0] = ShAmt;
6952     ShOps[1] = DAG.getConstant(0, MVT::i32);
6953     if (ShAmtVT == MVT::v4i32) {
6954       ShOps[2] = DAG.getUNDEF(MVT::i32);
6955       ShOps[3] = DAG.getUNDEF(MVT::i32);
6956       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6957     } else {
6958       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6959     }
6960
6961     EVT VT = Op.getValueType();
6962     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6963     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6964                        DAG.getConstant(NewIntNo, MVT::i32),
6965                        Op.getOperand(1), ShAmt);
6966   }
6967   }
6968 }
6969
6970 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
6971                                            SelectionDAG &DAG) const {
6972   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6973   DebugLoc dl = Op.getDebugLoc();
6974
6975   if (Depth > 0) {
6976     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6977     SDValue Offset =
6978       DAG.getConstant(TD->getPointerSize(),
6979                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6980     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6981                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6982                                    FrameAddr, Offset),
6983                        NULL, 0, false, false, 0);
6984   }
6985
6986   // Just load the return address.
6987   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6988   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6989                      RetAddrFI, NULL, 0, false, false, 0);
6990 }
6991
6992 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6993   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6994   MFI->setFrameAddressIsTaken(true);
6995   EVT VT = Op.getValueType();
6996   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6997   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6998   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6999   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7000   while (Depth--)
7001     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7002                             false, false, 0);
7003   return FrameAddr;
7004 }
7005
7006 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7007                                                      SelectionDAG &DAG) const {
7008   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7009 }
7010
7011 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7012   MachineFunction &MF = DAG.getMachineFunction();
7013   SDValue Chain     = Op.getOperand(0);
7014   SDValue Offset    = Op.getOperand(1);
7015   SDValue Handler   = Op.getOperand(2);
7016   DebugLoc dl       = Op.getDebugLoc();
7017
7018   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7019                                   getPointerTy());
7020   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7021
7022   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7023                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7024   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7025   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7026   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7027   MF.getRegInfo().addLiveOut(StoreAddrReg);
7028
7029   return DAG.getNode(X86ISD::EH_RETURN, dl,
7030                      MVT::Other,
7031                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7032 }
7033
7034 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7035                                              SelectionDAG &DAG) const {
7036   SDValue Root = Op.getOperand(0);
7037   SDValue Trmp = Op.getOperand(1); // trampoline
7038   SDValue FPtr = Op.getOperand(2); // nested function
7039   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7040   DebugLoc dl  = Op.getDebugLoc();
7041
7042   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7043
7044   if (Subtarget->is64Bit()) {
7045     SDValue OutChains[6];
7046
7047     // Large code-model.
7048     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7049     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7050
7051     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7052     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7053
7054     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7055
7056     // Load the pointer to the nested function into R11.
7057     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7058     SDValue Addr = Trmp;
7059     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7060                                 Addr, TrmpAddr, 0, false, false, 0);
7061
7062     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7063                        DAG.getConstant(2, MVT::i64));
7064     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7065                                 false, false, 2);
7066
7067     // Load the 'nest' parameter value into R10.
7068     // R10 is specified in X86CallingConv.td
7069     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7070     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7071                        DAG.getConstant(10, MVT::i64));
7072     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7073                                 Addr, TrmpAddr, 10, false, false, 0);
7074
7075     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7076                        DAG.getConstant(12, MVT::i64));
7077     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7078                                 false, false, 2);
7079
7080     // Jump to the nested function.
7081     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7082     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7083                        DAG.getConstant(20, MVT::i64));
7084     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7085                                 Addr, TrmpAddr, 20, false, false, 0);
7086
7087     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7088     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7089                        DAG.getConstant(22, MVT::i64));
7090     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7091                                 TrmpAddr, 22, false, false, 0);
7092
7093     SDValue Ops[] =
7094       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7095     return DAG.getMergeValues(Ops, 2, dl);
7096   } else {
7097     const Function *Func =
7098       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7099     CallingConv::ID CC = Func->getCallingConv();
7100     unsigned NestReg;
7101
7102     switch (CC) {
7103     default:
7104       llvm_unreachable("Unsupported calling convention");
7105     case CallingConv::C:
7106     case CallingConv::X86_StdCall: {
7107       // Pass 'nest' parameter in ECX.
7108       // Must be kept in sync with X86CallingConv.td
7109       NestReg = X86::ECX;
7110
7111       // Check that ECX wasn't needed by an 'inreg' parameter.
7112       const FunctionType *FTy = Func->getFunctionType();
7113       const AttrListPtr &Attrs = Func->getAttributes();
7114
7115       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7116         unsigned InRegCount = 0;
7117         unsigned Idx = 1;
7118
7119         for (FunctionType::param_iterator I = FTy->param_begin(),
7120              E = FTy->param_end(); I != E; ++I, ++Idx)
7121           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7122             // FIXME: should only count parameters that are lowered to integers.
7123             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7124
7125         if (InRegCount > 2) {
7126           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7127         }
7128       }
7129       break;
7130     }
7131     case CallingConv::X86_FastCall:
7132     case CallingConv::X86_ThisCall:
7133     case CallingConv::Fast:
7134       // Pass 'nest' parameter in EAX.
7135       // Must be kept in sync with X86CallingConv.td
7136       NestReg = X86::EAX;
7137       break;
7138     }
7139
7140     SDValue OutChains[4];
7141     SDValue Addr, Disp;
7142
7143     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7144                        DAG.getConstant(10, MVT::i32));
7145     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7146
7147     // This is storing the opcode for MOV32ri.
7148     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7149     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7150     OutChains[0] = DAG.getStore(Root, dl,
7151                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7152                                 Trmp, TrmpAddr, 0, false, false, 0);
7153
7154     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7155                        DAG.getConstant(1, MVT::i32));
7156     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7157                                 false, false, 1);
7158
7159     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7160     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7161                        DAG.getConstant(5, MVT::i32));
7162     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7163                                 TrmpAddr, 5, false, false, 1);
7164
7165     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7166                        DAG.getConstant(6, MVT::i32));
7167     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7168                                 false, false, 1);
7169
7170     SDValue Ops[] =
7171       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7172     return DAG.getMergeValues(Ops, 2, dl);
7173   }
7174 }
7175
7176 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7177                                             SelectionDAG &DAG) const {
7178   /*
7179    The rounding mode is in bits 11:10 of FPSR, and has the following
7180    settings:
7181      00 Round to nearest
7182      01 Round to -inf
7183      10 Round to +inf
7184      11 Round to 0
7185
7186   FLT_ROUNDS, on the other hand, expects the following:
7187     -1 Undefined
7188      0 Round to 0
7189      1 Round to nearest
7190      2 Round to +inf
7191      3 Round to -inf
7192
7193   To perform the conversion, we do:
7194     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7195   */
7196
7197   MachineFunction &MF = DAG.getMachineFunction();
7198   const TargetMachine &TM = MF.getTarget();
7199   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7200   unsigned StackAlignment = TFI.getStackAlignment();
7201   EVT VT = Op.getValueType();
7202   DebugLoc dl = Op.getDebugLoc();
7203
7204   // Save FP Control Word to stack slot
7205   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7206   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7207
7208   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7209                               DAG.getEntryNode(), StackSlot);
7210
7211   // Load FP Control Word from stack slot
7212   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7213                             false, false, 0);
7214
7215   // Transform as necessary
7216   SDValue CWD1 =
7217     DAG.getNode(ISD::SRL, dl, MVT::i16,
7218                 DAG.getNode(ISD::AND, dl, MVT::i16,
7219                             CWD, DAG.getConstant(0x800, MVT::i16)),
7220                 DAG.getConstant(11, MVT::i8));
7221   SDValue CWD2 =
7222     DAG.getNode(ISD::SRL, dl, MVT::i16,
7223                 DAG.getNode(ISD::AND, dl, MVT::i16,
7224                             CWD, DAG.getConstant(0x400, MVT::i16)),
7225                 DAG.getConstant(9, MVT::i8));
7226
7227   SDValue RetVal =
7228     DAG.getNode(ISD::AND, dl, MVT::i16,
7229                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7230                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7231                             DAG.getConstant(1, MVT::i16)),
7232                 DAG.getConstant(3, MVT::i16));
7233
7234
7235   return DAG.getNode((VT.getSizeInBits() < 16 ?
7236                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7237 }
7238
7239 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7240   EVT VT = Op.getValueType();
7241   EVT OpVT = VT;
7242   unsigned NumBits = VT.getSizeInBits();
7243   DebugLoc dl = Op.getDebugLoc();
7244
7245   Op = Op.getOperand(0);
7246   if (VT == MVT::i8) {
7247     // Zero extend to i32 since there is not an i8 bsr.
7248     OpVT = MVT::i32;
7249     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7250   }
7251
7252   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7253   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7254   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7255
7256   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7257   SDValue Ops[] = {
7258     Op,
7259     DAG.getConstant(NumBits+NumBits-1, OpVT),
7260     DAG.getConstant(X86::COND_E, MVT::i8),
7261     Op.getValue(1)
7262   };
7263   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7264
7265   // Finally xor with NumBits-1.
7266   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7267
7268   if (VT == MVT::i8)
7269     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7270   return Op;
7271 }
7272
7273 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7274   EVT VT = Op.getValueType();
7275   EVT OpVT = VT;
7276   unsigned NumBits = VT.getSizeInBits();
7277   DebugLoc dl = Op.getDebugLoc();
7278
7279   Op = Op.getOperand(0);
7280   if (VT == MVT::i8) {
7281     OpVT = MVT::i32;
7282     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7283   }
7284
7285   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7286   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7287   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7288
7289   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7290   SDValue Ops[] = {
7291     Op,
7292     DAG.getConstant(NumBits, OpVT),
7293     DAG.getConstant(X86::COND_E, MVT::i8),
7294     Op.getValue(1)
7295   };
7296   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7297
7298   if (VT == MVT::i8)
7299     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7300   return Op;
7301 }
7302
7303 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7304   EVT VT = Op.getValueType();
7305   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7306   DebugLoc dl = Op.getDebugLoc();
7307
7308   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7309   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7310   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7311   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7312   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7313   //
7314   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7315   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7316   //  return AloBlo + AloBhi + AhiBlo;
7317
7318   SDValue A = Op.getOperand(0);
7319   SDValue B = Op.getOperand(1);
7320
7321   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7322                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7323                        A, DAG.getConstant(32, MVT::i32));
7324   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7325                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7326                        B, DAG.getConstant(32, MVT::i32));
7327   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7328                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7329                        A, B);
7330   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7331                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7332                        A, Bhi);
7333   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7334                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7335                        Ahi, B);
7336   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7337                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7338                        AloBhi, DAG.getConstant(32, MVT::i32));
7339   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7340                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7341                        AhiBlo, DAG.getConstant(32, MVT::i32));
7342   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7343   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7344   return Res;
7345 }
7346
7347
7348 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7349   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7350   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7351   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7352   // has only one use.
7353   SDNode *N = Op.getNode();
7354   SDValue LHS = N->getOperand(0);
7355   SDValue RHS = N->getOperand(1);
7356   unsigned BaseOp = 0;
7357   unsigned Cond = 0;
7358   DebugLoc dl = Op.getDebugLoc();
7359
7360   switch (Op.getOpcode()) {
7361   default: llvm_unreachable("Unknown ovf instruction!");
7362   case ISD::SADDO:
7363     // A subtract of one will be selected as a INC. Note that INC doesn't
7364     // set CF, so we can't do this for UADDO.
7365     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7366       if (C->getAPIntValue() == 1) {
7367         BaseOp = X86ISD::INC;
7368         Cond = X86::COND_O;
7369         break;
7370       }
7371     BaseOp = X86ISD::ADD;
7372     Cond = X86::COND_O;
7373     break;
7374   case ISD::UADDO:
7375     BaseOp = X86ISD::ADD;
7376     Cond = X86::COND_B;
7377     break;
7378   case ISD::SSUBO:
7379     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7380     // set CF, so we can't do this for USUBO.
7381     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7382       if (C->getAPIntValue() == 1) {
7383         BaseOp = X86ISD::DEC;
7384         Cond = X86::COND_O;
7385         break;
7386       }
7387     BaseOp = X86ISD::SUB;
7388     Cond = X86::COND_O;
7389     break;
7390   case ISD::USUBO:
7391     BaseOp = X86ISD::SUB;
7392     Cond = X86::COND_B;
7393     break;
7394   case ISD::SMULO:
7395     BaseOp = X86ISD::SMUL;
7396     Cond = X86::COND_O;
7397     break;
7398   case ISD::UMULO:
7399     BaseOp = X86ISD::UMUL;
7400     Cond = X86::COND_B;
7401     break;
7402   }
7403
7404   // Also sets EFLAGS.
7405   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7406   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7407
7408   SDValue SetCC =
7409     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7410                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7411
7412   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7413   return Sum;
7414 }
7415
7416 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7417   EVT T = Op.getValueType();
7418   DebugLoc dl = Op.getDebugLoc();
7419   unsigned Reg = 0;
7420   unsigned size = 0;
7421   switch(T.getSimpleVT().SimpleTy) {
7422   default:
7423     assert(false && "Invalid value type!");
7424   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7425   case MVT::i16: Reg = X86::AX;  size = 2; break;
7426   case MVT::i32: Reg = X86::EAX; size = 4; break;
7427   case MVT::i64:
7428     assert(Subtarget->is64Bit() && "Node not type legal!");
7429     Reg = X86::RAX; size = 8;
7430     break;
7431   }
7432   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7433                                     Op.getOperand(2), SDValue());
7434   SDValue Ops[] = { cpIn.getValue(0),
7435                     Op.getOperand(1),
7436                     Op.getOperand(3),
7437                     DAG.getTargetConstant(size, MVT::i8),
7438                     cpIn.getValue(1) };
7439   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7440   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7441   SDValue cpOut =
7442     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7443   return cpOut;
7444 }
7445
7446 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7447                                                  SelectionDAG &DAG) const {
7448   assert(Subtarget->is64Bit() && "Result not type legalized?");
7449   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7450   SDValue TheChain = Op.getOperand(0);
7451   DebugLoc dl = Op.getDebugLoc();
7452   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7453   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7454   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7455                                    rax.getValue(2));
7456   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7457                             DAG.getConstant(32, MVT::i8));
7458   SDValue Ops[] = {
7459     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7460     rdx.getValue(1)
7461   };
7462   return DAG.getMergeValues(Ops, 2, dl);
7463 }
7464
7465 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7466   SDNode *Node = Op.getNode();
7467   DebugLoc dl = Node->getDebugLoc();
7468   EVT T = Node->getValueType(0);
7469   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7470                               DAG.getConstant(0, T), Node->getOperand(2));
7471   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7472                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7473                        Node->getOperand(0),
7474                        Node->getOperand(1), negOp,
7475                        cast<AtomicSDNode>(Node)->getSrcValue(),
7476                        cast<AtomicSDNode>(Node)->getAlignment());
7477 }
7478
7479 /// LowerOperation - Provide custom lowering hooks for some operations.
7480 ///
7481 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7482   switch (Op.getOpcode()) {
7483   default: llvm_unreachable("Should not custom lower this!");
7484   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7485   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7486   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7487   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7488   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7489   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7490   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7491   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7492   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7493   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7494   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7495   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7496   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7497   case ISD::SHL_PARTS:
7498   case ISD::SRA_PARTS:
7499   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7500   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7501   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7502   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7503   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7504   case ISD::FABS:               return LowerFABS(Op, DAG);
7505   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7506   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7507   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7508   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7509   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7510   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7511   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7512   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7513   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7514   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7515   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7516   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7517   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7518   case ISD::FRAME_TO_ARGS_OFFSET:
7519                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7520   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7521   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7522   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7523   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7524   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7525   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7526   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7527   case ISD::SADDO:
7528   case ISD::UADDO:
7529   case ISD::SSUBO:
7530   case ISD::USUBO:
7531   case ISD::SMULO:
7532   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7533   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7534   }
7535 }
7536
7537 void X86TargetLowering::
7538 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7539                         SelectionDAG &DAG, unsigned NewOp) const {
7540   EVT T = Node->getValueType(0);
7541   DebugLoc dl = Node->getDebugLoc();
7542   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7543
7544   SDValue Chain = Node->getOperand(0);
7545   SDValue In1 = Node->getOperand(1);
7546   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7547                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7548   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7549                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7550   SDValue Ops[] = { Chain, In1, In2L, In2H };
7551   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7552   SDValue Result =
7553     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7554                             cast<MemSDNode>(Node)->getMemOperand());
7555   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7556   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7557   Results.push_back(Result.getValue(2));
7558 }
7559
7560 /// ReplaceNodeResults - Replace a node with an illegal result type
7561 /// with a new node built out of custom code.
7562 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7563                                            SmallVectorImpl<SDValue>&Results,
7564                                            SelectionDAG &DAG) const {
7565   DebugLoc dl = N->getDebugLoc();
7566   switch (N->getOpcode()) {
7567   default:
7568     assert(false && "Do not know how to custom type legalize this operation!");
7569     return;
7570   case ISD::FP_TO_SINT: {
7571     std::pair<SDValue,SDValue> Vals =
7572         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7573     SDValue FIST = Vals.first, StackSlot = Vals.second;
7574     if (FIST.getNode() != 0) {
7575       EVT VT = N->getValueType(0);
7576       // Return a load from the stack slot.
7577       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7578                                     false, false, 0));
7579     }
7580     return;
7581   }
7582   case ISD::READCYCLECOUNTER: {
7583     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7584     SDValue TheChain = N->getOperand(0);
7585     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7586     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7587                                      rd.getValue(1));
7588     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7589                                      eax.getValue(2));
7590     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7591     SDValue Ops[] = { eax, edx };
7592     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7593     Results.push_back(edx.getValue(1));
7594     return;
7595   }
7596   case ISD::ATOMIC_CMP_SWAP: {
7597     EVT T = N->getValueType(0);
7598     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7599     SDValue cpInL, cpInH;
7600     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7601                         DAG.getConstant(0, MVT::i32));
7602     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7603                         DAG.getConstant(1, MVT::i32));
7604     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7605     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7606                              cpInL.getValue(1));
7607     SDValue swapInL, swapInH;
7608     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7609                           DAG.getConstant(0, MVT::i32));
7610     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7611                           DAG.getConstant(1, MVT::i32));
7612     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7613                                cpInH.getValue(1));
7614     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7615                                swapInL.getValue(1));
7616     SDValue Ops[] = { swapInH.getValue(0),
7617                       N->getOperand(1),
7618                       swapInH.getValue(1) };
7619     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7620     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7621     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7622                                         MVT::i32, Result.getValue(1));
7623     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7624                                         MVT::i32, cpOutL.getValue(2));
7625     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7626     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7627     Results.push_back(cpOutH.getValue(1));
7628     return;
7629   }
7630   case ISD::ATOMIC_LOAD_ADD:
7631     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7632     return;
7633   case ISD::ATOMIC_LOAD_AND:
7634     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7635     return;
7636   case ISD::ATOMIC_LOAD_NAND:
7637     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7638     return;
7639   case ISD::ATOMIC_LOAD_OR:
7640     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7641     return;
7642   case ISD::ATOMIC_LOAD_SUB:
7643     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7644     return;
7645   case ISD::ATOMIC_LOAD_XOR:
7646     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7647     return;
7648   case ISD::ATOMIC_SWAP:
7649     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7650     return;
7651   }
7652 }
7653
7654 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7655   switch (Opcode) {
7656   default: return NULL;
7657   case X86ISD::BSF:                return "X86ISD::BSF";
7658   case X86ISD::BSR:                return "X86ISD::BSR";
7659   case X86ISD::SHLD:               return "X86ISD::SHLD";
7660   case X86ISD::SHRD:               return "X86ISD::SHRD";
7661   case X86ISD::FAND:               return "X86ISD::FAND";
7662   case X86ISD::FOR:                return "X86ISD::FOR";
7663   case X86ISD::FXOR:               return "X86ISD::FXOR";
7664   case X86ISD::FSRL:               return "X86ISD::FSRL";
7665   case X86ISD::FILD:               return "X86ISD::FILD";
7666   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7667   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7668   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7669   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7670   case X86ISD::FLD:                return "X86ISD::FLD";
7671   case X86ISD::FST:                return "X86ISD::FST";
7672   case X86ISD::CALL:               return "X86ISD::CALL";
7673   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7674   case X86ISD::BT:                 return "X86ISD::BT";
7675   case X86ISD::CMP:                return "X86ISD::CMP";
7676   case X86ISD::COMI:               return "X86ISD::COMI";
7677   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7678   case X86ISD::SETCC:              return "X86ISD::SETCC";
7679   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7680   case X86ISD::CMOV:               return "X86ISD::CMOV";
7681   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7682   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7683   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7684   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7685   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7686   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7687   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7688   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7689   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7690   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7691   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7692   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7693   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7694   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7695   case X86ISD::FMAX:               return "X86ISD::FMAX";
7696   case X86ISD::FMIN:               return "X86ISD::FMIN";
7697   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7698   case X86ISD::FRCP:               return "X86ISD::FRCP";
7699   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7700   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7701   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7702   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7703   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7704   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7705   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7706   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7707   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7708   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7709   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7710   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7711   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7712   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7713   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7714   case X86ISD::VSHL:               return "X86ISD::VSHL";
7715   case X86ISD::VSRL:               return "X86ISD::VSRL";
7716   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7717   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7718   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7719   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7720   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7721   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7722   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7723   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7724   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7725   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7726   case X86ISD::ADD:                return "X86ISD::ADD";
7727   case X86ISD::SUB:                return "X86ISD::SUB";
7728   case X86ISD::SMUL:               return "X86ISD::SMUL";
7729   case X86ISD::UMUL:               return "X86ISD::UMUL";
7730   case X86ISD::INC:                return "X86ISD::INC";
7731   case X86ISD::DEC:                return "X86ISD::DEC";
7732   case X86ISD::OR:                 return "X86ISD::OR";
7733   case X86ISD::XOR:                return "X86ISD::XOR";
7734   case X86ISD::AND:                return "X86ISD::AND";
7735   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7736   case X86ISD::PTEST:              return "X86ISD::PTEST";
7737   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7738   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7739   }
7740 }
7741
7742 // isLegalAddressingMode - Return true if the addressing mode represented
7743 // by AM is legal for this target, for a load/store of the specified type.
7744 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7745                                               const Type *Ty) const {
7746   // X86 supports extremely general addressing modes.
7747   CodeModel::Model M = getTargetMachine().getCodeModel();
7748
7749   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7750   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7751     return false;
7752
7753   if (AM.BaseGV) {
7754     unsigned GVFlags =
7755       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7756
7757     // If a reference to this global requires an extra load, we can't fold it.
7758     if (isGlobalStubReference(GVFlags))
7759       return false;
7760
7761     // If BaseGV requires a register for the PIC base, we cannot also have a
7762     // BaseReg specified.
7763     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7764       return false;
7765
7766     // If lower 4G is not available, then we must use rip-relative addressing.
7767     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7768       return false;
7769   }
7770
7771   switch (AM.Scale) {
7772   case 0:
7773   case 1:
7774   case 2:
7775   case 4:
7776   case 8:
7777     // These scales always work.
7778     break;
7779   case 3:
7780   case 5:
7781   case 9:
7782     // These scales are formed with basereg+scalereg.  Only accept if there is
7783     // no basereg yet.
7784     if (AM.HasBaseReg)
7785       return false;
7786     break;
7787   default:  // Other stuff never works.
7788     return false;
7789   }
7790
7791   return true;
7792 }
7793
7794
7795 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7796   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7797     return false;
7798   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7799   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7800   if (NumBits1 <= NumBits2)
7801     return false;
7802   return true;
7803 }
7804
7805 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7806   if (!VT1.isInteger() || !VT2.isInteger())
7807     return false;
7808   unsigned NumBits1 = VT1.getSizeInBits();
7809   unsigned NumBits2 = VT2.getSizeInBits();
7810   if (NumBits1 <= NumBits2)
7811     return false;
7812   return true;
7813 }
7814
7815 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7816   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7817   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7818 }
7819
7820 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7821   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7822   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7823 }
7824
7825 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7826   // i16 instructions are longer (0x66 prefix) and potentially slower.
7827   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7828 }
7829
7830 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7831 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7832 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7833 /// are assumed to be legal.
7834 bool
7835 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7836                                       EVT VT) const {
7837   // Very little shuffling can be done for 64-bit vectors right now.
7838   if (VT.getSizeInBits() == 64)
7839     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7840
7841   // FIXME: pshufb, blends, shifts.
7842   return (VT.getVectorNumElements() == 2 ||
7843           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7844           isMOVLMask(M, VT) ||
7845           isSHUFPMask(M, VT) ||
7846           isPSHUFDMask(M, VT) ||
7847           isPSHUFHWMask(M, VT) ||
7848           isPSHUFLWMask(M, VT) ||
7849           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7850           isUNPCKLMask(M, VT) ||
7851           isUNPCKHMask(M, VT) ||
7852           isUNPCKL_v_undef_Mask(M, VT) ||
7853           isUNPCKH_v_undef_Mask(M, VT));
7854 }
7855
7856 bool
7857 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7858                                           EVT VT) const {
7859   unsigned NumElts = VT.getVectorNumElements();
7860   // FIXME: This collection of masks seems suspect.
7861   if (NumElts == 2)
7862     return true;
7863   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7864     return (isMOVLMask(Mask, VT)  ||
7865             isCommutedMOVLMask(Mask, VT, true) ||
7866             isSHUFPMask(Mask, VT) ||
7867             isCommutedSHUFPMask(Mask, VT));
7868   }
7869   return false;
7870 }
7871
7872 //===----------------------------------------------------------------------===//
7873 //                           X86 Scheduler Hooks
7874 //===----------------------------------------------------------------------===//
7875
7876 // private utility function
7877 MachineBasicBlock *
7878 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7879                                                        MachineBasicBlock *MBB,
7880                                                        unsigned regOpc,
7881                                                        unsigned immOpc,
7882                                                        unsigned LoadOpc,
7883                                                        unsigned CXchgOpc,
7884                                                        unsigned copyOpc,
7885                                                        unsigned notOpc,
7886                                                        unsigned EAXreg,
7887                                                        TargetRegisterClass *RC,
7888                                                        bool invSrc) const {
7889   // For the atomic bitwise operator, we generate
7890   //   thisMBB:
7891   //   newMBB:
7892   //     ld  t1 = [bitinstr.addr]
7893   //     op  t2 = t1, [bitinstr.val]
7894   //     mov EAX = t1
7895   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7896   //     bz  newMBB
7897   //     fallthrough -->nextMBB
7898   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7899   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7900   MachineFunction::iterator MBBIter = MBB;
7901   ++MBBIter;
7902
7903   /// First build the CFG
7904   MachineFunction *F = MBB->getParent();
7905   MachineBasicBlock *thisMBB = MBB;
7906   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7907   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7908   F->insert(MBBIter, newMBB);
7909   F->insert(MBBIter, nextMBB);
7910
7911   // Move all successors to thisMBB to nextMBB
7912   nextMBB->transferSuccessors(thisMBB);
7913
7914   // Update thisMBB to fall through to newMBB
7915   thisMBB->addSuccessor(newMBB);
7916
7917   // newMBB jumps to itself and fall through to nextMBB
7918   newMBB->addSuccessor(nextMBB);
7919   newMBB->addSuccessor(newMBB);
7920
7921   // Insert instructions into newMBB based on incoming instruction
7922   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7923          "unexpected number of operands");
7924   DebugLoc dl = bInstr->getDebugLoc();
7925   MachineOperand& destOper = bInstr->getOperand(0);
7926   MachineOperand* argOpers[2 + X86AddrNumOperands];
7927   int numArgs = bInstr->getNumOperands() - 1;
7928   for (int i=0; i < numArgs; ++i)
7929     argOpers[i] = &bInstr->getOperand(i+1);
7930
7931   // x86 address has 4 operands: base, index, scale, and displacement
7932   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7933   int valArgIndx = lastAddrIndx + 1;
7934
7935   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7936   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7937   for (int i=0; i <= lastAddrIndx; ++i)
7938     (*MIB).addOperand(*argOpers[i]);
7939
7940   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7941   if (invSrc) {
7942     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7943   }
7944   else
7945     tt = t1;
7946
7947   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7948   assert((argOpers[valArgIndx]->isReg() ||
7949           argOpers[valArgIndx]->isImm()) &&
7950          "invalid operand");
7951   if (argOpers[valArgIndx]->isReg())
7952     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7953   else
7954     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7955   MIB.addReg(tt);
7956   (*MIB).addOperand(*argOpers[valArgIndx]);
7957
7958   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7959   MIB.addReg(t1);
7960
7961   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7962   for (int i=0; i <= lastAddrIndx; ++i)
7963     (*MIB).addOperand(*argOpers[i]);
7964   MIB.addReg(t2);
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), destOper.getReg());
7970   MIB.addReg(EAXreg);
7971
7972   // insert branch
7973   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
7974
7975   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7976   return nextMBB;
7977 }
7978
7979 // private utility function:  64 bit atomics on 32 bit host.
7980 MachineBasicBlock *
7981 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7982                                                        MachineBasicBlock *MBB,
7983                                                        unsigned regOpcL,
7984                                                        unsigned regOpcH,
7985                                                        unsigned immOpcL,
7986                                                        unsigned immOpcH,
7987                                                        bool invSrc) const {
7988   // For the atomic bitwise operator, we generate
7989   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7990   //     ld t1,t2 = [bitinstr.addr]
7991   //   newMBB:
7992   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7993   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7994   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7995   //     mov ECX, EBX <- t5, t6
7996   //     mov EAX, EDX <- t1, t2
7997   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7998   //     mov t3, t4 <- EAX, EDX
7999   //     bz  newMBB
8000   //     result in out1, out2
8001   //     fallthrough -->nextMBB
8002
8003   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8004   const unsigned LoadOpc = X86::MOV32rm;
8005   const unsigned copyOpc = X86::MOV32rr;
8006   const unsigned NotOpc = X86::NOT32r;
8007   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8008   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8009   MachineFunction::iterator MBBIter = MBB;
8010   ++MBBIter;
8011
8012   /// First build the CFG
8013   MachineFunction *F = MBB->getParent();
8014   MachineBasicBlock *thisMBB = MBB;
8015   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8016   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8017   F->insert(MBBIter, newMBB);
8018   F->insert(MBBIter, nextMBB);
8019
8020   // Move all successors to thisMBB to nextMBB
8021   nextMBB->transferSuccessors(thisMBB);
8022
8023   // Update thisMBB to fall through to newMBB
8024   thisMBB->addSuccessor(newMBB);
8025
8026   // newMBB jumps to itself and fall through to nextMBB
8027   newMBB->addSuccessor(nextMBB);
8028   newMBB->addSuccessor(newMBB);
8029
8030   DebugLoc dl = bInstr->getDebugLoc();
8031   // Insert instructions into newMBB based on incoming instruction
8032   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8033   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8034          "unexpected number of operands");
8035   MachineOperand& dest1Oper = bInstr->getOperand(0);
8036   MachineOperand& dest2Oper = bInstr->getOperand(1);
8037   MachineOperand* argOpers[2 + X86AddrNumOperands];
8038   for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8039     argOpers[i] = &bInstr->getOperand(i+2);
8040
8041     // We use some of the operands multiple times, so conservatively just
8042     // clear any kill flags that might be present.
8043     if (argOpers[i]->isReg() && argOpers[i]->isUse())
8044       argOpers[i]->setIsKill(false);
8045   }
8046
8047   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8048   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8049
8050   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8051   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8052   for (int i=0; i <= lastAddrIndx; ++i)
8053     (*MIB).addOperand(*argOpers[i]);
8054   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8055   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8056   // add 4 to displacement.
8057   for (int i=0; i <= lastAddrIndx-2; ++i)
8058     (*MIB).addOperand(*argOpers[i]);
8059   MachineOperand newOp3 = *(argOpers[3]);
8060   if (newOp3.isImm())
8061     newOp3.setImm(newOp3.getImm()+4);
8062   else
8063     newOp3.setOffset(newOp3.getOffset()+4);
8064   (*MIB).addOperand(newOp3);
8065   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8066
8067   // t3/4 are defined later, at the bottom of the loop
8068   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8069   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8070   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8071     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8072   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8073     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8074
8075   // The subsequent operations should be using the destination registers of
8076   //the PHI instructions.
8077   if (invSrc) {
8078     t1 = F->getRegInfo().createVirtualRegister(RC);
8079     t2 = F->getRegInfo().createVirtualRegister(RC);
8080     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8081     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8082   } else {
8083     t1 = dest1Oper.getReg();
8084     t2 = dest2Oper.getReg();
8085   }
8086
8087   int valArgIndx = lastAddrIndx + 1;
8088   assert((argOpers[valArgIndx]->isReg() ||
8089           argOpers[valArgIndx]->isImm()) &&
8090          "invalid operand");
8091   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8092   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8093   if (argOpers[valArgIndx]->isReg())
8094     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8095   else
8096     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8097   if (regOpcL != X86::MOV32rr)
8098     MIB.addReg(t1);
8099   (*MIB).addOperand(*argOpers[valArgIndx]);
8100   assert(argOpers[valArgIndx + 1]->isReg() ==
8101          argOpers[valArgIndx]->isReg());
8102   assert(argOpers[valArgIndx + 1]->isImm() ==
8103          argOpers[valArgIndx]->isImm());
8104   if (argOpers[valArgIndx + 1]->isReg())
8105     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8106   else
8107     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8108   if (regOpcH != X86::MOV32rr)
8109     MIB.addReg(t2);
8110   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8111
8112   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8113   MIB.addReg(t1);
8114   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8115   MIB.addReg(t2);
8116
8117   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8118   MIB.addReg(t5);
8119   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8120   MIB.addReg(t6);
8121
8122   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8123   for (int i=0; i <= lastAddrIndx; ++i)
8124     (*MIB).addOperand(*argOpers[i]);
8125
8126   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8127   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8128                     bInstr->memoperands_end());
8129
8130   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8131   MIB.addReg(X86::EAX);
8132   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8133   MIB.addReg(X86::EDX);
8134
8135   // insert branch
8136   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8137
8138   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8139   return nextMBB;
8140 }
8141
8142 // private utility function
8143 MachineBasicBlock *
8144 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8145                                                       MachineBasicBlock *MBB,
8146                                                       unsigned cmovOpc) const {
8147   // For the atomic min/max operator, we generate
8148   //   thisMBB:
8149   //   newMBB:
8150   //     ld t1 = [min/max.addr]
8151   //     mov t2 = [min/max.val]
8152   //     cmp  t1, t2
8153   //     cmov[cond] t2 = t1
8154   //     mov EAX = t1
8155   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8156   //     bz   newMBB
8157   //     fallthrough -->nextMBB
8158   //
8159   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8160   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8161   MachineFunction::iterator MBBIter = MBB;
8162   ++MBBIter;
8163
8164   /// First build the CFG
8165   MachineFunction *F = MBB->getParent();
8166   MachineBasicBlock *thisMBB = MBB;
8167   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8168   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8169   F->insert(MBBIter, newMBB);
8170   F->insert(MBBIter, nextMBB);
8171
8172   // Move all successors of thisMBB to nextMBB
8173   nextMBB->transferSuccessors(thisMBB);
8174
8175   // Update thisMBB to fall through to newMBB
8176   thisMBB->addSuccessor(newMBB);
8177
8178   // newMBB jumps to newMBB and fall through to nextMBB
8179   newMBB->addSuccessor(nextMBB);
8180   newMBB->addSuccessor(newMBB);
8181
8182   DebugLoc dl = mInstr->getDebugLoc();
8183   // Insert instructions into newMBB based on incoming instruction
8184   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8185          "unexpected number of operands");
8186   MachineOperand& destOper = mInstr->getOperand(0);
8187   MachineOperand* argOpers[2 + X86AddrNumOperands];
8188   int numArgs = mInstr->getNumOperands() - 1;
8189   for (int i=0; i < numArgs; ++i)
8190     argOpers[i] = &mInstr->getOperand(i+1);
8191
8192   // x86 address has 4 operands: base, index, scale, and displacement
8193   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8194   int valArgIndx = lastAddrIndx + 1;
8195
8196   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8197   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8198   for (int i=0; i <= lastAddrIndx; ++i)
8199     (*MIB).addOperand(*argOpers[i]);
8200
8201   // We only support register and immediate values
8202   assert((argOpers[valArgIndx]->isReg() ||
8203           argOpers[valArgIndx]->isImm()) &&
8204          "invalid operand");
8205
8206   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8207   if (argOpers[valArgIndx]->isReg())
8208     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8209   else
8210     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8211   (*MIB).addOperand(*argOpers[valArgIndx]);
8212
8213   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8214   MIB.addReg(t1);
8215
8216   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8217   MIB.addReg(t1);
8218   MIB.addReg(t2);
8219
8220   // Generate movc
8221   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8222   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8223   MIB.addReg(t2);
8224   MIB.addReg(t1);
8225
8226   // Cmp and exchange if none has modified the memory location
8227   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8228   for (int i=0; i <= lastAddrIndx; ++i)
8229     (*MIB).addOperand(*argOpers[i]);
8230   MIB.addReg(t3);
8231   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8232   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8233                     mInstr->memoperands_end());
8234
8235   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8236   MIB.addReg(X86::EAX);
8237
8238   // insert branch
8239   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8240
8241   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8242   return nextMBB;
8243 }
8244
8245 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8246 // all of this code can be replaced with that in the .td file.
8247 MachineBasicBlock *
8248 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8249                             unsigned numArgs, bool memArg) const {
8250
8251   MachineFunction *F = BB->getParent();
8252   DebugLoc dl = MI->getDebugLoc();
8253   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8254
8255   unsigned Opc;
8256   if (memArg)
8257     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8258   else
8259     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8260
8261   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8262
8263   for (unsigned i = 0; i < numArgs; ++i) {
8264     MachineOperand &Op = MI->getOperand(i+1);
8265
8266     if (!(Op.isReg() && Op.isImplicit()))
8267       MIB.addOperand(Op);
8268   }
8269
8270   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8271     .addReg(X86::XMM0);
8272
8273   F->DeleteMachineInstr(MI);
8274
8275   return BB;
8276 }
8277
8278 MachineBasicBlock *
8279 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8280                                                  MachineInstr *MI,
8281                                                  MachineBasicBlock *MBB) const {
8282   // Emit code to save XMM registers to the stack. The ABI says that the
8283   // number of registers to save is given in %al, so it's theoretically
8284   // possible to do an indirect jump trick to avoid saving all of them,
8285   // however this code takes a simpler approach and just executes all
8286   // of the stores if %al is non-zero. It's less code, and it's probably
8287   // easier on the hardware branch predictor, and stores aren't all that
8288   // expensive anyway.
8289
8290   // Create the new basic blocks. One block contains all the XMM stores,
8291   // and one block is the final destination regardless of whether any
8292   // stores were performed.
8293   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8294   MachineFunction *F = MBB->getParent();
8295   MachineFunction::iterator MBBIter = MBB;
8296   ++MBBIter;
8297   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8298   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8299   F->insert(MBBIter, XMMSaveMBB);
8300   F->insert(MBBIter, EndMBB);
8301
8302   // Set up the CFG.
8303   // Move any original successors of MBB to the end block.
8304   EndMBB->transferSuccessors(MBB);
8305   // The original block will now fall through to the XMM save block.
8306   MBB->addSuccessor(XMMSaveMBB);
8307   // The XMMSaveMBB will fall through to the end block.
8308   XMMSaveMBB->addSuccessor(EndMBB);
8309
8310   // Now add the instructions.
8311   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8312   DebugLoc DL = MI->getDebugLoc();
8313
8314   unsigned CountReg = MI->getOperand(0).getReg();
8315   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8316   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8317
8318   if (!Subtarget->isTargetWin64()) {
8319     // If %al is 0, branch around the XMM save block.
8320     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8321     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8322     MBB->addSuccessor(EndMBB);
8323   }
8324
8325   // In the XMM save block, save all the XMM argument registers.
8326   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8327     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8328     MachineMemOperand *MMO =
8329       F->getMachineMemOperand(
8330         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8331         MachineMemOperand::MOStore, Offset,
8332         /*Size=*/16, /*Align=*/16);
8333     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8334       .addFrameIndex(RegSaveFrameIndex)
8335       .addImm(/*Scale=*/1)
8336       .addReg(/*IndexReg=*/0)
8337       .addImm(/*Disp=*/Offset)
8338       .addReg(/*Segment=*/0)
8339       .addReg(MI->getOperand(i).getReg())
8340       .addMemOperand(MMO);
8341   }
8342
8343   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8344
8345   return EndMBB;
8346 }
8347
8348 MachineBasicBlock *
8349 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8350                                      MachineBasicBlock *BB) const {
8351   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8352   DebugLoc DL = MI->getDebugLoc();
8353
8354   // To "insert" a SELECT_CC instruction, we actually have to insert the
8355   // diamond control-flow pattern.  The incoming instruction knows the
8356   // destination vreg to set, the condition code register to branch on, the
8357   // true/false values to select between, and a branch opcode to use.
8358   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8359   MachineFunction::iterator It = BB;
8360   ++It;
8361
8362   //  thisMBB:
8363   //  ...
8364   //   TrueVal = ...
8365   //   cmpTY ccX, r1, r2
8366   //   bCC copy1MBB
8367   //   fallthrough --> copy0MBB
8368   MachineBasicBlock *thisMBB = BB;
8369   MachineFunction *F = BB->getParent();
8370   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8371   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8372   unsigned Opc =
8373     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8374   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8375   F->insert(It, copy0MBB);
8376   F->insert(It, sinkMBB);
8377   // Update machine-CFG edges by first adding all successors of the current
8378   // block to the new block which will contain the Phi node for the select.
8379   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8380          E = BB->succ_end(); I != E; ++I)
8381     sinkMBB->addSuccessor(*I);
8382   // Next, remove all successors of the current block, and add the true
8383   // and fallthrough blocks as its successors.
8384   while (!BB->succ_empty())
8385     BB->removeSuccessor(BB->succ_begin());
8386   // Add the true and fallthrough blocks as its successors.
8387   BB->addSuccessor(copy0MBB);
8388   BB->addSuccessor(sinkMBB);
8389
8390   //  copy0MBB:
8391   //   %FalseValue = ...
8392   //   # fallthrough to sinkMBB
8393   copy0MBB->addSuccessor(sinkMBB);
8394
8395   //  sinkMBB:
8396   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8397   //  ...
8398   BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8399     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8400     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8401
8402   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8403   return sinkMBB;
8404 }
8405
8406 MachineBasicBlock *
8407 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8408                                           MachineBasicBlock *BB) const {
8409   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8410   DebugLoc DL = MI->getDebugLoc();
8411   MachineFunction *F = BB->getParent();
8412
8413   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8414   // non-trivial part is impdef of ESP.
8415   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8416   // mingw-w64.
8417
8418   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8419     .addExternalSymbol("_alloca")
8420     .addReg(X86::EAX, RegState::Implicit)
8421     .addReg(X86::ESP, RegState::Implicit)
8422     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8423     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8424
8425   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8426   return BB;
8427 }
8428
8429 MachineBasicBlock *
8430 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8431                                                MachineBasicBlock *BB) const {
8432   switch (MI->getOpcode()) {
8433   default: assert(false && "Unexpected instr type to insert");
8434   case X86::MINGW_ALLOCA:
8435     return EmitLoweredMingwAlloca(MI, BB);
8436   case X86::CMOV_GR8:
8437   case X86::CMOV_V1I64:
8438   case X86::CMOV_FR32:
8439   case X86::CMOV_FR64:
8440   case X86::CMOV_V4F32:
8441   case X86::CMOV_V2F64:
8442   case X86::CMOV_V2I64:
8443   case X86::CMOV_GR16:
8444   case X86::CMOV_GR32:
8445   case X86::CMOV_RFP32:
8446   case X86::CMOV_RFP64:
8447   case X86::CMOV_RFP80:
8448     return EmitLoweredSelect(MI, BB);
8449
8450   case X86::FP32_TO_INT16_IN_MEM:
8451   case X86::FP32_TO_INT32_IN_MEM:
8452   case X86::FP32_TO_INT64_IN_MEM:
8453   case X86::FP64_TO_INT16_IN_MEM:
8454   case X86::FP64_TO_INT32_IN_MEM:
8455   case X86::FP64_TO_INT64_IN_MEM:
8456   case X86::FP80_TO_INT16_IN_MEM:
8457   case X86::FP80_TO_INT32_IN_MEM:
8458   case X86::FP80_TO_INT64_IN_MEM: {
8459     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8460     DebugLoc DL = MI->getDebugLoc();
8461
8462     // Change the floating point control register to use "round towards zero"
8463     // mode when truncating to an integer value.
8464     MachineFunction *F = BB->getParent();
8465     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8466     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8467
8468     // Load the old value of the high byte of the control word...
8469     unsigned OldCW =
8470       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8471     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8472                       CWFrameIdx);
8473
8474     // Set the high part to be round to zero...
8475     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8476       .addImm(0xC7F);
8477
8478     // Reload the modified control word now...
8479     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8480
8481     // Restore the memory image of control word to original value
8482     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8483       .addReg(OldCW);
8484
8485     // Get the X86 opcode to use.
8486     unsigned Opc;
8487     switch (MI->getOpcode()) {
8488     default: llvm_unreachable("illegal opcode!");
8489     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8490     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8491     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8492     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8493     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8494     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8495     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8496     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8497     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8498     }
8499
8500     X86AddressMode AM;
8501     MachineOperand &Op = MI->getOperand(0);
8502     if (Op.isReg()) {
8503       AM.BaseType = X86AddressMode::RegBase;
8504       AM.Base.Reg = Op.getReg();
8505     } else {
8506       AM.BaseType = X86AddressMode::FrameIndexBase;
8507       AM.Base.FrameIndex = Op.getIndex();
8508     }
8509     Op = MI->getOperand(1);
8510     if (Op.isImm())
8511       AM.Scale = Op.getImm();
8512     Op = MI->getOperand(2);
8513     if (Op.isImm())
8514       AM.IndexReg = Op.getImm();
8515     Op = MI->getOperand(3);
8516     if (Op.isGlobal()) {
8517       AM.GV = Op.getGlobal();
8518     } else {
8519       AM.Disp = Op.getImm();
8520     }
8521     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8522                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8523
8524     // Reload the original control word now.
8525     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8526
8527     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8528     return BB;
8529   }
8530     // String/text processing lowering.
8531   case X86::PCMPISTRM128REG:
8532     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8533   case X86::PCMPISTRM128MEM:
8534     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8535   case X86::PCMPESTRM128REG:
8536     return EmitPCMP(MI, BB, 5, false /* in mem */);
8537   case X86::PCMPESTRM128MEM:
8538     return EmitPCMP(MI, BB, 5, true /* in mem */);
8539
8540     // Atomic Lowering.
8541   case X86::ATOMAND32:
8542     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8543                                                X86::AND32ri, X86::MOV32rm,
8544                                                X86::LCMPXCHG32, X86::MOV32rr,
8545                                                X86::NOT32r, X86::EAX,
8546                                                X86::GR32RegisterClass);
8547   case X86::ATOMOR32:
8548     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8549                                                X86::OR32ri, X86::MOV32rm,
8550                                                X86::LCMPXCHG32, X86::MOV32rr,
8551                                                X86::NOT32r, X86::EAX,
8552                                                X86::GR32RegisterClass);
8553   case X86::ATOMXOR32:
8554     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8555                                                X86::XOR32ri, X86::MOV32rm,
8556                                                X86::LCMPXCHG32, X86::MOV32rr,
8557                                                X86::NOT32r, X86::EAX,
8558                                                X86::GR32RegisterClass);
8559   case X86::ATOMNAND32:
8560     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8561                                                X86::AND32ri, X86::MOV32rm,
8562                                                X86::LCMPXCHG32, X86::MOV32rr,
8563                                                X86::NOT32r, X86::EAX,
8564                                                X86::GR32RegisterClass, true);
8565   case X86::ATOMMIN32:
8566     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8567   case X86::ATOMMAX32:
8568     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8569   case X86::ATOMUMIN32:
8570     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8571   case X86::ATOMUMAX32:
8572     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8573
8574   case X86::ATOMAND16:
8575     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8576                                                X86::AND16ri, X86::MOV16rm,
8577                                                X86::LCMPXCHG16, X86::MOV16rr,
8578                                                X86::NOT16r, X86::AX,
8579                                                X86::GR16RegisterClass);
8580   case X86::ATOMOR16:
8581     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8582                                                X86::OR16ri, X86::MOV16rm,
8583                                                X86::LCMPXCHG16, X86::MOV16rr,
8584                                                X86::NOT16r, X86::AX,
8585                                                X86::GR16RegisterClass);
8586   case X86::ATOMXOR16:
8587     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8588                                                X86::XOR16ri, X86::MOV16rm,
8589                                                X86::LCMPXCHG16, X86::MOV16rr,
8590                                                X86::NOT16r, X86::AX,
8591                                                X86::GR16RegisterClass);
8592   case X86::ATOMNAND16:
8593     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8594                                                X86::AND16ri, X86::MOV16rm,
8595                                                X86::LCMPXCHG16, X86::MOV16rr,
8596                                                X86::NOT16r, X86::AX,
8597                                                X86::GR16RegisterClass, true);
8598   case X86::ATOMMIN16:
8599     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8600   case X86::ATOMMAX16:
8601     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8602   case X86::ATOMUMIN16:
8603     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8604   case X86::ATOMUMAX16:
8605     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8606
8607   case X86::ATOMAND8:
8608     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8609                                                X86::AND8ri, X86::MOV8rm,
8610                                                X86::LCMPXCHG8, X86::MOV8rr,
8611                                                X86::NOT8r, X86::AL,
8612                                                X86::GR8RegisterClass);
8613   case X86::ATOMOR8:
8614     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8615                                                X86::OR8ri, X86::MOV8rm,
8616                                                X86::LCMPXCHG8, X86::MOV8rr,
8617                                                X86::NOT8r, X86::AL,
8618                                                X86::GR8RegisterClass);
8619   case X86::ATOMXOR8:
8620     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8621                                                X86::XOR8ri, X86::MOV8rm,
8622                                                X86::LCMPXCHG8, X86::MOV8rr,
8623                                                X86::NOT8r, X86::AL,
8624                                                X86::GR8RegisterClass);
8625   case X86::ATOMNAND8:
8626     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8627                                                X86::AND8ri, X86::MOV8rm,
8628                                                X86::LCMPXCHG8, X86::MOV8rr,
8629                                                X86::NOT8r, X86::AL,
8630                                                X86::GR8RegisterClass, true);
8631   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8632   // This group is for 64-bit host.
8633   case X86::ATOMAND64:
8634     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8635                                                X86::AND64ri32, X86::MOV64rm,
8636                                                X86::LCMPXCHG64, X86::MOV64rr,
8637                                                X86::NOT64r, X86::RAX,
8638                                                X86::GR64RegisterClass);
8639   case X86::ATOMOR64:
8640     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8641                                                X86::OR64ri32, X86::MOV64rm,
8642                                                X86::LCMPXCHG64, X86::MOV64rr,
8643                                                X86::NOT64r, X86::RAX,
8644                                                X86::GR64RegisterClass);
8645   case X86::ATOMXOR64:
8646     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8647                                                X86::XOR64ri32, X86::MOV64rm,
8648                                                X86::LCMPXCHG64, X86::MOV64rr,
8649                                                X86::NOT64r, X86::RAX,
8650                                                X86::GR64RegisterClass);
8651   case X86::ATOMNAND64:
8652     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8653                                                X86::AND64ri32, X86::MOV64rm,
8654                                                X86::LCMPXCHG64, X86::MOV64rr,
8655                                                X86::NOT64r, X86::RAX,
8656                                                X86::GR64RegisterClass, true);
8657   case X86::ATOMMIN64:
8658     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8659   case X86::ATOMMAX64:
8660     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8661   case X86::ATOMUMIN64:
8662     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8663   case X86::ATOMUMAX64:
8664     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8665
8666   // This group does 64-bit operations on a 32-bit host.
8667   case X86::ATOMAND6432:
8668     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8669                                                X86::AND32rr, X86::AND32rr,
8670                                                X86::AND32ri, X86::AND32ri,
8671                                                false);
8672   case X86::ATOMOR6432:
8673     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8674                                                X86::OR32rr, X86::OR32rr,
8675                                                X86::OR32ri, X86::OR32ri,
8676                                                false);
8677   case X86::ATOMXOR6432:
8678     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8679                                                X86::XOR32rr, X86::XOR32rr,
8680                                                X86::XOR32ri, X86::XOR32ri,
8681                                                false);
8682   case X86::ATOMNAND6432:
8683     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8684                                                X86::AND32rr, X86::AND32rr,
8685                                                X86::AND32ri, X86::AND32ri,
8686                                                true);
8687   case X86::ATOMADD6432:
8688     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8689                                                X86::ADD32rr, X86::ADC32rr,
8690                                                X86::ADD32ri, X86::ADC32ri,
8691                                                false);
8692   case X86::ATOMSUB6432:
8693     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8694                                                X86::SUB32rr, X86::SBB32rr,
8695                                                X86::SUB32ri, X86::SBB32ri,
8696                                                false);
8697   case X86::ATOMSWAP6432:
8698     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8699                                                X86::MOV32rr, X86::MOV32rr,
8700                                                X86::MOV32ri, X86::MOV32ri,
8701                                                false);
8702   case X86::VASTART_SAVE_XMM_REGS:
8703     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8704   }
8705 }
8706
8707 //===----------------------------------------------------------------------===//
8708 //                           X86 Optimization Hooks
8709 //===----------------------------------------------------------------------===//
8710
8711 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8712                                                        const APInt &Mask,
8713                                                        APInt &KnownZero,
8714                                                        APInt &KnownOne,
8715                                                        const SelectionDAG &DAG,
8716                                                        unsigned Depth) const {
8717   unsigned Opc = Op.getOpcode();
8718   assert((Opc >= ISD::BUILTIN_OP_END ||
8719           Opc == ISD::INTRINSIC_WO_CHAIN ||
8720           Opc == ISD::INTRINSIC_W_CHAIN ||
8721           Opc == ISD::INTRINSIC_VOID) &&
8722          "Should use MaskedValueIsZero if you don't know whether Op"
8723          " is a target node!");
8724
8725   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8726   switch (Opc) {
8727   default: break;
8728   case X86ISD::ADD:
8729   case X86ISD::SUB:
8730   case X86ISD::SMUL:
8731   case X86ISD::UMUL:
8732   case X86ISD::INC:
8733   case X86ISD::DEC:
8734   case X86ISD::OR:
8735   case X86ISD::XOR:
8736   case X86ISD::AND:
8737     // These nodes' second result is a boolean.
8738     if (Op.getResNo() == 0)
8739       break;
8740     // Fallthrough
8741   case X86ISD::SETCC:
8742     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8743                                        Mask.getBitWidth() - 1);
8744     break;
8745   }
8746 }
8747
8748 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8749 /// node is a GlobalAddress + offset.
8750 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8751                                        const GlobalValue* &GA,
8752                                        int64_t &Offset) const {
8753   if (N->getOpcode() == X86ISD::Wrapper) {
8754     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8755       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8756       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8757       return true;
8758     }
8759   }
8760   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8761 }
8762
8763 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8764 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8765 /// if the load addresses are consecutive, non-overlapping, and in the right
8766 /// order.
8767 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8768                                      const TargetLowering &TLI) {
8769   DebugLoc dl = N->getDebugLoc();
8770   EVT VT = N->getValueType(0);
8771   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8772
8773   if (VT.getSizeInBits() != 128)
8774     return SDValue();
8775
8776   SmallVector<SDValue, 16> Elts;
8777   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8778     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8779   
8780   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8781 }
8782
8783 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8784 /// and convert it from being a bunch of shuffles and extracts to a simple
8785 /// store and scalar loads to extract the elements.
8786 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8787                                                 const TargetLowering &TLI) {
8788   SDValue InputVector = N->getOperand(0);
8789
8790   // Only operate on vectors of 4 elements, where the alternative shuffling
8791   // gets to be more expensive.
8792   if (InputVector.getValueType() != MVT::v4i32)
8793     return SDValue();
8794
8795   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8796   // single use which is a sign-extend or zero-extend, and all elements are
8797   // used.
8798   SmallVector<SDNode *, 4> Uses;
8799   unsigned ExtractedElements = 0;
8800   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8801        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8802     if (UI.getUse().getResNo() != InputVector.getResNo())
8803       return SDValue();
8804
8805     SDNode *Extract = *UI;
8806     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8807       return SDValue();
8808
8809     if (Extract->getValueType(0) != MVT::i32)
8810       return SDValue();
8811     if (!Extract->hasOneUse())
8812       return SDValue();
8813     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8814         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8815       return SDValue();
8816     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8817       return SDValue();
8818
8819     // Record which element was extracted.
8820     ExtractedElements |=
8821       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8822
8823     Uses.push_back(Extract);
8824   }
8825
8826   // If not all the elements were used, this may not be worthwhile.
8827   if (ExtractedElements != 15)
8828     return SDValue();
8829
8830   // Ok, we've now decided to do the transformation.
8831   DebugLoc dl = InputVector.getDebugLoc();
8832
8833   // Store the value to a temporary stack slot.
8834   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8835   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8836                             false, false, 0);
8837
8838   // Replace each use (extract) with a load of the appropriate element.
8839   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8840        UE = Uses.end(); UI != UE; ++UI) {
8841     SDNode *Extract = *UI;
8842
8843     // Compute the element's address.
8844     SDValue Idx = Extract->getOperand(1);
8845     unsigned EltSize =
8846         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8847     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8848     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8849
8850     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8851
8852     // Load the scalar.
8853     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8854                           NULL, 0, false, false, 0);
8855
8856     // Replace the exact with the load.
8857     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8858   }
8859
8860   // The replacement was made in place; don't return anything.
8861   return SDValue();
8862 }
8863
8864 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8865 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8866                                     const X86Subtarget *Subtarget) {
8867   DebugLoc DL = N->getDebugLoc();
8868   SDValue Cond = N->getOperand(0);
8869   // Get the LHS/RHS of the select.
8870   SDValue LHS = N->getOperand(1);
8871   SDValue RHS = N->getOperand(2);
8872
8873   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8874   // instructions match the semantics of the common C idiom x<y?x:y but not
8875   // x<=y?x:y, because of how they handle negative zero (which can be
8876   // ignored in unsafe-math mode).
8877   if (Subtarget->hasSSE2() &&
8878       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8879       Cond.getOpcode() == ISD::SETCC) {
8880     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8881
8882     unsigned Opcode = 0;
8883     // Check for x CC y ? x : y.
8884     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8885         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8886       switch (CC) {
8887       default: break;
8888       case ISD::SETULT:
8889         // Converting this to a min would handle NaNs incorrectly, and swapping
8890         // the operands would cause it to handle comparisons between positive
8891         // and negative zero incorrectly.
8892         if (!FiniteOnlyFPMath() &&
8893             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8894           if (!UnsafeFPMath &&
8895               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8896             break;
8897           std::swap(LHS, RHS);
8898         }
8899         Opcode = X86ISD::FMIN;
8900         break;
8901       case ISD::SETOLE:
8902         // Converting this to a min would handle comparisons between positive
8903         // and negative zero incorrectly.
8904         if (!UnsafeFPMath &&
8905             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8906           break;
8907         Opcode = X86ISD::FMIN;
8908         break;
8909       case ISD::SETULE:
8910         // Converting this to a min would handle both negative zeros and NaNs
8911         // incorrectly, but we can swap the operands to fix both.
8912         std::swap(LHS, RHS);
8913       case ISD::SETOLT:
8914       case ISD::SETLT:
8915       case ISD::SETLE:
8916         Opcode = X86ISD::FMIN;
8917         break;
8918
8919       case ISD::SETOGE:
8920         // Converting this to a max would handle comparisons between positive
8921         // and negative zero incorrectly.
8922         if (!UnsafeFPMath &&
8923             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8924           break;
8925         Opcode = X86ISD::FMAX;
8926         break;
8927       case ISD::SETUGT:
8928         // Converting this to a max would handle NaNs incorrectly, and swapping
8929         // the operands would cause it to handle comparisons between positive
8930         // and negative zero incorrectly.
8931         if (!FiniteOnlyFPMath() &&
8932             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8933           if (!UnsafeFPMath &&
8934               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8935             break;
8936           std::swap(LHS, RHS);
8937         }
8938         Opcode = X86ISD::FMAX;
8939         break;
8940       case ISD::SETUGE:
8941         // Converting this to a max would handle both negative zeros and NaNs
8942         // incorrectly, but we can swap the operands to fix both.
8943         std::swap(LHS, RHS);
8944       case ISD::SETOGT:
8945       case ISD::SETGT:
8946       case ISD::SETGE:
8947         Opcode = X86ISD::FMAX;
8948         break;
8949       }
8950     // Check for x CC y ? y : x -- a min/max with reversed arms.
8951     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8952                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8953       switch (CC) {
8954       default: break;
8955       case ISD::SETOGE:
8956         // Converting this to a min would handle comparisons between positive
8957         // and negative zero incorrectly, and swapping the operands would
8958         // cause it to handle NaNs incorrectly.
8959         if (!UnsafeFPMath &&
8960             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8961           if (!FiniteOnlyFPMath() &&
8962               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8963             break;
8964           std::swap(LHS, RHS);
8965         }
8966         Opcode = X86ISD::FMIN;
8967         break;
8968       case ISD::SETUGT:
8969         // Converting this to a min would handle NaNs incorrectly.
8970         if (!UnsafeFPMath &&
8971             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8972           break;
8973         Opcode = X86ISD::FMIN;
8974         break;
8975       case ISD::SETUGE:
8976         // Converting this to a min would handle both negative zeros and NaNs
8977         // incorrectly, but we can swap the operands to fix both.
8978         std::swap(LHS, RHS);
8979       case ISD::SETOGT:
8980       case ISD::SETGT:
8981       case ISD::SETGE:
8982         Opcode = X86ISD::FMIN;
8983         break;
8984
8985       case ISD::SETULT:
8986         // Converting this to a max would handle NaNs incorrectly.
8987         if (!FiniteOnlyFPMath() &&
8988             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8989           break;
8990         Opcode = X86ISD::FMAX;
8991         break;
8992       case ISD::SETOLE:
8993         // Converting this to a max would handle comparisons between positive
8994         // and negative zero incorrectly, and swapping the operands would
8995         // cause it to handle NaNs incorrectly.
8996         if (!UnsafeFPMath &&
8997             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
8998           if (!FiniteOnlyFPMath() &&
8999               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9000             break;
9001           std::swap(LHS, RHS);
9002         }
9003         Opcode = X86ISD::FMAX;
9004         break;
9005       case ISD::SETULE:
9006         // Converting this to a max would handle both negative zeros and NaNs
9007         // incorrectly, but we can swap the operands to fix both.
9008         std::swap(LHS, RHS);
9009       case ISD::SETOLT:
9010       case ISD::SETLT:
9011       case ISD::SETLE:
9012         Opcode = X86ISD::FMAX;
9013         break;
9014       }
9015     }
9016
9017     if (Opcode)
9018       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9019   }
9020
9021   // If this is a select between two integer constants, try to do some
9022   // optimizations.
9023   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9024     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9025       // Don't do this for crazy integer types.
9026       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9027         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9028         // so that TrueC (the true value) is larger than FalseC.
9029         bool NeedsCondInvert = false;
9030
9031         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9032             // Efficiently invertible.
9033             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9034              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9035               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9036           NeedsCondInvert = true;
9037           std::swap(TrueC, FalseC);
9038         }
9039
9040         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9041         if (FalseC->getAPIntValue() == 0 &&
9042             TrueC->getAPIntValue().isPowerOf2()) {
9043           if (NeedsCondInvert) // Invert the condition if needed.
9044             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9045                                DAG.getConstant(1, Cond.getValueType()));
9046
9047           // Zero extend the condition if needed.
9048           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9049
9050           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9051           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9052                              DAG.getConstant(ShAmt, MVT::i8));
9053         }
9054
9055         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9056         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9057           if (NeedsCondInvert) // Invert the condition if needed.
9058             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9059                                DAG.getConstant(1, Cond.getValueType()));
9060
9061           // Zero extend the condition if needed.
9062           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9063                              FalseC->getValueType(0), Cond);
9064           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9065                              SDValue(FalseC, 0));
9066         }
9067
9068         // Optimize cases that will turn into an LEA instruction.  This requires
9069         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9070         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9071           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9072           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9073
9074           bool isFastMultiplier = false;
9075           if (Diff < 10) {
9076             switch ((unsigned char)Diff) {
9077               default: break;
9078               case 1:  // result = add base, cond
9079               case 2:  // result = lea base(    , cond*2)
9080               case 3:  // result = lea base(cond, cond*2)
9081               case 4:  // result = lea base(    , cond*4)
9082               case 5:  // result = lea base(cond, cond*4)
9083               case 8:  // result = lea base(    , cond*8)
9084               case 9:  // result = lea base(cond, cond*8)
9085                 isFastMultiplier = true;
9086                 break;
9087             }
9088           }
9089
9090           if (isFastMultiplier) {
9091             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9092             if (NeedsCondInvert) // Invert the condition if needed.
9093               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9094                                  DAG.getConstant(1, Cond.getValueType()));
9095
9096             // Zero extend the condition if needed.
9097             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9098                                Cond);
9099             // Scale the condition by the difference.
9100             if (Diff != 1)
9101               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9102                                  DAG.getConstant(Diff, Cond.getValueType()));
9103
9104             // Add the base if non-zero.
9105             if (FalseC->getAPIntValue() != 0)
9106               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9107                                  SDValue(FalseC, 0));
9108             return Cond;
9109           }
9110         }
9111       }
9112   }
9113
9114   return SDValue();
9115 }
9116
9117 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9118 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9119                                   TargetLowering::DAGCombinerInfo &DCI) {
9120   DebugLoc DL = N->getDebugLoc();
9121
9122   // If the flag operand isn't dead, don't touch this CMOV.
9123   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9124     return SDValue();
9125
9126   // If this is a select between two integer constants, try to do some
9127   // optimizations.  Note that the operands are ordered the opposite of SELECT
9128   // operands.
9129   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9130     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9131       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9132       // larger than FalseC (the false value).
9133       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9134
9135       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9136         CC = X86::GetOppositeBranchCondition(CC);
9137         std::swap(TrueC, FalseC);
9138       }
9139
9140       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9141       // This is efficient for any integer data type (including i8/i16) and
9142       // shift amount.
9143       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9144         SDValue Cond = N->getOperand(3);
9145         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9146                            DAG.getConstant(CC, MVT::i8), Cond);
9147
9148         // Zero extend the condition if needed.
9149         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9150
9151         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9152         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9153                            DAG.getConstant(ShAmt, MVT::i8));
9154         if (N->getNumValues() == 2)  // Dead flag value?
9155           return DCI.CombineTo(N, Cond, SDValue());
9156         return Cond;
9157       }
9158
9159       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9160       // for any integer data type, including i8/i16.
9161       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9162         SDValue Cond = N->getOperand(3);
9163         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9164                            DAG.getConstant(CC, MVT::i8), Cond);
9165
9166         // Zero extend the condition if needed.
9167         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9168                            FalseC->getValueType(0), Cond);
9169         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9170                            SDValue(FalseC, 0));
9171
9172         if (N->getNumValues() == 2)  // Dead flag value?
9173           return DCI.CombineTo(N, Cond, SDValue());
9174         return Cond;
9175       }
9176
9177       // Optimize cases that will turn into an LEA instruction.  This requires
9178       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9179       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9180         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9181         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9182
9183         bool isFastMultiplier = false;
9184         if (Diff < 10) {
9185           switch ((unsigned char)Diff) {
9186           default: break;
9187           case 1:  // result = add base, cond
9188           case 2:  // result = lea base(    , cond*2)
9189           case 3:  // result = lea base(cond, cond*2)
9190           case 4:  // result = lea base(    , cond*4)
9191           case 5:  // result = lea base(cond, cond*4)
9192           case 8:  // result = lea base(    , cond*8)
9193           case 9:  // result = lea base(cond, cond*8)
9194             isFastMultiplier = true;
9195             break;
9196           }
9197         }
9198
9199         if (isFastMultiplier) {
9200           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9201           SDValue Cond = N->getOperand(3);
9202           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9203                              DAG.getConstant(CC, MVT::i8), Cond);
9204           // Zero extend the condition if needed.
9205           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9206                              Cond);
9207           // Scale the condition by the difference.
9208           if (Diff != 1)
9209             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9210                                DAG.getConstant(Diff, Cond.getValueType()));
9211
9212           // Add the base if non-zero.
9213           if (FalseC->getAPIntValue() != 0)
9214             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9215                                SDValue(FalseC, 0));
9216           if (N->getNumValues() == 2)  // Dead flag value?
9217             return DCI.CombineTo(N, Cond, SDValue());
9218           return Cond;
9219         }
9220       }
9221     }
9222   }
9223   return SDValue();
9224 }
9225
9226
9227 /// PerformMulCombine - Optimize a single multiply with constant into two
9228 /// in order to implement it with two cheaper instructions, e.g.
9229 /// LEA + SHL, LEA + LEA.
9230 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9231                                  TargetLowering::DAGCombinerInfo &DCI) {
9232   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9233     return SDValue();
9234
9235   EVT VT = N->getValueType(0);
9236   if (VT != MVT::i64)
9237     return SDValue();
9238
9239   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9240   if (!C)
9241     return SDValue();
9242   uint64_t MulAmt = C->getZExtValue();
9243   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9244     return SDValue();
9245
9246   uint64_t MulAmt1 = 0;
9247   uint64_t MulAmt2 = 0;
9248   if ((MulAmt % 9) == 0) {
9249     MulAmt1 = 9;
9250     MulAmt2 = MulAmt / 9;
9251   } else if ((MulAmt % 5) == 0) {
9252     MulAmt1 = 5;
9253     MulAmt2 = MulAmt / 5;
9254   } else if ((MulAmt % 3) == 0) {
9255     MulAmt1 = 3;
9256     MulAmt2 = MulAmt / 3;
9257   }
9258   if (MulAmt2 &&
9259       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9260     DebugLoc DL = N->getDebugLoc();
9261
9262     if (isPowerOf2_64(MulAmt2) &&
9263         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9264       // If second multiplifer is pow2, issue it first. We want the multiply by
9265       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9266       // is an add.
9267       std::swap(MulAmt1, MulAmt2);
9268
9269     SDValue NewMul;
9270     if (isPowerOf2_64(MulAmt1))
9271       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9272                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9273     else
9274       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9275                            DAG.getConstant(MulAmt1, VT));
9276
9277     if (isPowerOf2_64(MulAmt2))
9278       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9279                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9280     else
9281       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9282                            DAG.getConstant(MulAmt2, VT));
9283
9284     // Do not add new nodes to DAG combiner worklist.
9285     DCI.CombineTo(N, NewMul, false);
9286   }
9287   return SDValue();
9288 }
9289
9290 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9291   SDValue N0 = N->getOperand(0);
9292   SDValue N1 = N->getOperand(1);
9293   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9294   EVT VT = N0.getValueType();
9295
9296   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9297   // since the result of setcc_c is all zero's or all ones.
9298   if (N1C && N0.getOpcode() == ISD::AND &&
9299       N0.getOperand(1).getOpcode() == ISD::Constant) {
9300     SDValue N00 = N0.getOperand(0);
9301     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9302         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9303           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9304          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9305       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9306       APInt ShAmt = N1C->getAPIntValue();
9307       Mask = Mask.shl(ShAmt);
9308       if (Mask != 0)
9309         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9310                            N00, DAG.getConstant(Mask, VT));
9311     }
9312   }
9313
9314   return SDValue();
9315 }
9316
9317 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9318 ///                       when possible.
9319 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9320                                    const X86Subtarget *Subtarget) {
9321   EVT VT = N->getValueType(0);
9322   if (!VT.isVector() && VT.isInteger() &&
9323       N->getOpcode() == ISD::SHL)
9324     return PerformSHLCombine(N, DAG);
9325
9326   // On X86 with SSE2 support, we can transform this to a vector shift if
9327   // all elements are shifted by the same amount.  We can't do this in legalize
9328   // because the a constant vector is typically transformed to a constant pool
9329   // so we have no knowledge of the shift amount.
9330   if (!Subtarget->hasSSE2())
9331     return SDValue();
9332
9333   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9334     return SDValue();
9335
9336   SDValue ShAmtOp = N->getOperand(1);
9337   EVT EltVT = VT.getVectorElementType();
9338   DebugLoc DL = N->getDebugLoc();
9339   SDValue BaseShAmt = SDValue();
9340   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9341     unsigned NumElts = VT.getVectorNumElements();
9342     unsigned i = 0;
9343     for (; i != NumElts; ++i) {
9344       SDValue Arg = ShAmtOp.getOperand(i);
9345       if (Arg.getOpcode() == ISD::UNDEF) continue;
9346       BaseShAmt = Arg;
9347       break;
9348     }
9349     for (; i != NumElts; ++i) {
9350       SDValue Arg = ShAmtOp.getOperand(i);
9351       if (Arg.getOpcode() == ISD::UNDEF) continue;
9352       if (Arg != BaseShAmt) {
9353         return SDValue();
9354       }
9355     }
9356   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9357              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9358     SDValue InVec = ShAmtOp.getOperand(0);
9359     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9360       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9361       unsigned i = 0;
9362       for (; i != NumElts; ++i) {
9363         SDValue Arg = InVec.getOperand(i);
9364         if (Arg.getOpcode() == ISD::UNDEF) continue;
9365         BaseShAmt = Arg;
9366         break;
9367       }
9368     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9369        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9370          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9371          if (C->getZExtValue() == SplatIdx)
9372            BaseShAmt = InVec.getOperand(1);
9373        }
9374     }
9375     if (BaseShAmt.getNode() == 0)
9376       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9377                               DAG.getIntPtrConstant(0));
9378   } else
9379     return SDValue();
9380
9381   // The shift amount is an i32.
9382   if (EltVT.bitsGT(MVT::i32))
9383     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9384   else if (EltVT.bitsLT(MVT::i32))
9385     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9386
9387   // The shift amount is identical so we can do a vector shift.
9388   SDValue  ValOp = N->getOperand(0);
9389   switch (N->getOpcode()) {
9390   default:
9391     llvm_unreachable("Unknown shift opcode!");
9392     break;
9393   case ISD::SHL:
9394     if (VT == MVT::v2i64)
9395       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9396                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9397                          ValOp, BaseShAmt);
9398     if (VT == MVT::v4i32)
9399       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9400                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9401                          ValOp, BaseShAmt);
9402     if (VT == MVT::v8i16)
9403       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9404                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9405                          ValOp, BaseShAmt);
9406     break;
9407   case ISD::SRA:
9408     if (VT == MVT::v4i32)
9409       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9410                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9411                          ValOp, BaseShAmt);
9412     if (VT == MVT::v8i16)
9413       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9414                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9415                          ValOp, BaseShAmt);
9416     break;
9417   case ISD::SRL:
9418     if (VT == MVT::v2i64)
9419       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9420                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9421                          ValOp, BaseShAmt);
9422     if (VT == MVT::v4i32)
9423       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9424                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9425                          ValOp, BaseShAmt);
9426     if (VT ==  MVT::v8i16)
9427       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9428                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9429                          ValOp, BaseShAmt);
9430     break;
9431   }
9432   return SDValue();
9433 }
9434
9435 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9436                                 TargetLowering::DAGCombinerInfo &DCI,
9437                                 const X86Subtarget *Subtarget) {
9438   if (DCI.isBeforeLegalizeOps())
9439     return SDValue();
9440
9441   EVT VT = N->getValueType(0);
9442   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9443     return SDValue();
9444
9445   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9446   SDValue N0 = N->getOperand(0);
9447   SDValue N1 = N->getOperand(1);
9448   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9449     std::swap(N0, N1);
9450   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9451     return SDValue();
9452   if (!N0.hasOneUse() || !N1.hasOneUse())
9453     return SDValue();
9454
9455   SDValue ShAmt0 = N0.getOperand(1);
9456   if (ShAmt0.getValueType() != MVT::i8)
9457     return SDValue();
9458   SDValue ShAmt1 = N1.getOperand(1);
9459   if (ShAmt1.getValueType() != MVT::i8)
9460     return SDValue();
9461   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9462     ShAmt0 = ShAmt0.getOperand(0);
9463   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9464     ShAmt1 = ShAmt1.getOperand(0);
9465
9466   DebugLoc DL = N->getDebugLoc();
9467   unsigned Opc = X86ISD::SHLD;
9468   SDValue Op0 = N0.getOperand(0);
9469   SDValue Op1 = N1.getOperand(0);
9470   if (ShAmt0.getOpcode() == ISD::SUB) {
9471     Opc = X86ISD::SHRD;
9472     std::swap(Op0, Op1);
9473     std::swap(ShAmt0, ShAmt1);
9474   }
9475
9476   unsigned Bits = VT.getSizeInBits();
9477   if (ShAmt1.getOpcode() == ISD::SUB) {
9478     SDValue Sum = ShAmt1.getOperand(0);
9479     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9480       if (SumC->getSExtValue() == Bits &&
9481           ShAmt1.getOperand(1) == ShAmt0)
9482         return DAG.getNode(Opc, DL, VT,
9483                            Op0, Op1,
9484                            DAG.getNode(ISD::TRUNCATE, DL,
9485                                        MVT::i8, ShAmt0));
9486     }
9487   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9488     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9489     if (ShAmt0C &&
9490         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9491       return DAG.getNode(Opc, DL, VT,
9492                          N0.getOperand(0), N1.getOperand(0),
9493                          DAG.getNode(ISD::TRUNCATE, DL,
9494                                        MVT::i8, ShAmt0));
9495   }
9496
9497   return SDValue();
9498 }
9499
9500 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9501 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9502                                    const X86Subtarget *Subtarget) {
9503   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9504   // the FP state in cases where an emms may be missing.
9505   // A preferable solution to the general problem is to figure out the right
9506   // places to insert EMMS.  This qualifies as a quick hack.
9507
9508   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9509   StoreSDNode *St = cast<StoreSDNode>(N);
9510   EVT VT = St->getValue().getValueType();
9511   if (VT.getSizeInBits() != 64)
9512     return SDValue();
9513
9514   const Function *F = DAG.getMachineFunction().getFunction();
9515   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9516   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9517     && Subtarget->hasSSE2();
9518   if ((VT.isVector() ||
9519        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9520       isa<LoadSDNode>(St->getValue()) &&
9521       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9522       St->getChain().hasOneUse() && !St->isVolatile()) {
9523     SDNode* LdVal = St->getValue().getNode();
9524     LoadSDNode *Ld = 0;
9525     int TokenFactorIndex = -1;
9526     SmallVector<SDValue, 8> Ops;
9527     SDNode* ChainVal = St->getChain().getNode();
9528     // Must be a store of a load.  We currently handle two cases:  the load
9529     // is a direct child, and it's under an intervening TokenFactor.  It is
9530     // possible to dig deeper under nested TokenFactors.
9531     if (ChainVal == LdVal)
9532       Ld = cast<LoadSDNode>(St->getChain());
9533     else if (St->getValue().hasOneUse() &&
9534              ChainVal->getOpcode() == ISD::TokenFactor) {
9535       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9536         if (ChainVal->getOperand(i).getNode() == LdVal) {
9537           TokenFactorIndex = i;
9538           Ld = cast<LoadSDNode>(St->getValue());
9539         } else
9540           Ops.push_back(ChainVal->getOperand(i));
9541       }
9542     }
9543
9544     if (!Ld || !ISD::isNormalLoad(Ld))
9545       return SDValue();
9546
9547     // If this is not the MMX case, i.e. we are just turning i64 load/store
9548     // into f64 load/store, avoid the transformation if there are multiple
9549     // uses of the loaded value.
9550     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9551       return SDValue();
9552
9553     DebugLoc LdDL = Ld->getDebugLoc();
9554     DebugLoc StDL = N->getDebugLoc();
9555     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9556     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9557     // pair instead.
9558     if (Subtarget->is64Bit() || F64IsLegal) {
9559       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9560       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9561                                   Ld->getBasePtr(), Ld->getSrcValue(),
9562                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9563                                   Ld->isNonTemporal(), Ld->getAlignment());
9564       SDValue NewChain = NewLd.getValue(1);
9565       if (TokenFactorIndex != -1) {
9566         Ops.push_back(NewChain);
9567         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9568                                Ops.size());
9569       }
9570       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9571                           St->getSrcValue(), St->getSrcValueOffset(),
9572                           St->isVolatile(), St->isNonTemporal(),
9573                           St->getAlignment());
9574     }
9575
9576     // Otherwise, lower to two pairs of 32-bit loads / stores.
9577     SDValue LoAddr = Ld->getBasePtr();
9578     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9579                                  DAG.getConstant(4, MVT::i32));
9580
9581     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9582                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9583                                Ld->isVolatile(), Ld->isNonTemporal(),
9584                                Ld->getAlignment());
9585     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9586                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9587                                Ld->isVolatile(), Ld->isNonTemporal(),
9588                                MinAlign(Ld->getAlignment(), 4));
9589
9590     SDValue NewChain = LoLd.getValue(1);
9591     if (TokenFactorIndex != -1) {
9592       Ops.push_back(LoLd);
9593       Ops.push_back(HiLd);
9594       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9595                              Ops.size());
9596     }
9597
9598     LoAddr = St->getBasePtr();
9599     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9600                          DAG.getConstant(4, MVT::i32));
9601
9602     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9603                                 St->getSrcValue(), St->getSrcValueOffset(),
9604                                 St->isVolatile(), St->isNonTemporal(),
9605                                 St->getAlignment());
9606     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9607                                 St->getSrcValue(),
9608                                 St->getSrcValueOffset() + 4,
9609                                 St->isVolatile(),
9610                                 St->isNonTemporal(),
9611                                 MinAlign(St->getAlignment(), 4));
9612     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9613   }
9614   return SDValue();
9615 }
9616
9617 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9618 /// X86ISD::FXOR nodes.
9619 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9620   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9621   // F[X]OR(0.0, x) -> x
9622   // F[X]OR(x, 0.0) -> x
9623   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9624     if (C->getValueAPF().isPosZero())
9625       return N->getOperand(1);
9626   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9627     if (C->getValueAPF().isPosZero())
9628       return N->getOperand(0);
9629   return SDValue();
9630 }
9631
9632 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9633 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9634   // FAND(0.0, x) -> 0.0
9635   // FAND(x, 0.0) -> 0.0
9636   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9637     if (C->getValueAPF().isPosZero())
9638       return N->getOperand(0);
9639   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9640     if (C->getValueAPF().isPosZero())
9641       return N->getOperand(1);
9642   return SDValue();
9643 }
9644
9645 static SDValue PerformBTCombine(SDNode *N,
9646                                 SelectionDAG &DAG,
9647                                 TargetLowering::DAGCombinerInfo &DCI) {
9648   // BT ignores high bits in the bit index operand.
9649   SDValue Op1 = N->getOperand(1);
9650   if (Op1.hasOneUse()) {
9651     unsigned BitWidth = Op1.getValueSizeInBits();
9652     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9653     APInt KnownZero, KnownOne;
9654     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9655                                           !DCI.isBeforeLegalizeOps());
9656     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9657     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9658         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9659       DCI.CommitTargetLoweringOpt(TLO);
9660   }
9661   return SDValue();
9662 }
9663
9664 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9665   SDValue Op = N->getOperand(0);
9666   if (Op.getOpcode() == ISD::BIT_CONVERT)
9667     Op = Op.getOperand(0);
9668   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9669   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9670       VT.getVectorElementType().getSizeInBits() ==
9671       OpVT.getVectorElementType().getSizeInBits()) {
9672     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9673   }
9674   return SDValue();
9675 }
9676
9677 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9678 // Locked instructions, in turn, have implicit fence semantics (all memory
9679 // operations are flushed before issuing the locked instruction, and the
9680 // are not buffered), so we can fold away the common pattern of
9681 // fence-atomic-fence.
9682 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9683   SDValue atomic = N->getOperand(0);
9684   switch (atomic.getOpcode()) {
9685     case ISD::ATOMIC_CMP_SWAP:
9686     case ISD::ATOMIC_SWAP:
9687     case ISD::ATOMIC_LOAD_ADD:
9688     case ISD::ATOMIC_LOAD_SUB:
9689     case ISD::ATOMIC_LOAD_AND:
9690     case ISD::ATOMIC_LOAD_OR:
9691     case ISD::ATOMIC_LOAD_XOR:
9692     case ISD::ATOMIC_LOAD_NAND:
9693     case ISD::ATOMIC_LOAD_MIN:
9694     case ISD::ATOMIC_LOAD_MAX:
9695     case ISD::ATOMIC_LOAD_UMIN:
9696     case ISD::ATOMIC_LOAD_UMAX:
9697       break;
9698     default:
9699       return SDValue();
9700   }
9701
9702   SDValue fence = atomic.getOperand(0);
9703   if (fence.getOpcode() != ISD::MEMBARRIER)
9704     return SDValue();
9705
9706   switch (atomic.getOpcode()) {
9707     case ISD::ATOMIC_CMP_SWAP:
9708       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9709                                     atomic.getOperand(1), atomic.getOperand(2),
9710                                     atomic.getOperand(3));
9711     case ISD::ATOMIC_SWAP:
9712     case ISD::ATOMIC_LOAD_ADD:
9713     case ISD::ATOMIC_LOAD_SUB:
9714     case ISD::ATOMIC_LOAD_AND:
9715     case ISD::ATOMIC_LOAD_OR:
9716     case ISD::ATOMIC_LOAD_XOR:
9717     case ISD::ATOMIC_LOAD_NAND:
9718     case ISD::ATOMIC_LOAD_MIN:
9719     case ISD::ATOMIC_LOAD_MAX:
9720     case ISD::ATOMIC_LOAD_UMIN:
9721     case ISD::ATOMIC_LOAD_UMAX:
9722       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9723                                     atomic.getOperand(1), atomic.getOperand(2));
9724     default:
9725       return SDValue();
9726   }
9727 }
9728
9729 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9730   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9731   //           (and (i32 x86isd::setcc_carry), 1)
9732   // This eliminates the zext. This transformation is necessary because
9733   // ISD::SETCC is always legalized to i8.
9734   DebugLoc dl = N->getDebugLoc();
9735   SDValue N0 = N->getOperand(0);
9736   EVT VT = N->getValueType(0);
9737   if (N0.getOpcode() == ISD::AND &&
9738       N0.hasOneUse() &&
9739       N0.getOperand(0).hasOneUse()) {
9740     SDValue N00 = N0.getOperand(0);
9741     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9742       return SDValue();
9743     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9744     if (!C || C->getZExtValue() != 1)
9745       return SDValue();
9746     return DAG.getNode(ISD::AND, dl, VT,
9747                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9748                                    N00.getOperand(0), N00.getOperand(1)),
9749                        DAG.getConstant(1, VT));
9750   }
9751
9752   return SDValue();
9753 }
9754
9755 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9756                                              DAGCombinerInfo &DCI) const {
9757   SelectionDAG &DAG = DCI.DAG;
9758   switch (N->getOpcode()) {
9759   default: break;
9760   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9761   case ISD::EXTRACT_VECTOR_ELT:
9762                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9763   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9764   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9765   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9766   case ISD::SHL:
9767   case ISD::SRA:
9768   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9769   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
9770   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9771   case X86ISD::FXOR:
9772   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9773   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9774   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9775   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9776   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9777   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9778   }
9779
9780   return SDValue();
9781 }
9782
9783 /// isTypeDesirableForOp - Return true if the target has native support for
9784 /// the specified value type and it is 'desirable' to use the type for the
9785 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9786 /// instruction encodings are longer and some i16 instructions are slow.
9787 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9788   if (!isTypeLegal(VT))
9789     return false;
9790   if (VT != MVT::i16)
9791     return true;
9792
9793   switch (Opc) {
9794   default:
9795     return true;
9796   case ISD::LOAD:
9797   case ISD::SIGN_EXTEND:
9798   case ISD::ZERO_EXTEND:
9799   case ISD::ANY_EXTEND:
9800   case ISD::SHL:
9801   case ISD::SRL:
9802   case ISD::SUB:
9803   case ISD::ADD:
9804   case ISD::MUL:
9805   case ISD::AND:
9806   case ISD::OR:
9807   case ISD::XOR:
9808     return false;
9809   }
9810 }
9811
9812 static bool MayFoldLoad(SDValue Op) {
9813   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9814 }
9815
9816 static bool MayFoldIntoStore(SDValue Op) {
9817   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9818 }
9819
9820 /// IsDesirableToPromoteOp - This method query the target whether it is
9821 /// beneficial for dag combiner to promote the specified node. If true, it
9822 /// should return the desired promotion type by reference.
9823 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9824   EVT VT = Op.getValueType();
9825   if (VT != MVT::i16)
9826     return false;
9827
9828   bool Promote = false;
9829   bool Commute = false;
9830   switch (Op.getOpcode()) {
9831   default: break;
9832   case ISD::LOAD: {
9833     LoadSDNode *LD = cast<LoadSDNode>(Op);
9834     // If the non-extending load has a single use and it's not live out, then it
9835     // might be folded.
9836     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9837                                                      Op.hasOneUse()*/) {
9838       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9839              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9840         // The only case where we'd want to promote LOAD (rather then it being
9841         // promoted as an operand is when it's only use is liveout.
9842         if (UI->getOpcode() != ISD::CopyToReg)
9843           return false;
9844       }
9845     }
9846     Promote = true;
9847     break;
9848   }
9849   case ISD::SIGN_EXTEND:
9850   case ISD::ZERO_EXTEND:
9851   case ISD::ANY_EXTEND:
9852     Promote = true;
9853     break;
9854   case ISD::SHL:
9855   case ISD::SRL: {
9856     SDValue N0 = Op.getOperand(0);
9857     // Look out for (store (shl (load), x)).
9858     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9859       return false;
9860     Promote = true;
9861     break;
9862   }
9863   case ISD::ADD:
9864   case ISD::MUL:
9865   case ISD::AND:
9866   case ISD::OR:
9867   case ISD::XOR:
9868     Commute = true;
9869     // fallthrough
9870   case ISD::SUB: {
9871     SDValue N0 = Op.getOperand(0);
9872     SDValue N1 = Op.getOperand(1);
9873     if (!Commute && MayFoldLoad(N1))
9874       return false;
9875     // Avoid disabling potential load folding opportunities.
9876     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9877       return false;
9878     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9879       return false;
9880     Promote = true;
9881   }
9882   }
9883
9884   PVT = MVT::i32;
9885   return Promote;
9886 }
9887
9888 //===----------------------------------------------------------------------===//
9889 //                           X86 Inline Assembly Support
9890 //===----------------------------------------------------------------------===//
9891
9892 static bool LowerToBSwap(CallInst *CI) {
9893   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9894   // we will turn this bswap into something that will be lowered to logical ops
9895   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9896   // so don't worry about this.
9897
9898   // Verify this is a simple bswap.
9899   if (CI->getNumOperands() != 2 ||
9900       CI->getType() != CI->getOperand(1)->getType() ||
9901       !CI->getType()->isIntegerTy())
9902     return false;
9903
9904   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9905   if (!Ty || Ty->getBitWidth() % 16 != 0)
9906     return false;
9907
9908   // Okay, we can do this xform, do so now.
9909   const Type *Tys[] = { Ty };
9910   Module *M = CI->getParent()->getParent()->getParent();
9911   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9912
9913   Value *Op = CI->getOperand(1);
9914   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9915
9916   CI->replaceAllUsesWith(Op);
9917   CI->eraseFromParent();
9918   return true;
9919 }
9920
9921 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9922   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9923   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9924
9925   std::string AsmStr = IA->getAsmString();
9926
9927   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9928   SmallVector<StringRef, 4> AsmPieces;
9929   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9930
9931   switch (AsmPieces.size()) {
9932   default: return false;
9933   case 1:
9934     AsmStr = AsmPieces[0];
9935     AsmPieces.clear();
9936     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9937
9938     // bswap $0
9939     if (AsmPieces.size() == 2 &&
9940         (AsmPieces[0] == "bswap" ||
9941          AsmPieces[0] == "bswapq" ||
9942          AsmPieces[0] == "bswapl") &&
9943         (AsmPieces[1] == "$0" ||
9944          AsmPieces[1] == "${0:q}")) {
9945       // No need to check constraints, nothing other than the equivalent of
9946       // "=r,0" would be valid here.
9947       return LowerToBSwap(CI);
9948     }
9949     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9950     if (CI->getType()->isIntegerTy(16) &&
9951         AsmPieces.size() == 3 &&
9952         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9953         AsmPieces[1] == "$$8," &&
9954         AsmPieces[2] == "${0:w}" &&
9955         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9956       AsmPieces.clear();
9957       const std::string &Constraints = IA->getConstraintString();
9958       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9959       std::sort(AsmPieces.begin(), AsmPieces.end());
9960       if (AsmPieces.size() == 4 &&
9961           AsmPieces[0] == "~{cc}" &&
9962           AsmPieces[1] == "~{dirflag}" &&
9963           AsmPieces[2] == "~{flags}" &&
9964           AsmPieces[3] == "~{fpsr}") {
9965         return LowerToBSwap(CI);
9966       }
9967     }
9968     break;
9969   case 3:
9970     if (CI->getType()->isIntegerTy(64) &&
9971         Constraints.size() >= 2 &&
9972         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9973         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9974       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9975       SmallVector<StringRef, 4> Words;
9976       SplitString(AsmPieces[0], Words, " \t");
9977       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9978         Words.clear();
9979         SplitString(AsmPieces[1], Words, " \t");
9980         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9981           Words.clear();
9982           SplitString(AsmPieces[2], Words, " \t,");
9983           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9984               Words[2] == "%edx") {
9985             return LowerToBSwap(CI);
9986           }
9987         }
9988       }
9989     }
9990     break;
9991   }
9992   return false;
9993 }
9994
9995
9996
9997 /// getConstraintType - Given a constraint letter, return the type of
9998 /// constraint it is for this target.
9999 X86TargetLowering::ConstraintType
10000 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10001   if (Constraint.size() == 1) {
10002     switch (Constraint[0]) {
10003     case 'A':
10004       return C_Register;
10005     case 'f':
10006     case 'r':
10007     case 'R':
10008     case 'l':
10009     case 'q':
10010     case 'Q':
10011     case 'x':
10012     case 'y':
10013     case 'Y':
10014       return C_RegisterClass;
10015     case 'e':
10016     case 'Z':
10017       return C_Other;
10018     default:
10019       break;
10020     }
10021   }
10022   return TargetLowering::getConstraintType(Constraint);
10023 }
10024
10025 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10026 /// with another that has more specific requirements based on the type of the
10027 /// corresponding operand.
10028 const char *X86TargetLowering::
10029 LowerXConstraint(EVT ConstraintVT) const {
10030   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10031   // 'f' like normal targets.
10032   if (ConstraintVT.isFloatingPoint()) {
10033     if (Subtarget->hasSSE2())
10034       return "Y";
10035     if (Subtarget->hasSSE1())
10036       return "x";
10037   }
10038
10039   return TargetLowering::LowerXConstraint(ConstraintVT);
10040 }
10041
10042 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10043 /// vector.  If it is invalid, don't add anything to Ops.
10044 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10045                                                      char Constraint,
10046                                                      bool hasMemory,
10047                                                      std::vector<SDValue>&Ops,
10048                                                      SelectionDAG &DAG) const {
10049   SDValue Result(0, 0);
10050
10051   switch (Constraint) {
10052   default: break;
10053   case 'I':
10054     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10055       if (C->getZExtValue() <= 31) {
10056         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10057         break;
10058       }
10059     }
10060     return;
10061   case 'J':
10062     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10063       if (C->getZExtValue() <= 63) {
10064         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10065         break;
10066       }
10067     }
10068     return;
10069   case 'K':
10070     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10071       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10072         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10073         break;
10074       }
10075     }
10076     return;
10077   case 'N':
10078     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10079       if (C->getZExtValue() <= 255) {
10080         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10081         break;
10082       }
10083     }
10084     return;
10085   case 'e': {
10086     // 32-bit signed value
10087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10088       const ConstantInt *CI = C->getConstantIntValue();
10089       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10090                                   C->getSExtValue())) {
10091         // Widen to 64 bits here to get it sign extended.
10092         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10093         break;
10094       }
10095     // FIXME gcc accepts some relocatable values here too, but only in certain
10096     // memory models; it's complicated.
10097     }
10098     return;
10099   }
10100   case 'Z': {
10101     // 32-bit unsigned value
10102     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10103       const ConstantInt *CI = C->getConstantIntValue();
10104       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10105                                   C->getZExtValue())) {
10106         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10107         break;
10108       }
10109     }
10110     // FIXME gcc accepts some relocatable values here too, but only in certain
10111     // memory models; it's complicated.
10112     return;
10113   }
10114   case 'i': {
10115     // Literal immediates are always ok.
10116     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10117       // Widen to 64 bits here to get it sign extended.
10118       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10119       break;
10120     }
10121
10122     // If we are in non-pic codegen mode, we allow the address of a global (with
10123     // an optional displacement) to be used with 'i'.
10124     GlobalAddressSDNode *GA = 0;
10125     int64_t Offset = 0;
10126
10127     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10128     while (1) {
10129       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10130         Offset += GA->getOffset();
10131         break;
10132       } else if (Op.getOpcode() == ISD::ADD) {
10133         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10134           Offset += C->getZExtValue();
10135           Op = Op.getOperand(0);
10136           continue;
10137         }
10138       } else if (Op.getOpcode() == ISD::SUB) {
10139         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10140           Offset += -C->getZExtValue();
10141           Op = Op.getOperand(0);
10142           continue;
10143         }
10144       }
10145
10146       // Otherwise, this isn't something we can handle, reject it.
10147       return;
10148     }
10149
10150     const GlobalValue *GV = GA->getGlobal();
10151     // If we require an extra load to get this address, as in PIC mode, we
10152     // can't accept it.
10153     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10154                                                         getTargetMachine())))
10155       return;
10156
10157     if (hasMemory)
10158       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10159     else
10160       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10161     Result = Op;
10162     break;
10163   }
10164   }
10165
10166   if (Result.getNode()) {
10167     Ops.push_back(Result);
10168     return;
10169   }
10170   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10171                                                       Ops, DAG);
10172 }
10173
10174 std::vector<unsigned> X86TargetLowering::
10175 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10176                                   EVT VT) const {
10177   if (Constraint.size() == 1) {
10178     // FIXME: not handling fp-stack yet!
10179     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10180     default: break;  // Unknown constraint letter
10181     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10182       if (Subtarget->is64Bit()) {
10183         if (VT == MVT::i32)
10184           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10185                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10186                                        X86::R10D,X86::R11D,X86::R12D,
10187                                        X86::R13D,X86::R14D,X86::R15D,
10188                                        X86::EBP, X86::ESP, 0);
10189         else if (VT == MVT::i16)
10190           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10191                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10192                                        X86::R10W,X86::R11W,X86::R12W,
10193                                        X86::R13W,X86::R14W,X86::R15W,
10194                                        X86::BP,  X86::SP, 0);
10195         else if (VT == MVT::i8)
10196           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10197                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10198                                        X86::R10B,X86::R11B,X86::R12B,
10199                                        X86::R13B,X86::R14B,X86::R15B,
10200                                        X86::BPL, X86::SPL, 0);
10201
10202         else if (VT == MVT::i64)
10203           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10204                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10205                                        X86::R10, X86::R11, X86::R12,
10206                                        X86::R13, X86::R14, X86::R15,
10207                                        X86::RBP, X86::RSP, 0);
10208
10209         break;
10210       }
10211       // 32-bit fallthrough
10212     case 'Q':   // Q_REGS
10213       if (VT == MVT::i32)
10214         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10215       else if (VT == MVT::i16)
10216         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10217       else if (VT == MVT::i8)
10218         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10219       else if (VT == MVT::i64)
10220         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10221       break;
10222     }
10223   }
10224
10225   return std::vector<unsigned>();
10226 }
10227
10228 std::pair<unsigned, const TargetRegisterClass*>
10229 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10230                                                 EVT VT) const {
10231   // First, see if this is a constraint that directly corresponds to an LLVM
10232   // register class.
10233   if (Constraint.size() == 1) {
10234     // GCC Constraint Letters
10235     switch (Constraint[0]) {
10236     default: break;
10237     case 'r':   // GENERAL_REGS
10238     case 'l':   // INDEX_REGS
10239       if (VT == MVT::i8)
10240         return std::make_pair(0U, X86::GR8RegisterClass);
10241       if (VT == MVT::i16)
10242         return std::make_pair(0U, X86::GR16RegisterClass);
10243       if (VT == MVT::i32 || !Subtarget->is64Bit())
10244         return std::make_pair(0U, X86::GR32RegisterClass);
10245       return std::make_pair(0U, X86::GR64RegisterClass);
10246     case 'R':   // LEGACY_REGS
10247       if (VT == MVT::i8)
10248         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10249       if (VT == MVT::i16)
10250         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10251       if (VT == MVT::i32 || !Subtarget->is64Bit())
10252         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10253       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10254     case 'f':  // FP Stack registers.
10255       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10256       // value to the correct fpstack register class.
10257       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10258         return std::make_pair(0U, X86::RFP32RegisterClass);
10259       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10260         return std::make_pair(0U, X86::RFP64RegisterClass);
10261       return std::make_pair(0U, X86::RFP80RegisterClass);
10262     case 'y':   // MMX_REGS if MMX allowed.
10263       if (!Subtarget->hasMMX()) break;
10264       return std::make_pair(0U, X86::VR64RegisterClass);
10265     case 'Y':   // SSE_REGS if SSE2 allowed
10266       if (!Subtarget->hasSSE2()) break;
10267       // FALL THROUGH.
10268     case 'x':   // SSE_REGS if SSE1 allowed
10269       if (!Subtarget->hasSSE1()) break;
10270
10271       switch (VT.getSimpleVT().SimpleTy) {
10272       default: break;
10273       // Scalar SSE types.
10274       case MVT::f32:
10275       case MVT::i32:
10276         return std::make_pair(0U, X86::FR32RegisterClass);
10277       case MVT::f64:
10278       case MVT::i64:
10279         return std::make_pair(0U, X86::FR64RegisterClass);
10280       // Vector types.
10281       case MVT::v16i8:
10282       case MVT::v8i16:
10283       case MVT::v4i32:
10284       case MVT::v2i64:
10285       case MVT::v4f32:
10286       case MVT::v2f64:
10287         return std::make_pair(0U, X86::VR128RegisterClass);
10288       }
10289       break;
10290     }
10291   }
10292
10293   // Use the default implementation in TargetLowering to convert the register
10294   // constraint into a member of a register class.
10295   std::pair<unsigned, const TargetRegisterClass*> Res;
10296   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10297
10298   // Not found as a standard register?
10299   if (Res.second == 0) {
10300     // Map st(0) -> st(7) -> ST0
10301     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10302         tolower(Constraint[1]) == 's' &&
10303         tolower(Constraint[2]) == 't' &&
10304         Constraint[3] == '(' &&
10305         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10306         Constraint[5] == ')' &&
10307         Constraint[6] == '}') {
10308
10309       Res.first = X86::ST0+Constraint[4]-'0';
10310       Res.second = X86::RFP80RegisterClass;
10311       return Res;
10312     }
10313
10314     // GCC allows "st(0)" to be called just plain "st".
10315     if (StringRef("{st}").equals_lower(Constraint)) {
10316       Res.first = X86::ST0;
10317       Res.second = X86::RFP80RegisterClass;
10318       return Res;
10319     }
10320
10321     // flags -> EFLAGS
10322     if (StringRef("{flags}").equals_lower(Constraint)) {
10323       Res.first = X86::EFLAGS;
10324       Res.second = X86::CCRRegisterClass;
10325       return Res;
10326     }
10327
10328     // 'A' means EAX + EDX.
10329     if (Constraint == "A") {
10330       Res.first = X86::EAX;
10331       Res.second = X86::GR32_ADRegisterClass;
10332       return Res;
10333     }
10334     return Res;
10335   }
10336
10337   // Otherwise, check to see if this is a register class of the wrong value
10338   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10339   // turn into {ax},{dx}.
10340   if (Res.second->hasType(VT))
10341     return Res;   // Correct type already, nothing to do.
10342
10343   // All of the single-register GCC register classes map their values onto
10344   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10345   // really want an 8-bit or 32-bit register, map to the appropriate register
10346   // class and return the appropriate register.
10347   if (Res.second == X86::GR16RegisterClass) {
10348     if (VT == MVT::i8) {
10349       unsigned DestReg = 0;
10350       switch (Res.first) {
10351       default: break;
10352       case X86::AX: DestReg = X86::AL; break;
10353       case X86::DX: DestReg = X86::DL; break;
10354       case X86::CX: DestReg = X86::CL; break;
10355       case X86::BX: DestReg = X86::BL; break;
10356       }
10357       if (DestReg) {
10358         Res.first = DestReg;
10359         Res.second = X86::GR8RegisterClass;
10360       }
10361     } else if (VT == MVT::i32) {
10362       unsigned DestReg = 0;
10363       switch (Res.first) {
10364       default: break;
10365       case X86::AX: DestReg = X86::EAX; break;
10366       case X86::DX: DestReg = X86::EDX; break;
10367       case X86::CX: DestReg = X86::ECX; break;
10368       case X86::BX: DestReg = X86::EBX; break;
10369       case X86::SI: DestReg = X86::ESI; break;
10370       case X86::DI: DestReg = X86::EDI; break;
10371       case X86::BP: DestReg = X86::EBP; break;
10372       case X86::SP: DestReg = X86::ESP; break;
10373       }
10374       if (DestReg) {
10375         Res.first = DestReg;
10376         Res.second = X86::GR32RegisterClass;
10377       }
10378     } else if (VT == MVT::i64) {
10379       unsigned DestReg = 0;
10380       switch (Res.first) {
10381       default: break;
10382       case X86::AX: DestReg = X86::RAX; break;
10383       case X86::DX: DestReg = X86::RDX; break;
10384       case X86::CX: DestReg = X86::RCX; break;
10385       case X86::BX: DestReg = X86::RBX; break;
10386       case X86::SI: DestReg = X86::RSI; break;
10387       case X86::DI: DestReg = X86::RDI; break;
10388       case X86::BP: DestReg = X86::RBP; break;
10389       case X86::SP: DestReg = X86::RSP; break;
10390       }
10391       if (DestReg) {
10392         Res.first = DestReg;
10393         Res.second = X86::GR64RegisterClass;
10394       }
10395     }
10396   } else if (Res.second == X86::FR32RegisterClass ||
10397              Res.second == X86::FR64RegisterClass ||
10398              Res.second == X86::VR128RegisterClass) {
10399     // Handle references to XMM physical registers that got mapped into the
10400     // wrong class.  This can happen with constraints like {xmm0} where the
10401     // target independent register mapper will just pick the first match it can
10402     // find, ignoring the required type.
10403     if (VT == MVT::f32)
10404       Res.second = X86::FR32RegisterClass;
10405     else if (VT == MVT::f64)
10406       Res.second = X86::FR64RegisterClass;
10407     else if (X86::VR128RegisterClass->hasType(VT))
10408       Res.second = X86::VR128RegisterClass;
10409   }
10410
10411   return Res;
10412 }