PowerPC: Simplify FADD in round-to-zero mode.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC 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 implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
37 using namespace llvm;
38
39 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
40                                        CCValAssign::LocInfo &LocInfo,
41                                        ISD::ArgFlagsTy &ArgFlags,
42                                        CCState &State);
43 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
44                                               MVT &LocVT,
45                                               CCValAssign::LocInfo &LocInfo,
46                                               ISD::ArgFlagsTy &ArgFlags,
47                                               CCState &State);
48 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
49                                                 MVT &LocVT,
50                                                 CCValAssign::LocInfo &LocInfo,
51                                                 ISD::ArgFlagsTy &ArgFlags,
52                                                 CCState &State);
53
54 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
55 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
56
57 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
58 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
59
60 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
61 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
62
63 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
64   if (TM.getSubtargetImpl()->isDarwin())
65     return new TargetLoweringObjectFileMachO();
66
67   return new TargetLoweringObjectFileELF();
68 }
69
70 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
71   : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
72   const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
73   PPCRegInfo = TM.getRegisterInfo();
74
75   setPow2DivIsCheap();
76
77   // Use _setjmp/_longjmp instead of setjmp/longjmp.
78   setUseUnderscoreSetJmp(true);
79   setUseUnderscoreLongJmp(true);
80
81   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
82   // arguments are at least 4/8 bytes aligned.
83   bool isPPC64 = Subtarget->isPPC64();
84   setMinStackArgumentAlignment(isPPC64 ? 8:4);
85
86   // Set up the register classes.
87   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
88   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
89   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
90
91   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
92   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
94
95   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
96
97   // PowerPC has pre-inc load and store's.
98   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
99   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
100   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
101   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
102   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
103   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
104   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
105   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
106   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
107   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
108
109   // This is used in the ppcf128->int sequence.  Note it has different semantics
110   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
111   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
112
113   // We do not currently implement these libm ops for PowerPC.
114   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
115   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
116   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
117   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
118   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
119
120   // PowerPC has no SREM/UREM instructions
121   setOperationAction(ISD::SREM, MVT::i32, Expand);
122   setOperationAction(ISD::UREM, MVT::i32, Expand);
123   setOperationAction(ISD::SREM, MVT::i64, Expand);
124   setOperationAction(ISD::UREM, MVT::i64, Expand);
125
126   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
127   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
128   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
129   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
130   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
131   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
132   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
133   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
134   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
135
136   // We don't support sin/cos/sqrt/fmod/pow
137   setOperationAction(ISD::FSIN , MVT::f64, Expand);
138   setOperationAction(ISD::FCOS , MVT::f64, Expand);
139   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
140   setOperationAction(ISD::FREM , MVT::f64, Expand);
141   setOperationAction(ISD::FPOW , MVT::f64, Expand);
142   setOperationAction(ISD::FMA  , MVT::f64, Legal);
143   setOperationAction(ISD::FSIN , MVT::f32, Expand);
144   setOperationAction(ISD::FCOS , MVT::f32, Expand);
145   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
146   setOperationAction(ISD::FREM , MVT::f32, Expand);
147   setOperationAction(ISD::FPOW , MVT::f32, Expand);
148   setOperationAction(ISD::FMA  , MVT::f32, Legal);
149
150   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
151
152   // If we're enabling GP optimizations, use hardware square root
153   if (!Subtarget->hasFSQRT()) {
154     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
155     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
156   }
157
158   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
159   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
160
161   // PowerPC does not have BSWAP, CTPOP or CTTZ
162   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
163   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
164   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
165   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
166   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
167   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
168   setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
169   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
170   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
171   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
172
173   // PowerPC does not have ROTR
174   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
175   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
176
177   // PowerPC does not have Select
178   setOperationAction(ISD::SELECT, MVT::i32, Expand);
179   setOperationAction(ISD::SELECT, MVT::i64, Expand);
180   setOperationAction(ISD::SELECT, MVT::f32, Expand);
181   setOperationAction(ISD::SELECT, MVT::f64, Expand);
182
183   // PowerPC wants to turn select_cc of FP into fsel when possible.
184   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
186
187   // PowerPC wants to optimize integer setcc a bit
188   setOperationAction(ISD::SETCC, MVT::i32, Custom);
189
190   // PowerPC does not have BRCOND which requires SetCC
191   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
192
193   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
194
195   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
196   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
197
198   // PowerPC does not have [U|S]INT_TO_FP
199   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
200   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
201
202   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
203   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
204   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
205   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
206
207   // We cannot sextinreg(i1).  Expand to shifts.
208   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
209
210   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
211   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
212   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
213   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
214
215   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
216   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
217   // support continuation, user-level threading, and etc.. As a result, no
218   // other SjLj exception interfaces are implemented and please don't build
219   // your own exception handling based on them.
220   // LLVM/Clang supports zero-cost DWARF exception handling.
221   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
222   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
223
224   // We want to legalize GlobalAddress and ConstantPool nodes into the
225   // appropriate instructions to materialize the address.
226   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
227   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
228   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
229   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
230   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
231   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
233   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
234   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
235   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
236
237   // TRAP is legal.
238   setOperationAction(ISD::TRAP, MVT::Other, Legal);
239
240   // TRAMPOLINE is custom lowered.
241   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
242   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
243
244   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
245   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
246
247   if (Subtarget->isSVR4ABI()) {
248     if (isPPC64) {
249       // VAARG always uses double-word chunks, so promote anything smaller.
250       setOperationAction(ISD::VAARG, MVT::i1, Promote);
251       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
252       setOperationAction(ISD::VAARG, MVT::i8, Promote);
253       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
254       setOperationAction(ISD::VAARG, MVT::i16, Promote);
255       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
256       setOperationAction(ISD::VAARG, MVT::i32, Promote);
257       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
258       setOperationAction(ISD::VAARG, MVT::Other, Expand);
259     } else {
260       // VAARG is custom lowered with the 32-bit SVR4 ABI.
261       setOperationAction(ISD::VAARG, MVT::Other, Custom);
262       setOperationAction(ISD::VAARG, MVT::i64, Custom);
263     }
264   } else
265     setOperationAction(ISD::VAARG, MVT::Other, Expand);
266
267   // Use the default implementation.
268   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
269   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
270   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
271   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
272   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
273   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
274
275   // We want to custom lower some of our intrinsics.
276   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
277
278   // Comparisons that require checking two conditions.
279   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
280   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
281   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
282   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
283   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
284   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
285   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
286   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
287   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
288   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
289   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
290   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
291
292   if (Subtarget->has64BitSupport()) {
293     // They also have instructions for converting between i64 and fp.
294     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
295     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
297     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
298     // This is just the low 32 bits of a (signed) fp->i64 conversion.
299     // We cannot do this with Promote because i64 is not a legal type.
300     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
301
302     // FIXME: disable this lowered code.  This generates 64-bit register values,
303     // and we don't model the fact that the top part is clobbered by calls.  We
304     // need to flag these together so that the value isn't live across a call.
305     //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
306   } else {
307     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
308     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
309   }
310
311   if (Subtarget->use64BitRegs()) {
312     // 64-bit PowerPC implementations can support i64 types directly
313     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
314     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
315     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
316     // 64-bit PowerPC wants to expand i128 shifts itself.
317     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
318     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
319     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
320   } else {
321     // 32-bit PowerPC wants to expand i64 shifts itself.
322     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
323     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
324     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
325   }
326
327   if (Subtarget->hasAltivec()) {
328     // First set operation action for all vector types to expand. Then we
329     // will selectively turn on ones that can be effectively codegen'd.
330     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
331          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
332       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
333
334       // add/sub are legal for all supported vector VT's.
335       setOperationAction(ISD::ADD , VT, Legal);
336       setOperationAction(ISD::SUB , VT, Legal);
337
338       // We promote all shuffles to v16i8.
339       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
340       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
341
342       // We promote all non-typed operations to v4i32.
343       setOperationAction(ISD::AND   , VT, Promote);
344       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
345       setOperationAction(ISD::OR    , VT, Promote);
346       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
347       setOperationAction(ISD::XOR   , VT, Promote);
348       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
349       setOperationAction(ISD::LOAD  , VT, Promote);
350       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
351       setOperationAction(ISD::SELECT, VT, Promote);
352       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
353       setOperationAction(ISD::STORE, VT, Promote);
354       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
355
356       // No other operations are legal.
357       setOperationAction(ISD::MUL , VT, Expand);
358       setOperationAction(ISD::SDIV, VT, Expand);
359       setOperationAction(ISD::SREM, VT, Expand);
360       setOperationAction(ISD::UDIV, VT, Expand);
361       setOperationAction(ISD::UREM, VT, Expand);
362       setOperationAction(ISD::FDIV, VT, Expand);
363       setOperationAction(ISD::FNEG, VT, Expand);
364       setOperationAction(ISD::FSQRT, VT, Expand);
365       setOperationAction(ISD::FLOG, VT, Expand);
366       setOperationAction(ISD::FLOG10, VT, Expand);
367       setOperationAction(ISD::FLOG2, VT, Expand);
368       setOperationAction(ISD::FEXP, VT, Expand);
369       setOperationAction(ISD::FEXP2, VT, Expand);
370       setOperationAction(ISD::FSIN, VT, Expand);
371       setOperationAction(ISD::FCOS, VT, Expand);
372       setOperationAction(ISD::FABS, VT, Expand);
373       setOperationAction(ISD::FPOWI, VT, Expand);
374       setOperationAction(ISD::FFLOOR, VT, Expand);
375       setOperationAction(ISD::FCEIL,  VT, Expand);
376       setOperationAction(ISD::FTRUNC, VT, Expand);
377       setOperationAction(ISD::FRINT,  VT, Expand);
378       setOperationAction(ISD::FNEARBYINT, VT, Expand);
379       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
380       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
381       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
382       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
383       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
384       setOperationAction(ISD::UDIVREM, VT, Expand);
385       setOperationAction(ISD::SDIVREM, VT, Expand);
386       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
387       setOperationAction(ISD::FPOW, VT, Expand);
388       setOperationAction(ISD::CTPOP, VT, Expand);
389       setOperationAction(ISD::CTLZ, VT, Expand);
390       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
391       setOperationAction(ISD::CTTZ, VT, Expand);
392       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
393       setOperationAction(ISD::VSELECT, VT, Expand);
394       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
395
396       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
397            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
398         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
399         setTruncStoreAction(VT, InnerVT, Expand);
400       }
401       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
402       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
403       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
404     }
405
406     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
407     // with merges, splats, etc.
408     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
409
410     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
411     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
412     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
413     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
414     setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
415     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
416     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
417     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
418     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
419     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
420     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
421     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
422     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
423     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
424
425     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
426     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
427     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
428     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
429
430     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
431     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
432     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
433     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
434     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
435
436     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
437     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
438
439     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
440     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
441     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
442     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
443
444     // Altivec does not contain unordered floating-point compare instructions
445     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
446     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
447     setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
448     setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
449     setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
450     setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
451   }
452
453   if (Subtarget->has64BitSupport()) {
454     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
455     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
456   }
457
458   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
459   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
460   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
461   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
462
463   setBooleanContents(ZeroOrOneBooleanContent);
464   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
465
466   if (isPPC64) {
467     setStackPointerRegisterToSaveRestore(PPC::X1);
468     setExceptionPointerRegister(PPC::X3);
469     setExceptionSelectorRegister(PPC::X4);
470   } else {
471     setStackPointerRegisterToSaveRestore(PPC::R1);
472     setExceptionPointerRegister(PPC::R3);
473     setExceptionSelectorRegister(PPC::R4);
474   }
475
476   // We have target-specific dag combine patterns for the following nodes:
477   setTargetDAGCombine(ISD::SINT_TO_FP);
478   setTargetDAGCombine(ISD::STORE);
479   setTargetDAGCombine(ISD::BR_CC);
480   setTargetDAGCombine(ISD::BSWAP);
481
482   // Darwin long double math library functions have $LDBL128 appended.
483   if (Subtarget->isDarwin()) {
484     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
485     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
486     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
487     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
488     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
489     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
490     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
491     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
492     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
493     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
494   }
495
496   setMinFunctionAlignment(2);
497   if (PPCSubTarget.isDarwin())
498     setPrefFunctionAlignment(4);
499
500   if (isPPC64 && Subtarget->isJITCodeModel())
501     // Temporary workaround for the inability of PPC64 JIT to handle jump
502     // tables.
503     setSupportJumpTables(false);
504
505   setInsertFencesForAtomic(true);
506
507   setSchedulingPreference(Sched::Hybrid);
508
509   computeRegisterProperties();
510
511   // The Freescale cores does better with aggressive inlining of memcpy and
512   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
513   if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
514       Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
515     MaxStoresPerMemset = 32;
516     MaxStoresPerMemsetOptSize = 16;
517     MaxStoresPerMemcpy = 32;
518     MaxStoresPerMemcpyOptSize = 8;
519     MaxStoresPerMemmove = 32;
520     MaxStoresPerMemmoveOptSize = 8;
521
522     setPrefFunctionAlignment(4);
523     BenefitFromCodePlacementOpt = true;
524   }
525 }
526
527 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
528 /// function arguments in the caller parameter area.
529 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
530   const TargetMachine &TM = getTargetMachine();
531   // Darwin passes everything on 4 byte boundary.
532   if (TM.getSubtarget<PPCSubtarget>().isDarwin())
533     return 4;
534
535   // 16byte and wider vectors are passed on 16byte boundary.
536   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
537     if (VTy->getBitWidth() >= 128)
538       return 16;
539
540   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
541    if (PPCSubTarget.isPPC64())
542      return 8;
543
544   return 4;
545 }
546
547 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
548   switch (Opcode) {
549   default: return 0;
550   case PPCISD::FSEL:            return "PPCISD::FSEL";
551   case PPCISD::FCFID:           return "PPCISD::FCFID";
552   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
553   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
554   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
555   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
556   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
557   case PPCISD::VPERM:           return "PPCISD::VPERM";
558   case PPCISD::Hi:              return "PPCISD::Hi";
559   case PPCISD::Lo:              return "PPCISD::Lo";
560   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
561   case PPCISD::TOC_RESTORE:     return "PPCISD::TOC_RESTORE";
562   case PPCISD::LOAD:            return "PPCISD::LOAD";
563   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
564   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
565   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
566   case PPCISD::SRL:             return "PPCISD::SRL";
567   case PPCISD::SRA:             return "PPCISD::SRA";
568   case PPCISD::SHL:             return "PPCISD::SHL";
569   case PPCISD::EXTSW_32:        return "PPCISD::EXTSW_32";
570   case PPCISD::STD_32:          return "PPCISD::STD_32";
571   case PPCISD::CALL:            return "PPCISD::CALL";
572   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
573   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
574   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
575   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
576   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
577   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
578   case PPCISD::MFCR:            return "PPCISD::MFCR";
579   case PPCISD::VCMP:            return "PPCISD::VCMP";
580   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
581   case PPCISD::LBRX:            return "PPCISD::LBRX";
582   case PPCISD::STBRX:           return "PPCISD::STBRX";
583   case PPCISD::LARX:            return "PPCISD::LARX";
584   case PPCISD::STCX:            return "PPCISD::STCX";
585   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
586   case PPCISD::MFFS:            return "PPCISD::MFFS";
587   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
588   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
589   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
590   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
591   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
592   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
593   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
594   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
595   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
596   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
597   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
598   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
599   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
600   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
601   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
602   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
603   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
604   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
605   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
606   }
607 }
608
609 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
610   if (!VT.isVector())
611     return MVT::i32;
612   return VT.changeVectorElementTypeToInteger();
613 }
614
615 //===----------------------------------------------------------------------===//
616 // Node matching predicates, for use by the tblgen matching code.
617 //===----------------------------------------------------------------------===//
618
619 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
620 static bool isFloatingPointZero(SDValue Op) {
621   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
622     return CFP->getValueAPF().isZero();
623   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
624     // Maybe this has already been legalized into the constant pool?
625     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
626       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
627         return CFP->getValueAPF().isZero();
628   }
629   return false;
630 }
631
632 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
633 /// true if Op is undef or if it matches the specified value.
634 static bool isConstantOrUndef(int Op, int Val) {
635   return Op < 0 || Op == Val;
636 }
637
638 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
639 /// VPKUHUM instruction.
640 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
641   if (!isUnary) {
642     for (unsigned i = 0; i != 16; ++i)
643       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+1))
644         return false;
645   } else {
646     for (unsigned i = 0; i != 8; ++i)
647       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+1) ||
648           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+1))
649         return false;
650   }
651   return true;
652 }
653
654 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
655 /// VPKUWUM instruction.
656 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
657   if (!isUnary) {
658     for (unsigned i = 0; i != 16; i += 2)
659       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
660           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
661         return false;
662   } else {
663     for (unsigned i = 0; i != 8; i += 2)
664       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
665           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3) ||
666           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+2) ||
667           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+3))
668         return false;
669   }
670   return true;
671 }
672
673 /// isVMerge - Common function, used to match vmrg* shuffles.
674 ///
675 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
676                      unsigned LHSStart, unsigned RHSStart) {
677   assert(N->getValueType(0) == MVT::v16i8 &&
678          "PPC only supports shuffles by bytes!");
679   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
680          "Unsupported merge size!");
681
682   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
683     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
684       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
685                              LHSStart+j+i*UnitSize) ||
686           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
687                              RHSStart+j+i*UnitSize))
688         return false;
689     }
690   return true;
691 }
692
693 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
694 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
695 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
696                              bool isUnary) {
697   if (!isUnary)
698     return isVMerge(N, UnitSize, 8, 24);
699   return isVMerge(N, UnitSize, 8, 8);
700 }
701
702 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
703 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
704 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
705                              bool isUnary) {
706   if (!isUnary)
707     return isVMerge(N, UnitSize, 0, 16);
708   return isVMerge(N, UnitSize, 0, 0);
709 }
710
711
712 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
713 /// amount, otherwise return -1.
714 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
715   assert(N->getValueType(0) == MVT::v16i8 &&
716          "PPC only supports shuffles by bytes!");
717
718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
719
720   // Find the first non-undef value in the shuffle mask.
721   unsigned i;
722   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
723     /*search*/;
724
725   if (i == 16) return -1;  // all undef.
726
727   // Otherwise, check to see if the rest of the elements are consecutively
728   // numbered from this value.
729   unsigned ShiftAmt = SVOp->getMaskElt(i);
730   if (ShiftAmt < i) return -1;
731   ShiftAmt -= i;
732
733   if (!isUnary) {
734     // Check the rest of the elements to see if they are consecutive.
735     for (++i; i != 16; ++i)
736       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
737         return -1;
738   } else {
739     // Check the rest of the elements to see if they are consecutive.
740     for (++i; i != 16; ++i)
741       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
742         return -1;
743   }
744   return ShiftAmt;
745 }
746
747 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
748 /// specifies a splat of a single element that is suitable for input to
749 /// VSPLTB/VSPLTH/VSPLTW.
750 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
751   assert(N->getValueType(0) == MVT::v16i8 &&
752          (EltSize == 1 || EltSize == 2 || EltSize == 4));
753
754   // This is a splat operation if each element of the permute is the same, and
755   // if the value doesn't reference the second vector.
756   unsigned ElementBase = N->getMaskElt(0);
757
758   // FIXME: Handle UNDEF elements too!
759   if (ElementBase >= 16)
760     return false;
761
762   // Check that the indices are consecutive, in the case of a multi-byte element
763   // splatted with a v16i8 mask.
764   for (unsigned i = 1; i != EltSize; ++i)
765     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
766       return false;
767
768   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
769     if (N->getMaskElt(i) < 0) continue;
770     for (unsigned j = 0; j != EltSize; ++j)
771       if (N->getMaskElt(i+j) != N->getMaskElt(j))
772         return false;
773   }
774   return true;
775 }
776
777 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
778 /// are -0.0.
779 bool PPC::isAllNegativeZeroVector(SDNode *N) {
780   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
781
782   APInt APVal, APUndef;
783   unsigned BitSize;
784   bool HasAnyUndefs;
785
786   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
787     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
788       return CFP->getValueAPF().isNegZero();
789
790   return false;
791 }
792
793 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
794 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
795 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
797   assert(isSplatShuffleMask(SVOp, EltSize));
798   return SVOp->getMaskElt(0) / EltSize;
799 }
800
801 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
802 /// by using a vspltis[bhw] instruction of the specified element size, return
803 /// the constant being splatted.  The ByteSize field indicates the number of
804 /// bytes of each element [124] -> [bhw].
805 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
806   SDValue OpVal(0, 0);
807
808   // If ByteSize of the splat is bigger than the element size of the
809   // build_vector, then we have a case where we are checking for a splat where
810   // multiple elements of the buildvector are folded together into a single
811   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
812   unsigned EltSize = 16/N->getNumOperands();
813   if (EltSize < ByteSize) {
814     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
815     SDValue UniquedVals[4];
816     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
817
818     // See if all of the elements in the buildvector agree across.
819     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
820       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
821       // If the element isn't a constant, bail fully out.
822       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
823
824
825       if (UniquedVals[i&(Multiple-1)].getNode() == 0)
826         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
827       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
828         return SDValue();  // no match.
829     }
830
831     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
832     // either constant or undef values that are identical for each chunk.  See
833     // if these chunks can form into a larger vspltis*.
834
835     // Check to see if all of the leading entries are either 0 or -1.  If
836     // neither, then this won't fit into the immediate field.
837     bool LeadingZero = true;
838     bool LeadingOnes = true;
839     for (unsigned i = 0; i != Multiple-1; ++i) {
840       if (UniquedVals[i].getNode() == 0) continue;  // Must have been undefs.
841
842       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
843       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
844     }
845     // Finally, check the least significant entry.
846     if (LeadingZero) {
847       if (UniquedVals[Multiple-1].getNode() == 0)
848         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
849       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
850       if (Val < 16)
851         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
852     }
853     if (LeadingOnes) {
854       if (UniquedVals[Multiple-1].getNode() == 0)
855         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
856       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
857       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
858         return DAG.getTargetConstant(Val, MVT::i32);
859     }
860
861     return SDValue();
862   }
863
864   // Check to see if this buildvec has a single non-undef value in its elements.
865   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
866     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
867     if (OpVal.getNode() == 0)
868       OpVal = N->getOperand(i);
869     else if (OpVal != N->getOperand(i))
870       return SDValue();
871   }
872
873   if (OpVal.getNode() == 0) return SDValue();  // All UNDEF: use implicit def.
874
875   unsigned ValSizeInBytes = EltSize;
876   uint64_t Value = 0;
877   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
878     Value = CN->getZExtValue();
879   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
880     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
881     Value = FloatToBits(CN->getValueAPF().convertToFloat());
882   }
883
884   // If the splat value is larger than the element value, then we can never do
885   // this splat.  The only case that we could fit the replicated bits into our
886   // immediate field for would be zero, and we prefer to use vxor for it.
887   if (ValSizeInBytes < ByteSize) return SDValue();
888
889   // If the element value is larger than the splat value, cut it in half and
890   // check to see if the two halves are equal.  Continue doing this until we
891   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
892   while (ValSizeInBytes > ByteSize) {
893     ValSizeInBytes >>= 1;
894
895     // If the top half equals the bottom half, we're still ok.
896     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
897          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
898       return SDValue();
899   }
900
901   // Properly sign extend the value.
902   int MaskVal = SignExtend32(Value, ByteSize * 8);
903
904   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
905   if (MaskVal == 0) return SDValue();
906
907   // Finally, if this value fits in a 5 bit sext field, return it
908   if (SignExtend32<5>(MaskVal) == MaskVal)
909     return DAG.getTargetConstant(MaskVal, MVT::i32);
910   return SDValue();
911 }
912
913 //===----------------------------------------------------------------------===//
914 //  Addressing Mode Selection
915 //===----------------------------------------------------------------------===//
916
917 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
918 /// or 64-bit immediate, and if the value can be accurately represented as a
919 /// sign extension from a 16-bit value.  If so, this returns true and the
920 /// immediate.
921 static bool isIntS16Immediate(SDNode *N, short &Imm) {
922   if (N->getOpcode() != ISD::Constant)
923     return false;
924
925   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
926   if (N->getValueType(0) == MVT::i32)
927     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
928   else
929     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
930 }
931 static bool isIntS16Immediate(SDValue Op, short &Imm) {
932   return isIntS16Immediate(Op.getNode(), Imm);
933 }
934
935
936 /// SelectAddressRegReg - Given the specified addressed, check to see if it
937 /// can be represented as an indexed [r+r] operation.  Returns false if it
938 /// can be more efficiently represented with [r+imm].
939 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
940                                             SDValue &Index,
941                                             SelectionDAG &DAG) const {
942   short imm = 0;
943   if (N.getOpcode() == ISD::ADD) {
944     if (isIntS16Immediate(N.getOperand(1), imm))
945       return false;    // r+i
946     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
947       return false;    // r+i
948
949     Base = N.getOperand(0);
950     Index = N.getOperand(1);
951     return true;
952   } else if (N.getOpcode() == ISD::OR) {
953     if (isIntS16Immediate(N.getOperand(1), imm))
954       return false;    // r+i can fold it if we can.
955
956     // If this is an or of disjoint bitfields, we can codegen this as an add
957     // (for better address arithmetic) if the LHS and RHS of the OR are provably
958     // disjoint.
959     APInt LHSKnownZero, LHSKnownOne;
960     APInt RHSKnownZero, RHSKnownOne;
961     DAG.ComputeMaskedBits(N.getOperand(0),
962                           LHSKnownZero, LHSKnownOne);
963
964     if (LHSKnownZero.getBoolValue()) {
965       DAG.ComputeMaskedBits(N.getOperand(1),
966                             RHSKnownZero, RHSKnownOne);
967       // If all of the bits are known zero on the LHS or RHS, the add won't
968       // carry.
969       if (~(LHSKnownZero | RHSKnownZero) == 0) {
970         Base = N.getOperand(0);
971         Index = N.getOperand(1);
972         return true;
973       }
974     }
975   }
976
977   return false;
978 }
979
980 /// Returns true if the address N can be represented by a base register plus
981 /// a signed 16-bit displacement [r+imm], and if it is not better
982 /// represented as reg+reg.
983 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
984                                             SDValue &Base,
985                                             SelectionDAG &DAG) const {
986   // FIXME dl should come from parent load or store, not from address
987   DebugLoc dl = N.getDebugLoc();
988   // If this can be more profitably realized as r+r, fail.
989   if (SelectAddressRegReg(N, Disp, Base, DAG))
990     return false;
991
992   if (N.getOpcode() == ISD::ADD) {
993     short imm = 0;
994     if (isIntS16Immediate(N.getOperand(1), imm)) {
995       Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
996       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
997         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
998       } else {
999         Base = N.getOperand(0);
1000       }
1001       return true; // [r+i]
1002     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1003       // Match LOAD (ADD (X, Lo(G))).
1004       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1005              && "Cannot handle constant offsets yet!");
1006       Disp = N.getOperand(1).getOperand(0);  // The global address.
1007       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1008              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1009              Disp.getOpcode() == ISD::TargetConstantPool ||
1010              Disp.getOpcode() == ISD::TargetJumpTable);
1011       Base = N.getOperand(0);
1012       return true;  // [&g+r]
1013     }
1014   } else if (N.getOpcode() == ISD::OR) {
1015     short imm = 0;
1016     if (isIntS16Immediate(N.getOperand(1), imm)) {
1017       // If this is an or of disjoint bitfields, we can codegen this as an add
1018       // (for better address arithmetic) if the LHS and RHS of the OR are
1019       // provably disjoint.
1020       APInt LHSKnownZero, LHSKnownOne;
1021       DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1022
1023       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1024         // If all of the bits are known zero on the LHS or RHS, the add won't
1025         // carry.
1026         Base = N.getOperand(0);
1027         Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1028         return true;
1029       }
1030     }
1031   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1032     // Loading from a constant address.
1033
1034     // If this address fits entirely in a 16-bit sext immediate field, codegen
1035     // this as "d, 0"
1036     short Imm;
1037     if (isIntS16Immediate(CN, Imm)) {
1038       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1039       Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1040                              CN->getValueType(0));
1041       return true;
1042     }
1043
1044     // Handle 32-bit sext immediates with LIS + addr mode.
1045     if (CN->getValueType(0) == MVT::i32 ||
1046         (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1047       int Addr = (int)CN->getZExtValue();
1048
1049       // Otherwise, break this down into an LIS + disp.
1050       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1051
1052       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1053       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1054       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1055       return true;
1056     }
1057   }
1058
1059   Disp = DAG.getTargetConstant(0, getPointerTy());
1060   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1061     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1062   else
1063     Base = N;
1064   return true;      // [r+0]
1065 }
1066
1067 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1068 /// represented as an indexed [r+r] operation.
1069 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1070                                                 SDValue &Index,
1071                                                 SelectionDAG &DAG) const {
1072   // Check to see if we can easily represent this as an [r+r] address.  This
1073   // will fail if it thinks that the address is more profitably represented as
1074   // reg+imm, e.g. where imm = 0.
1075   if (SelectAddressRegReg(N, Base, Index, DAG))
1076     return true;
1077
1078   // If the operand is an addition, always emit this as [r+r], since this is
1079   // better (for code size, and execution, as the memop does the add for free)
1080   // than emitting an explicit add.
1081   if (N.getOpcode() == ISD::ADD) {
1082     Base = N.getOperand(0);
1083     Index = N.getOperand(1);
1084     return true;
1085   }
1086
1087   // Otherwise, do it the hard way, using R0 as the base register.
1088   Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1089                          N.getValueType());
1090   Index = N;
1091   return true;
1092 }
1093
1094 /// SelectAddressRegImmShift - Returns true if the address N can be
1095 /// represented by a base register plus a signed 14-bit displacement
1096 /// [r+imm*4].  Suitable for use by STD and friends.
1097 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1098                                                  SDValue &Base,
1099                                                  SelectionDAG &DAG) const {
1100   // FIXME dl should come from the parent load or store, not the address
1101   DebugLoc dl = N.getDebugLoc();
1102   // If this can be more profitably realized as r+r, fail.
1103   if (SelectAddressRegReg(N, Disp, Base, DAG))
1104     return false;
1105
1106   if (N.getOpcode() == ISD::ADD) {
1107     short imm = 0;
1108     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1109       Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1110       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1111         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1112       } else {
1113         Base = N.getOperand(0);
1114       }
1115       return true; // [r+i]
1116     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1117       // Match LOAD (ADD (X, Lo(G))).
1118       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1119              && "Cannot handle constant offsets yet!");
1120       Disp = N.getOperand(1).getOperand(0);  // The global address.
1121       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1122              Disp.getOpcode() == ISD::TargetConstantPool ||
1123              Disp.getOpcode() == ISD::TargetJumpTable);
1124       Base = N.getOperand(0);
1125       return true;  // [&g+r]
1126     }
1127   } else if (N.getOpcode() == ISD::OR) {
1128     short imm = 0;
1129     if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1130       // If this is an or of disjoint bitfields, we can codegen this as an add
1131       // (for better address arithmetic) if the LHS and RHS of the OR are
1132       // provably disjoint.
1133       APInt LHSKnownZero, LHSKnownOne;
1134       DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1135       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1136         // If all of the bits are known zero on the LHS or RHS, the add won't
1137         // carry.
1138         Base = N.getOperand(0);
1139         Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1140         return true;
1141       }
1142     }
1143   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1144     // Loading from a constant address.  Verify low two bits are clear.
1145     if ((CN->getZExtValue() & 3) == 0) {
1146       // If this address fits entirely in a 14-bit sext immediate field, codegen
1147       // this as "d, 0"
1148       short Imm;
1149       if (isIntS16Immediate(CN, Imm)) {
1150         Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1151         Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1152                                CN->getValueType(0));
1153         return true;
1154       }
1155
1156       // Fold the low-part of 32-bit absolute addresses into addr mode.
1157       if (CN->getValueType(0) == MVT::i32 ||
1158           (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1159         int Addr = (int)CN->getZExtValue();
1160
1161         // Otherwise, break this down into an LIS + disp.
1162         Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1163         Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1164         unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1165         Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1166         return true;
1167       }
1168     }
1169   }
1170
1171   Disp = DAG.getTargetConstant(0, getPointerTy());
1172   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1173     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1174   else
1175     Base = N;
1176   return true;      // [r+0]
1177 }
1178
1179
1180 /// getPreIndexedAddressParts - returns true by value, base pointer and
1181 /// offset pointer and addressing mode by reference if the node's address
1182 /// can be legally represented as pre-indexed load / store address.
1183 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1184                                                   SDValue &Offset,
1185                                                   ISD::MemIndexedMode &AM,
1186                                                   SelectionDAG &DAG) const {
1187   if (DisablePPCPreinc) return false;
1188
1189   bool isLoad = true;
1190   SDValue Ptr;
1191   EVT VT;
1192   unsigned Alignment;
1193   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1194     Ptr = LD->getBasePtr();
1195     VT = LD->getMemoryVT();
1196     Alignment = LD->getAlignment();
1197   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1198     Ptr = ST->getBasePtr();
1199     VT  = ST->getMemoryVT();
1200     Alignment = ST->getAlignment();
1201     isLoad = false;
1202   } else
1203     return false;
1204
1205   // PowerPC doesn't have preinc load/store instructions for vectors.
1206   if (VT.isVector())
1207     return false;
1208
1209   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1210
1211     // Common code will reject creating a pre-inc form if the base pointer
1212     // is a frame index, or if N is a store and the base pointer is either
1213     // the same as or a predecessor of the value being stored.  Check for
1214     // those situations here, and try with swapped Base/Offset instead.
1215     bool Swap = false;
1216
1217     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1218       Swap = true;
1219     else if (!isLoad) {
1220       SDValue Val = cast<StoreSDNode>(N)->getValue();
1221       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1222         Swap = true;
1223     }
1224
1225     if (Swap)
1226       std::swap(Base, Offset);
1227
1228     AM = ISD::PRE_INC;
1229     return true;
1230   }
1231
1232   // LDU/STU use reg+imm*4, others use reg+imm.
1233   if (VT != MVT::i64) {
1234     // reg + imm
1235     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1236       return false;
1237   } else {
1238     // LDU/STU need an address with at least 4-byte alignment.
1239     if (Alignment < 4)
1240       return false;
1241
1242     // reg + imm * 4.
1243     if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1244       return false;
1245   }
1246
1247   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1248     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1249     // sext i32 to i64 when addr mode is r+i.
1250     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1251         LD->getExtensionType() == ISD::SEXTLOAD &&
1252         isa<ConstantSDNode>(Offset))
1253       return false;
1254   }
1255
1256   AM = ISD::PRE_INC;
1257   return true;
1258 }
1259
1260 //===----------------------------------------------------------------------===//
1261 //  LowerOperation implementation
1262 //===----------------------------------------------------------------------===//
1263
1264 /// GetLabelAccessInfo - Return true if we should reference labels using a
1265 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1266 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1267                                unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1268   HiOpFlags = PPCII::MO_HA16;
1269   LoOpFlags = PPCII::MO_LO16;
1270
1271   // Don't use the pic base if not in PIC relocation model.  Or if we are on a
1272   // non-darwin platform.  We don't support PIC on other platforms yet.
1273   bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1274                TM.getSubtarget<PPCSubtarget>().isDarwin();
1275   if (isPIC) {
1276     HiOpFlags |= PPCII::MO_PIC_FLAG;
1277     LoOpFlags |= PPCII::MO_PIC_FLAG;
1278   }
1279
1280   // If this is a reference to a global value that requires a non-lazy-ptr, make
1281   // sure that instruction lowering adds it.
1282   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1283     HiOpFlags |= PPCII::MO_NLP_FLAG;
1284     LoOpFlags |= PPCII::MO_NLP_FLAG;
1285
1286     if (GV->hasHiddenVisibility()) {
1287       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1288       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1289     }
1290   }
1291
1292   return isPIC;
1293 }
1294
1295 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1296                              SelectionDAG &DAG) {
1297   EVT PtrVT = HiPart.getValueType();
1298   SDValue Zero = DAG.getConstant(0, PtrVT);
1299   DebugLoc DL = HiPart.getDebugLoc();
1300
1301   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1302   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1303
1304   // With PIC, the first instruction is actually "GR+hi(&G)".
1305   if (isPIC)
1306     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1307                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1308
1309   // Generate non-pic code that has direct accesses to the constant pool.
1310   // The address of the global is just (hi(&g)+lo(&g)).
1311   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1312 }
1313
1314 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1315                                              SelectionDAG &DAG) const {
1316   EVT PtrVT = Op.getValueType();
1317   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1318   const Constant *C = CP->getConstVal();
1319
1320   // 64-bit SVR4 ABI code is always position-independent.
1321   // The actual address of the GlobalValue is stored in the TOC.
1322   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1323     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1324     return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1325                        DAG.getRegister(PPC::X2, MVT::i64));
1326   }
1327
1328   unsigned MOHiFlag, MOLoFlag;
1329   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1330   SDValue CPIHi =
1331     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1332   SDValue CPILo =
1333     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1334   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1335 }
1336
1337 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1338   EVT PtrVT = Op.getValueType();
1339   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1340
1341   // 64-bit SVR4 ABI code is always position-independent.
1342   // The actual address of the GlobalValue is stored in the TOC.
1343   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1344     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1345     return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1346                        DAG.getRegister(PPC::X2, MVT::i64));
1347   }
1348
1349   unsigned MOHiFlag, MOLoFlag;
1350   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1351   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1352   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1353   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1354 }
1355
1356 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1357                                              SelectionDAG &DAG) const {
1358   EVT PtrVT = Op.getValueType();
1359
1360   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1361
1362   unsigned MOHiFlag, MOLoFlag;
1363   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1364   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1365   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1366   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1367 }
1368
1369 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1370                                               SelectionDAG &DAG) const {
1371
1372   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1373   DebugLoc dl = GA->getDebugLoc();
1374   const GlobalValue *GV = GA->getGlobal();
1375   EVT PtrVT = getPointerTy();
1376   bool is64bit = PPCSubTarget.isPPC64();
1377
1378   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1379
1380   if (Model == TLSModel::LocalExec) {
1381     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1382                                                PPCII::MO_TPREL16_HA);
1383     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1384                                                PPCII::MO_TPREL16_LO);
1385     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1386                                      is64bit ? MVT::i64 : MVT::i32);
1387     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1388     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1389   }
1390
1391   if (!is64bit)
1392     llvm_unreachable("only local-exec is currently supported for ppc32");
1393
1394   if (Model == TLSModel::InitialExec) {
1395     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1396     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1397     SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1398                                      PtrVT, GOTReg, TGA);
1399     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1400                                    PtrVT, TGA, TPOffsetHi);
1401     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1402   }
1403
1404   if (Model == TLSModel::GeneralDynamic) {
1405     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1406     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1407     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1408                                      GOTReg, TGA);
1409     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1410                                    GOTEntryHi, TGA);
1411
1412     // We need a chain node, and don't have one handy.  The underlying
1413     // call has no side effects, so using the function entry node
1414     // suffices.
1415     SDValue Chain = DAG.getEntryNode();
1416     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1417     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1418     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1419                                   PtrVT, ParmReg, TGA);
1420     // The return value from GET_TLS_ADDR really is in X3 already, but
1421     // some hacks are needed here to tie everything together.  The extra
1422     // copies dissolve during subsequent transforms.
1423     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1424     return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1425   }
1426
1427   if (Model == TLSModel::LocalDynamic) {
1428     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1429     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1430     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1431                                      GOTReg, TGA);
1432     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1433                                    GOTEntryHi, TGA);
1434
1435     // We need a chain node, and don't have one handy.  The underlying
1436     // call has no side effects, so using the function entry node
1437     // suffices.
1438     SDValue Chain = DAG.getEntryNode();
1439     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1440     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1441     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1442                                   PtrVT, ParmReg, TGA);
1443     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1444     // some hacks are needed here to tie everything together.  The extra
1445     // copies dissolve during subsequent transforms.
1446     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1447     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1448                                       Chain, ParmReg, TGA);
1449     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1450   }
1451
1452   llvm_unreachable("Unknown TLS model!");
1453 }
1454
1455 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1456                                               SelectionDAG &DAG) const {
1457   EVT PtrVT = Op.getValueType();
1458   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1459   DebugLoc DL = GSDN->getDebugLoc();
1460   const GlobalValue *GV = GSDN->getGlobal();
1461
1462   // 64-bit SVR4 ABI code is always position-independent.
1463   // The actual address of the GlobalValue is stored in the TOC.
1464   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1465     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1466     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1467                        DAG.getRegister(PPC::X2, MVT::i64));
1468   }
1469
1470   unsigned MOHiFlag, MOLoFlag;
1471   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1472
1473   SDValue GAHi =
1474     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1475   SDValue GALo =
1476     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1477
1478   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1479
1480   // If the global reference is actually to a non-lazy-pointer, we have to do an
1481   // extra load to get the address of the global.
1482   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1483     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1484                       false, false, false, 0);
1485   return Ptr;
1486 }
1487
1488 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1489   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1490   DebugLoc dl = Op.getDebugLoc();
1491
1492   // If we're comparing for equality to zero, expose the fact that this is
1493   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1494   // fold the new nodes.
1495   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1496     if (C->isNullValue() && CC == ISD::SETEQ) {
1497       EVT VT = Op.getOperand(0).getValueType();
1498       SDValue Zext = Op.getOperand(0);
1499       if (VT.bitsLT(MVT::i32)) {
1500         VT = MVT::i32;
1501         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1502       }
1503       unsigned Log2b = Log2_32(VT.getSizeInBits());
1504       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1505       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1506                                 DAG.getConstant(Log2b, MVT::i32));
1507       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1508     }
1509     // Leave comparisons against 0 and -1 alone for now, since they're usually
1510     // optimized.  FIXME: revisit this when we can custom lower all setcc
1511     // optimizations.
1512     if (C->isAllOnesValue() || C->isNullValue())
1513       return SDValue();
1514   }
1515
1516   // If we have an integer seteq/setne, turn it into a compare against zero
1517   // by xor'ing the rhs with the lhs, which is faster than setting a
1518   // condition register, reading it back out, and masking the correct bit.  The
1519   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1520   // the result to other bit-twiddling opportunities.
1521   EVT LHSVT = Op.getOperand(0).getValueType();
1522   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1523     EVT VT = Op.getValueType();
1524     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1525                                 Op.getOperand(1));
1526     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1527   }
1528   return SDValue();
1529 }
1530
1531 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1532                                       const PPCSubtarget &Subtarget) const {
1533   SDNode *Node = Op.getNode();
1534   EVT VT = Node->getValueType(0);
1535   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1536   SDValue InChain = Node->getOperand(0);
1537   SDValue VAListPtr = Node->getOperand(1);
1538   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1539   DebugLoc dl = Node->getDebugLoc();
1540
1541   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1542
1543   // gpr_index
1544   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1545                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1546                                     false, false, 0);
1547   InChain = GprIndex.getValue(1);
1548
1549   if (VT == MVT::i64) {
1550     // Check if GprIndex is even
1551     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1552                                  DAG.getConstant(1, MVT::i32));
1553     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1554                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1555     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1556                                           DAG.getConstant(1, MVT::i32));
1557     // Align GprIndex to be even if it isn't
1558     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1559                            GprIndex);
1560   }
1561
1562   // fpr index is 1 byte after gpr
1563   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1564                                DAG.getConstant(1, MVT::i32));
1565
1566   // fpr
1567   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1568                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1569                                     false, false, 0);
1570   InChain = FprIndex.getValue(1);
1571
1572   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1573                                        DAG.getConstant(8, MVT::i32));
1574
1575   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1576                                         DAG.getConstant(4, MVT::i32));
1577
1578   // areas
1579   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1580                                      MachinePointerInfo(), false, false,
1581                                      false, 0);
1582   InChain = OverflowArea.getValue(1);
1583
1584   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1585                                     MachinePointerInfo(), false, false,
1586                                     false, 0);
1587   InChain = RegSaveArea.getValue(1);
1588
1589   // select overflow_area if index > 8
1590   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1591                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1592
1593   // adjustment constant gpr_index * 4/8
1594   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1595                                     VT.isInteger() ? GprIndex : FprIndex,
1596                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1597                                                     MVT::i32));
1598
1599   // OurReg = RegSaveArea + RegConstant
1600   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1601                                RegConstant);
1602
1603   // Floating types are 32 bytes into RegSaveArea
1604   if (VT.isFloatingPoint())
1605     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1606                          DAG.getConstant(32, MVT::i32));
1607
1608   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1609   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1610                                    VT.isInteger() ? GprIndex : FprIndex,
1611                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1612                                                    MVT::i32));
1613
1614   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1615                               VT.isInteger() ? VAListPtr : FprPtr,
1616                               MachinePointerInfo(SV),
1617                               MVT::i8, false, false, 0);
1618
1619   // determine if we should load from reg_save_area or overflow_area
1620   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1621
1622   // increase overflow_area by 4/8 if gpr/fpr > 8
1623   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1624                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1625                                           MVT::i32));
1626
1627   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1628                              OverflowAreaPlusN);
1629
1630   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1631                               OverflowAreaPtr,
1632                               MachinePointerInfo(),
1633                               MVT::i32, false, false, 0);
1634
1635   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1636                      false, false, false, 0);
1637 }
1638
1639 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1640                                                   SelectionDAG &DAG) const {
1641   return Op.getOperand(0);
1642 }
1643
1644 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1645                                                 SelectionDAG &DAG) const {
1646   SDValue Chain = Op.getOperand(0);
1647   SDValue Trmp = Op.getOperand(1); // trampoline
1648   SDValue FPtr = Op.getOperand(2); // nested function
1649   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1650   DebugLoc dl = Op.getDebugLoc();
1651
1652   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1653   bool isPPC64 = (PtrVT == MVT::i64);
1654   Type *IntPtrTy =
1655     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1656                                                              *DAG.getContext());
1657
1658   TargetLowering::ArgListTy Args;
1659   TargetLowering::ArgListEntry Entry;
1660
1661   Entry.Ty = IntPtrTy;
1662   Entry.Node = Trmp; Args.push_back(Entry);
1663
1664   // TrampSize == (isPPC64 ? 48 : 40);
1665   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1666                                isPPC64 ? MVT::i64 : MVT::i32);
1667   Args.push_back(Entry);
1668
1669   Entry.Node = FPtr; Args.push_back(Entry);
1670   Entry.Node = Nest; Args.push_back(Entry);
1671
1672   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1673   TargetLowering::CallLoweringInfo CLI(Chain,
1674                                        Type::getVoidTy(*DAG.getContext()),
1675                                        false, false, false, false, 0,
1676                                        CallingConv::C,
1677                 /*isTailCall=*/false,
1678                                        /*doesNotRet=*/false,
1679                                        /*isReturnValueUsed=*/true,
1680                 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1681                 Args, DAG, dl);
1682   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1683
1684   return CallResult.second;
1685 }
1686
1687 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1688                                         const PPCSubtarget &Subtarget) const {
1689   MachineFunction &MF = DAG.getMachineFunction();
1690   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1691
1692   DebugLoc dl = Op.getDebugLoc();
1693
1694   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1695     // vastart just stores the address of the VarArgsFrameIndex slot into the
1696     // memory location argument.
1697     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1698     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1699     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1700     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1701                         MachinePointerInfo(SV),
1702                         false, false, 0);
1703   }
1704
1705   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1706   // We suppose the given va_list is already allocated.
1707   //
1708   // typedef struct {
1709   //  char gpr;     /* index into the array of 8 GPRs
1710   //                 * stored in the register save area
1711   //                 * gpr=0 corresponds to r3,
1712   //                 * gpr=1 to r4, etc.
1713   //                 */
1714   //  char fpr;     /* index into the array of 8 FPRs
1715   //                 * stored in the register save area
1716   //                 * fpr=0 corresponds to f1,
1717   //                 * fpr=1 to f2, etc.
1718   //                 */
1719   //  char *overflow_arg_area;
1720   //                /* location on stack that holds
1721   //                 * the next overflow argument
1722   //                 */
1723   //  char *reg_save_area;
1724   //               /* where r3:r10 and f1:f8 (if saved)
1725   //                * are stored
1726   //                */
1727   // } va_list[1];
1728
1729
1730   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1731   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1732
1733
1734   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1735
1736   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1737                                             PtrVT);
1738   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1739                                  PtrVT);
1740
1741   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1742   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1743
1744   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1745   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1746
1747   uint64_t FPROffset = 1;
1748   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1749
1750   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1751
1752   // Store first byte : number of int regs
1753   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1754                                          Op.getOperand(1),
1755                                          MachinePointerInfo(SV),
1756                                          MVT::i8, false, false, 0);
1757   uint64_t nextOffset = FPROffset;
1758   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1759                                   ConstFPROffset);
1760
1761   // Store second byte : number of float regs
1762   SDValue secondStore =
1763     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1764                       MachinePointerInfo(SV, nextOffset), MVT::i8,
1765                       false, false, 0);
1766   nextOffset += StackOffset;
1767   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1768
1769   // Store second word : arguments given on stack
1770   SDValue thirdStore =
1771     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1772                  MachinePointerInfo(SV, nextOffset),
1773                  false, false, 0);
1774   nextOffset += FrameOffset;
1775   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1776
1777   // Store third word : arguments given in registers
1778   return DAG.getStore(thirdStore, dl, FR, nextPtr,
1779                       MachinePointerInfo(SV, nextOffset),
1780                       false, false, 0);
1781
1782 }
1783
1784 #include "PPCGenCallingConv.inc"
1785
1786 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1787                                        CCValAssign::LocInfo &LocInfo,
1788                                        ISD::ArgFlagsTy &ArgFlags,
1789                                        CCState &State) {
1790   return true;
1791 }
1792
1793 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1794                                               MVT &LocVT,
1795                                               CCValAssign::LocInfo &LocInfo,
1796                                               ISD::ArgFlagsTy &ArgFlags,
1797                                               CCState &State) {
1798   static const uint16_t ArgRegs[] = {
1799     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1800     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1801   };
1802   const unsigned NumArgRegs = array_lengthof(ArgRegs);
1803
1804   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1805
1806   // Skip one register if the first unallocated register has an even register
1807   // number and there are still argument registers available which have not been
1808   // allocated yet. RegNum is actually an index into ArgRegs, which means we
1809   // need to skip a register if RegNum is odd.
1810   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1811     State.AllocateReg(ArgRegs[RegNum]);
1812   }
1813
1814   // Always return false here, as this function only makes sure that the first
1815   // unallocated register has an odd register number and does not actually
1816   // allocate a register for the current argument.
1817   return false;
1818 }
1819
1820 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1821                                                 MVT &LocVT,
1822                                                 CCValAssign::LocInfo &LocInfo,
1823                                                 ISD::ArgFlagsTy &ArgFlags,
1824                                                 CCState &State) {
1825   static const uint16_t ArgRegs[] = {
1826     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1827     PPC::F8
1828   };
1829
1830   const unsigned NumArgRegs = array_lengthof(ArgRegs);
1831
1832   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1833
1834   // If there is only one Floating-point register left we need to put both f64
1835   // values of a split ppc_fp128 value on the stack.
1836   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1837     State.AllocateReg(ArgRegs[RegNum]);
1838   }
1839
1840   // Always return false here, as this function only makes sure that the two f64
1841   // values a ppc_fp128 value is split into are both passed in registers or both
1842   // passed on the stack and does not actually allocate a register for the
1843   // current argument.
1844   return false;
1845 }
1846
1847 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1848 /// on Darwin.
1849 static const uint16_t *GetFPR() {
1850   static const uint16_t FPR[] = {
1851     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1852     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1853   };
1854
1855   return FPR;
1856 }
1857
1858 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1859 /// the stack.
1860 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1861                                        unsigned PtrByteSize) {
1862   unsigned ArgSize = ArgVT.getSizeInBits()/8;
1863   if (Flags.isByVal())
1864     ArgSize = Flags.getByValSize();
1865   ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1866
1867   return ArgSize;
1868 }
1869
1870 SDValue
1871 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1872                                         CallingConv::ID CallConv, bool isVarArg,
1873                                         const SmallVectorImpl<ISD::InputArg>
1874                                           &Ins,
1875                                         DebugLoc dl, SelectionDAG &DAG,
1876                                         SmallVectorImpl<SDValue> &InVals)
1877                                           const {
1878   if (PPCSubTarget.isSVR4ABI()) {
1879     if (PPCSubTarget.isPPC64())
1880       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1881                                          dl, DAG, InVals);
1882     else
1883       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1884                                          dl, DAG, InVals);
1885   } else {
1886     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1887                                        dl, DAG, InVals);
1888   }
1889 }
1890
1891 SDValue
1892 PPCTargetLowering::LowerFormalArguments_32SVR4(
1893                                       SDValue Chain,
1894                                       CallingConv::ID CallConv, bool isVarArg,
1895                                       const SmallVectorImpl<ISD::InputArg>
1896                                         &Ins,
1897                                       DebugLoc dl, SelectionDAG &DAG,
1898                                       SmallVectorImpl<SDValue> &InVals) const {
1899
1900   // 32-bit SVR4 ABI Stack Frame Layout:
1901   //              +-----------------------------------+
1902   //        +-->  |            Back chain             |
1903   //        |     +-----------------------------------+
1904   //        |     | Floating-point register save area |
1905   //        |     +-----------------------------------+
1906   //        |     |    General register save area     |
1907   //        |     +-----------------------------------+
1908   //        |     |          CR save word             |
1909   //        |     +-----------------------------------+
1910   //        |     |         VRSAVE save word          |
1911   //        |     +-----------------------------------+
1912   //        |     |         Alignment padding         |
1913   //        |     +-----------------------------------+
1914   //        |     |     Vector register save area     |
1915   //        |     +-----------------------------------+
1916   //        |     |       Local variable space        |
1917   //        |     +-----------------------------------+
1918   //        |     |        Parameter list area        |
1919   //        |     +-----------------------------------+
1920   //        |     |           LR save word            |
1921   //        |     +-----------------------------------+
1922   // SP-->  +---  |            Back chain             |
1923   //              +-----------------------------------+
1924   //
1925   // Specifications:
1926   //   System V Application Binary Interface PowerPC Processor Supplement
1927   //   AltiVec Technology Programming Interface Manual
1928
1929   MachineFunction &MF = DAG.getMachineFunction();
1930   MachineFrameInfo *MFI = MF.getFrameInfo();
1931   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1932
1933   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1934   // Potential tail calls could cause overwriting of argument stack slots.
1935   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1936                        (CallConv == CallingConv::Fast));
1937   unsigned PtrByteSize = 4;
1938
1939   // Assign locations to all of the incoming arguments.
1940   SmallVector<CCValAssign, 16> ArgLocs;
1941   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1942                  getTargetMachine(), ArgLocs, *DAG.getContext());
1943
1944   // Reserve space for the linkage area on the stack.
1945   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1946
1947   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
1948
1949   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1950     CCValAssign &VA = ArgLocs[i];
1951
1952     // Arguments stored in registers.
1953     if (VA.isRegLoc()) {
1954       const TargetRegisterClass *RC;
1955       EVT ValVT = VA.getValVT();
1956
1957       switch (ValVT.getSimpleVT().SimpleTy) {
1958         default:
1959           llvm_unreachable("ValVT not supported by formal arguments Lowering");
1960         case MVT::i32:
1961           RC = &PPC::GPRCRegClass;
1962           break;
1963         case MVT::f32:
1964           RC = &PPC::F4RCRegClass;
1965           break;
1966         case MVT::f64:
1967           RC = &PPC::F8RCRegClass;
1968           break;
1969         case MVT::v16i8:
1970         case MVT::v8i16:
1971         case MVT::v4i32:
1972         case MVT::v4f32:
1973           RC = &PPC::VRRCRegClass;
1974           break;
1975       }
1976
1977       // Transform the arguments stored in physical registers into virtual ones.
1978       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1979       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1980
1981       InVals.push_back(ArgValue);
1982     } else {
1983       // Argument stored in memory.
1984       assert(VA.isMemLoc());
1985
1986       unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1987       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1988                                       isImmutable);
1989
1990       // Create load nodes to retrieve arguments from the stack.
1991       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1992       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1993                                    MachinePointerInfo(),
1994                                    false, false, false, 0));
1995     }
1996   }
1997
1998   // Assign locations to all of the incoming aggregate by value arguments.
1999   // Aggregates passed by value are stored in the local variable space of the
2000   // caller's stack frame, right above the parameter list area.
2001   SmallVector<CCValAssign, 16> ByValArgLocs;
2002   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2003                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
2004
2005   // Reserve stack space for the allocations in CCInfo.
2006   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2007
2008   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2009
2010   // Area that is at least reserved in the caller of this function.
2011   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2012
2013   // Set the size that is at least reserved in caller of this function.  Tail
2014   // call optimized function's reserved stack space needs to be aligned so that
2015   // taking the difference between two stack areas will result in an aligned
2016   // stack.
2017   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2018
2019   MinReservedArea =
2020     std::max(MinReservedArea,
2021              PPCFrameLowering::getMinCallFrameSize(false, false));
2022
2023   unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2024     getStackAlignment();
2025   unsigned AlignMask = TargetAlign-1;
2026   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2027
2028   FI->setMinReservedArea(MinReservedArea);
2029
2030   SmallVector<SDValue, 8> MemOps;
2031
2032   // If the function takes variable number of arguments, make a frame index for
2033   // the start of the first vararg value... for expansion of llvm.va_start.
2034   if (isVarArg) {
2035     static const uint16_t GPArgRegs[] = {
2036       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2037       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2038     };
2039     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2040
2041     static const uint16_t FPArgRegs[] = {
2042       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2043       PPC::F8
2044     };
2045     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2046
2047     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2048                                                           NumGPArgRegs));
2049     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2050                                                           NumFPArgRegs));
2051
2052     // Make room for NumGPArgRegs and NumFPArgRegs.
2053     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2054                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2055
2056     FuncInfo->setVarArgsStackOffset(
2057       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2058                              CCInfo.getNextStackOffset(), true));
2059
2060     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2061     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2062
2063     // The fixed integer arguments of a variadic function are stored to the
2064     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2065     // the result of va_next.
2066     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2067       // Get an existing live-in vreg, or add a new one.
2068       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2069       if (!VReg)
2070         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2071
2072       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2073       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2074                                    MachinePointerInfo(), false, false, 0);
2075       MemOps.push_back(Store);
2076       // Increment the address by four for the next argument to store
2077       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2078       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2079     }
2080
2081     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2082     // is set.
2083     // The double arguments are stored to the VarArgsFrameIndex
2084     // on the stack.
2085     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2086       // Get an existing live-in vreg, or add a new one.
2087       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2088       if (!VReg)
2089         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2090
2091       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2092       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2093                                    MachinePointerInfo(), false, false, 0);
2094       MemOps.push_back(Store);
2095       // Increment the address by eight for the next argument to store
2096       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2097                                          PtrVT);
2098       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2099     }
2100   }
2101
2102   if (!MemOps.empty())
2103     Chain = DAG.getNode(ISD::TokenFactor, dl,
2104                         MVT::Other, &MemOps[0], MemOps.size());
2105
2106   return Chain;
2107 }
2108
2109 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2110 // value to MVT::i64 and then truncate to the correct register size.
2111 SDValue
2112 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2113                                      SelectionDAG &DAG, SDValue ArgVal,
2114                                      DebugLoc dl) const {
2115   if (Flags.isSExt())
2116     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2117                          DAG.getValueType(ObjectVT));
2118   else if (Flags.isZExt())
2119     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2120                          DAG.getValueType(ObjectVT));
2121   
2122   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2123 }
2124
2125 // Set the size that is at least reserved in caller of this function.  Tail
2126 // call optimized functions' reserved stack space needs to be aligned so that
2127 // taking the difference between two stack areas will result in an aligned
2128 // stack.
2129 void
2130 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2131                                       unsigned nAltivecParamsAtEnd,
2132                                       unsigned MinReservedArea,
2133                                       bool isPPC64) const {
2134   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2135   // Add the Altivec parameters at the end, if needed.
2136   if (nAltivecParamsAtEnd) {
2137     MinReservedArea = ((MinReservedArea+15)/16)*16;
2138     MinReservedArea += 16*nAltivecParamsAtEnd;
2139   }
2140   MinReservedArea =
2141     std::max(MinReservedArea,
2142              PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2143   unsigned TargetAlign
2144     = DAG.getMachineFunction().getTarget().getFrameLowering()->
2145         getStackAlignment();
2146   unsigned AlignMask = TargetAlign-1;
2147   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2148   FI->setMinReservedArea(MinReservedArea);
2149 }
2150
2151 SDValue
2152 PPCTargetLowering::LowerFormalArguments_64SVR4(
2153                                       SDValue Chain,
2154                                       CallingConv::ID CallConv, bool isVarArg,
2155                                       const SmallVectorImpl<ISD::InputArg>
2156                                         &Ins,
2157                                       DebugLoc dl, SelectionDAG &DAG,
2158                                       SmallVectorImpl<SDValue> &InVals) const {
2159   // TODO: add description of PPC stack frame format, or at least some docs.
2160   //
2161   MachineFunction &MF = DAG.getMachineFunction();
2162   MachineFrameInfo *MFI = MF.getFrameInfo();
2163   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2164
2165   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2166   // Potential tail calls could cause overwriting of argument stack slots.
2167   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2168                        (CallConv == CallingConv::Fast));
2169   unsigned PtrByteSize = 8;
2170
2171   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2172   // Area that is at least reserved in caller of this function.
2173   unsigned MinReservedArea = ArgOffset;
2174
2175   static const uint16_t GPR[] = {
2176     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2177     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2178   };
2179
2180   static const uint16_t *FPR = GetFPR();
2181
2182   static const uint16_t VR[] = {
2183     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2184     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2185   };
2186
2187   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2188   const unsigned Num_FPR_Regs = 13;
2189   const unsigned Num_VR_Regs  = array_lengthof(VR);
2190
2191   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2192
2193   // Add DAG nodes to load the arguments or copy them out of registers.  On
2194   // entry to a function on PPC, the arguments start after the linkage area,
2195   // although the first ones are often in registers.
2196
2197   SmallVector<SDValue, 8> MemOps;
2198   unsigned nAltivecParamsAtEnd = 0;
2199   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2200   unsigned CurArgIdx = 0;
2201   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2202     SDValue ArgVal;
2203     bool needsLoad = false;
2204     EVT ObjectVT = Ins[ArgNo].VT;
2205     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2206     unsigned ArgSize = ObjSize;
2207     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2208     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2209     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2210
2211     unsigned CurArgOffset = ArgOffset;
2212
2213     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2214     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2215         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2216       if (isVarArg) {
2217         MinReservedArea = ((MinReservedArea+15)/16)*16;
2218         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2219                                                   Flags,
2220                                                   PtrByteSize);
2221       } else
2222         nAltivecParamsAtEnd++;
2223     } else
2224       // Calculate min reserved area.
2225       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2226                                                 Flags,
2227                                                 PtrByteSize);
2228
2229     // FIXME the codegen can be much improved in some cases.
2230     // We do not have to keep everything in memory.
2231     if (Flags.isByVal()) {
2232       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2233       ObjSize = Flags.getByValSize();
2234       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2235       // Empty aggregate parameters do not take up registers.  Examples:
2236       //   struct { } a;
2237       //   union  { } b;
2238       //   int c[0];
2239       // etc.  However, we have to provide a place-holder in InVals, so
2240       // pretend we have an 8-byte item at the current address for that
2241       // purpose.
2242       if (!ObjSize) {
2243         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2244         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2245         InVals.push_back(FIN);
2246         continue;
2247       }
2248       // All aggregates smaller than 8 bytes must be passed right-justified.
2249       if (ObjSize < PtrByteSize)
2250         CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2251       // The value of the object is its address.
2252       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2253       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2254       InVals.push_back(FIN);
2255
2256       if (ObjSize < 8) {
2257         if (GPR_idx != Num_GPR_Regs) {
2258           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2259           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2260           SDValue Store;
2261
2262           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2263             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2264                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2265             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2266                                       MachinePointerInfo(FuncArg, CurArgOffset),
2267                                       ObjType, false, false, 0);
2268           } else {
2269             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2270             // store the whole register as-is to the parameter save area
2271             // slot.  The address of the parameter was already calculated
2272             // above (InVals.push_back(FIN)) to be the right-justified
2273             // offset within the slot.  For this store, we need a new
2274             // frame index that points at the beginning of the slot.
2275             int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2276             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2277             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2278                                  MachinePointerInfo(FuncArg, ArgOffset),
2279                                  false, false, 0);
2280           }
2281
2282           MemOps.push_back(Store);
2283           ++GPR_idx;
2284         }
2285         // Whether we copied from a register or not, advance the offset
2286         // into the parameter save area by a full doubleword.
2287         ArgOffset += PtrByteSize;
2288         continue;
2289       }
2290
2291       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2292         // Store whatever pieces of the object are in registers
2293         // to memory.  ArgOffset will be the address of the beginning
2294         // of the object.
2295         if (GPR_idx != Num_GPR_Regs) {
2296           unsigned VReg;
2297           VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2298           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2299           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2300           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2301           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2302                                        MachinePointerInfo(FuncArg, ArgOffset),
2303                                        false, false, 0);
2304           MemOps.push_back(Store);
2305           ++GPR_idx;
2306           ArgOffset += PtrByteSize;
2307         } else {
2308           ArgOffset += ArgSize - j;
2309           break;
2310         }
2311       }
2312       continue;
2313     }
2314
2315     switch (ObjectVT.getSimpleVT().SimpleTy) {
2316     default: llvm_unreachable("Unhandled argument type!");
2317     case MVT::i32:
2318     case MVT::i64:
2319       if (GPR_idx != Num_GPR_Regs) {
2320         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2321         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2322
2323         if (ObjectVT == MVT::i32)
2324           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2325           // value to MVT::i64 and then truncate to the correct register size.
2326           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2327
2328         ++GPR_idx;
2329       } else {
2330         needsLoad = true;
2331         ArgSize = PtrByteSize;
2332       }
2333       ArgOffset += 8;
2334       break;
2335
2336     case MVT::f32:
2337     case MVT::f64:
2338       // Every 8 bytes of argument space consumes one of the GPRs available for
2339       // argument passing.
2340       if (GPR_idx != Num_GPR_Regs) {
2341         ++GPR_idx;
2342       }
2343       if (FPR_idx != Num_FPR_Regs) {
2344         unsigned VReg;
2345
2346         if (ObjectVT == MVT::f32)
2347           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2348         else
2349           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2350
2351         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2352         ++FPR_idx;
2353       } else {
2354         needsLoad = true;
2355         ArgSize = PtrByteSize;
2356       }
2357
2358       ArgOffset += 8;
2359       break;
2360     case MVT::v4f32:
2361     case MVT::v4i32:
2362     case MVT::v8i16:
2363     case MVT::v16i8:
2364       // Note that vector arguments in registers don't reserve stack space,
2365       // except in varargs functions.
2366       if (VR_idx != Num_VR_Regs) {
2367         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2368         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2369         if (isVarArg) {
2370           while ((ArgOffset % 16) != 0) {
2371             ArgOffset += PtrByteSize;
2372             if (GPR_idx != Num_GPR_Regs)
2373               GPR_idx++;
2374           }
2375           ArgOffset += 16;
2376           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2377         }
2378         ++VR_idx;
2379       } else {
2380         // Vectors are aligned.
2381         ArgOffset = ((ArgOffset+15)/16)*16;
2382         CurArgOffset = ArgOffset;
2383         ArgOffset += 16;
2384         needsLoad = true;
2385       }
2386       break;
2387     }
2388
2389     // We need to load the argument to a virtual register if we determined
2390     // above that we ran out of physical registers of the appropriate type.
2391     if (needsLoad) {
2392       int FI = MFI->CreateFixedObject(ObjSize,
2393                                       CurArgOffset + (ArgSize - ObjSize),
2394                                       isImmutable);
2395       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2396       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2397                            false, false, false, 0);
2398     }
2399
2400     InVals.push_back(ArgVal);
2401   }
2402
2403   // Set the size that is at least reserved in caller of this function.  Tail
2404   // call optimized functions' reserved stack space needs to be aligned so that
2405   // taking the difference between two stack areas will result in an aligned
2406   // stack.
2407   setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2408
2409   // If the function takes variable number of arguments, make a frame index for
2410   // the start of the first vararg value... for expansion of llvm.va_start.
2411   if (isVarArg) {
2412     int Depth = ArgOffset;
2413
2414     FuncInfo->setVarArgsFrameIndex(
2415       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2416     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2417
2418     // If this function is vararg, store any remaining integer argument regs
2419     // to their spots on the stack so that they may be loaded by deferencing the
2420     // result of va_next.
2421     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2422       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2423       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2424       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2425                                    MachinePointerInfo(), false, false, 0);
2426       MemOps.push_back(Store);
2427       // Increment the address by four for the next argument to store
2428       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2429       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2430     }
2431   }
2432
2433   if (!MemOps.empty())
2434     Chain = DAG.getNode(ISD::TokenFactor, dl,
2435                         MVT::Other, &MemOps[0], MemOps.size());
2436
2437   return Chain;
2438 }
2439
2440 SDValue
2441 PPCTargetLowering::LowerFormalArguments_Darwin(
2442                                       SDValue Chain,
2443                                       CallingConv::ID CallConv, bool isVarArg,
2444                                       const SmallVectorImpl<ISD::InputArg>
2445                                         &Ins,
2446                                       DebugLoc dl, SelectionDAG &DAG,
2447                                       SmallVectorImpl<SDValue> &InVals) const {
2448   // TODO: add description of PPC stack frame format, or at least some docs.
2449   //
2450   MachineFunction &MF = DAG.getMachineFunction();
2451   MachineFrameInfo *MFI = MF.getFrameInfo();
2452   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2453
2454   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2455   bool isPPC64 = PtrVT == MVT::i64;
2456   // Potential tail calls could cause overwriting of argument stack slots.
2457   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2458                        (CallConv == CallingConv::Fast));
2459   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2460
2461   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2462   // Area that is at least reserved in caller of this function.
2463   unsigned MinReservedArea = ArgOffset;
2464
2465   static const uint16_t GPR_32[] = {           // 32-bit registers.
2466     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2467     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2468   };
2469   static const uint16_t GPR_64[] = {           // 64-bit registers.
2470     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2471     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2472   };
2473
2474   static const uint16_t *FPR = GetFPR();
2475
2476   static const uint16_t VR[] = {
2477     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2478     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2479   };
2480
2481   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2482   const unsigned Num_FPR_Regs = 13;
2483   const unsigned Num_VR_Regs  = array_lengthof( VR);
2484
2485   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2486
2487   const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2488
2489   // In 32-bit non-varargs functions, the stack space for vectors is after the
2490   // stack space for non-vectors.  We do not use this space unless we have
2491   // too many vectors to fit in registers, something that only occurs in
2492   // constructed examples:), but we have to walk the arglist to figure
2493   // that out...for the pathological case, compute VecArgOffset as the
2494   // start of the vector parameter area.  Computing VecArgOffset is the
2495   // entire point of the following loop.
2496   unsigned VecArgOffset = ArgOffset;
2497   if (!isVarArg && !isPPC64) {
2498     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2499          ++ArgNo) {
2500       EVT ObjectVT = Ins[ArgNo].VT;
2501       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2502
2503       if (Flags.isByVal()) {
2504         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2505         unsigned ObjSize = Flags.getByValSize();
2506         unsigned ArgSize =
2507                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2508         VecArgOffset += ArgSize;
2509         continue;
2510       }
2511
2512       switch(ObjectVT.getSimpleVT().SimpleTy) {
2513       default: llvm_unreachable("Unhandled argument type!");
2514       case MVT::i32:
2515       case MVT::f32:
2516         VecArgOffset += 4;
2517         break;
2518       case MVT::i64:  // PPC64
2519       case MVT::f64:
2520         // FIXME: We are guaranteed to be !isPPC64 at this point.
2521         // Does MVT::i64 apply?
2522         VecArgOffset += 8;
2523         break;
2524       case MVT::v4f32:
2525       case MVT::v4i32:
2526       case MVT::v8i16:
2527       case MVT::v16i8:
2528         // Nothing to do, we're only looking at Nonvector args here.
2529         break;
2530       }
2531     }
2532   }
2533   // We've found where the vector parameter area in memory is.  Skip the
2534   // first 12 parameters; these don't use that memory.
2535   VecArgOffset = ((VecArgOffset+15)/16)*16;
2536   VecArgOffset += 12*16;
2537
2538   // Add DAG nodes to load the arguments or copy them out of registers.  On
2539   // entry to a function on PPC, the arguments start after the linkage area,
2540   // although the first ones are often in registers.
2541
2542   SmallVector<SDValue, 8> MemOps;
2543   unsigned nAltivecParamsAtEnd = 0;
2544   // FIXME: FuncArg and Ins[ArgNo] must reference the same argument.
2545   // When passing anonymous aggregates, this is currently not true.
2546   // See LowerFormalArguments_64SVR4 for a fix.
2547   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2548   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2549     SDValue ArgVal;
2550     bool needsLoad = false;
2551     EVT ObjectVT = Ins[ArgNo].VT;
2552     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2553     unsigned ArgSize = ObjSize;
2554     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2555
2556     unsigned CurArgOffset = ArgOffset;
2557
2558     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2559     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2560         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2561       if (isVarArg || isPPC64) {
2562         MinReservedArea = ((MinReservedArea+15)/16)*16;
2563         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2564                                                   Flags,
2565                                                   PtrByteSize);
2566       } else  nAltivecParamsAtEnd++;
2567     } else
2568       // Calculate min reserved area.
2569       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2570                                                 Flags,
2571                                                 PtrByteSize);
2572
2573     // FIXME the codegen can be much improved in some cases.
2574     // We do not have to keep everything in memory.
2575     if (Flags.isByVal()) {
2576       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2577       ObjSize = Flags.getByValSize();
2578       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2579       // Objects of size 1 and 2 are right justified, everything else is
2580       // left justified.  This means the memory address is adjusted forwards.
2581       if (ObjSize==1 || ObjSize==2) {
2582         CurArgOffset = CurArgOffset + (4 - ObjSize);
2583       }
2584       // The value of the object is its address.
2585       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2586       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2587       InVals.push_back(FIN);
2588       if (ObjSize==1 || ObjSize==2) {
2589         if (GPR_idx != Num_GPR_Regs) {
2590           unsigned VReg;
2591           if (isPPC64)
2592             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2593           else
2594             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2595           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2596           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2597           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2598                                             MachinePointerInfo(FuncArg,
2599                                               CurArgOffset),
2600                                             ObjType, false, false, 0);
2601           MemOps.push_back(Store);
2602           ++GPR_idx;
2603         }
2604
2605         ArgOffset += PtrByteSize;
2606
2607         continue;
2608       }
2609       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2610         // Store whatever pieces of the object are in registers
2611         // to memory.  ArgOffset will be the address of the beginning
2612         // of the object.
2613         if (GPR_idx != Num_GPR_Regs) {
2614           unsigned VReg;
2615           if (isPPC64)
2616             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2617           else
2618             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2619           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2620           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2621           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2622           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2623                                        MachinePointerInfo(FuncArg, ArgOffset),
2624                                        false, false, 0);
2625           MemOps.push_back(Store);
2626           ++GPR_idx;
2627           ArgOffset += PtrByteSize;
2628         } else {
2629           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2630           break;
2631         }
2632       }
2633       continue;
2634     }
2635
2636     switch (ObjectVT.getSimpleVT().SimpleTy) {
2637     default: llvm_unreachable("Unhandled argument type!");
2638     case MVT::i32:
2639       if (!isPPC64) {
2640         if (GPR_idx != Num_GPR_Regs) {
2641           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2642           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2643           ++GPR_idx;
2644         } else {
2645           needsLoad = true;
2646           ArgSize = PtrByteSize;
2647         }
2648         // All int arguments reserve stack space in the Darwin ABI.
2649         ArgOffset += PtrByteSize;
2650         break;
2651       }
2652       // FALLTHROUGH
2653     case MVT::i64:  // PPC64
2654       if (GPR_idx != Num_GPR_Regs) {
2655         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2656         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2657
2658         if (ObjectVT == MVT::i32)
2659           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2660           // value to MVT::i64 and then truncate to the correct register size.
2661           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2662
2663         ++GPR_idx;
2664       } else {
2665         needsLoad = true;
2666         ArgSize = PtrByteSize;
2667       }
2668       // All int arguments reserve stack space in the Darwin ABI.
2669       ArgOffset += 8;
2670       break;
2671
2672     case MVT::f32:
2673     case MVT::f64:
2674       // Every 4 bytes of argument space consumes one of the GPRs available for
2675       // argument passing.
2676       if (GPR_idx != Num_GPR_Regs) {
2677         ++GPR_idx;
2678         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2679           ++GPR_idx;
2680       }
2681       if (FPR_idx != Num_FPR_Regs) {
2682         unsigned VReg;
2683
2684         if (ObjectVT == MVT::f32)
2685           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2686         else
2687           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2688
2689         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2690         ++FPR_idx;
2691       } else {
2692         needsLoad = true;
2693       }
2694
2695       // All FP arguments reserve stack space in the Darwin ABI.
2696       ArgOffset += isPPC64 ? 8 : ObjSize;
2697       break;
2698     case MVT::v4f32:
2699     case MVT::v4i32:
2700     case MVT::v8i16:
2701     case MVT::v16i8:
2702       // Note that vector arguments in registers don't reserve stack space,
2703       // except in varargs functions.
2704       if (VR_idx != Num_VR_Regs) {
2705         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2706         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2707         if (isVarArg) {
2708           while ((ArgOffset % 16) != 0) {
2709             ArgOffset += PtrByteSize;
2710             if (GPR_idx != Num_GPR_Regs)
2711               GPR_idx++;
2712           }
2713           ArgOffset += 16;
2714           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2715         }
2716         ++VR_idx;
2717       } else {
2718         if (!isVarArg && !isPPC64) {
2719           // Vectors go after all the nonvectors.
2720           CurArgOffset = VecArgOffset;
2721           VecArgOffset += 16;
2722         } else {
2723           // Vectors are aligned.
2724           ArgOffset = ((ArgOffset+15)/16)*16;
2725           CurArgOffset = ArgOffset;
2726           ArgOffset += 16;
2727         }
2728         needsLoad = true;
2729       }
2730       break;
2731     }
2732
2733     // We need to load the argument to a virtual register if we determined above
2734     // that we ran out of physical registers of the appropriate type.
2735     if (needsLoad) {
2736       int FI = MFI->CreateFixedObject(ObjSize,
2737                                       CurArgOffset + (ArgSize - ObjSize),
2738                                       isImmutable);
2739       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2740       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2741                            false, false, false, 0);
2742     }
2743
2744     InVals.push_back(ArgVal);
2745   }
2746
2747   // Set the size that is at least reserved in caller of this function.  Tail
2748   // call optimized functions' reserved stack space needs to be aligned so that
2749   // taking the difference between two stack areas will result in an aligned
2750   // stack.
2751   setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2752
2753   // If the function takes variable number of arguments, make a frame index for
2754   // the start of the first vararg value... for expansion of llvm.va_start.
2755   if (isVarArg) {
2756     int Depth = ArgOffset;
2757
2758     FuncInfo->setVarArgsFrameIndex(
2759       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2760                              Depth, true));
2761     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2762
2763     // If this function is vararg, store any remaining integer argument regs
2764     // to their spots on the stack so that they may be loaded by deferencing the
2765     // result of va_next.
2766     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2767       unsigned VReg;
2768
2769       if (isPPC64)
2770         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2771       else
2772         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2773
2774       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2775       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2776                                    MachinePointerInfo(), false, false, 0);
2777       MemOps.push_back(Store);
2778       // Increment the address by four for the next argument to store
2779       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2780       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2781     }
2782   }
2783
2784   if (!MemOps.empty())
2785     Chain = DAG.getNode(ISD::TokenFactor, dl,
2786                         MVT::Other, &MemOps[0], MemOps.size());
2787
2788   return Chain;
2789 }
2790
2791 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2792 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2793 static unsigned
2794 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2795                                      bool isPPC64,
2796                                      bool isVarArg,
2797                                      unsigned CC,
2798                                      const SmallVectorImpl<ISD::OutputArg>
2799                                        &Outs,
2800                                      const SmallVectorImpl<SDValue> &OutVals,
2801                                      unsigned &nAltivecParamsAtEnd) {
2802   // Count how many bytes are to be pushed on the stack, including the linkage
2803   // area, and parameter passing area.  We start with 24/48 bytes, which is
2804   // prereserved space for [SP][CR][LR][3 x unused].
2805   unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2806   unsigned NumOps = Outs.size();
2807   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2808
2809   // Add up all the space actually used.
2810   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2811   // they all go in registers, but we must reserve stack space for them for
2812   // possible use by the caller.  In varargs or 64-bit calls, parameters are
2813   // assigned stack space in order, with padding so Altivec parameters are
2814   // 16-byte aligned.
2815   nAltivecParamsAtEnd = 0;
2816   for (unsigned i = 0; i != NumOps; ++i) {
2817     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2818     EVT ArgVT = Outs[i].VT;
2819     // Varargs Altivec parameters are padded to a 16 byte boundary.
2820     if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2821         ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2822       if (!isVarArg && !isPPC64) {
2823         // Non-varargs Altivec parameters go after all the non-Altivec
2824         // parameters; handle those later so we know how much padding we need.
2825         nAltivecParamsAtEnd++;
2826         continue;
2827       }
2828       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2829       NumBytes = ((NumBytes+15)/16)*16;
2830     }
2831     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2832   }
2833
2834    // Allow for Altivec parameters at the end, if needed.
2835   if (nAltivecParamsAtEnd) {
2836     NumBytes = ((NumBytes+15)/16)*16;
2837     NumBytes += 16*nAltivecParamsAtEnd;
2838   }
2839
2840   // The prolog code of the callee may store up to 8 GPR argument registers to
2841   // the stack, allowing va_start to index over them in memory if its varargs.
2842   // Because we cannot tell if this is needed on the caller side, we have to
2843   // conservatively assume that it is needed.  As such, make sure we have at
2844   // least enough stack space for the caller to store the 8 GPRs.
2845   NumBytes = std::max(NumBytes,
2846                       PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2847
2848   // Tail call needs the stack to be aligned.
2849   if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2850     unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2851       getFrameLowering()->getStackAlignment();
2852     unsigned AlignMask = TargetAlign-1;
2853     NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2854   }
2855
2856   return NumBytes;
2857 }
2858
2859 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2860 /// adjusted to accommodate the arguments for the tailcall.
2861 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2862                                    unsigned ParamSize) {
2863
2864   if (!isTailCall) return 0;
2865
2866   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2867   unsigned CallerMinReservedArea = FI->getMinReservedArea();
2868   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2869   // Remember only if the new adjustement is bigger.
2870   if (SPDiff < FI->getTailCallSPDelta())
2871     FI->setTailCallSPDelta(SPDiff);
2872
2873   return SPDiff;
2874 }
2875
2876 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2877 /// for tail call optimization. Targets which want to do tail call
2878 /// optimization should implement this function.
2879 bool
2880 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2881                                                      CallingConv::ID CalleeCC,
2882                                                      bool isVarArg,
2883                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2884                                                      SelectionDAG& DAG) const {
2885   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2886     return false;
2887
2888   // Variable argument functions are not supported.
2889   if (isVarArg)
2890     return false;
2891
2892   MachineFunction &MF = DAG.getMachineFunction();
2893   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2894   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2895     // Functions containing by val parameters are not supported.
2896     for (unsigned i = 0; i != Ins.size(); i++) {
2897        ISD::ArgFlagsTy Flags = Ins[i].Flags;
2898        if (Flags.isByVal()) return false;
2899     }
2900
2901     // Non PIC/GOT  tail calls are supported.
2902     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2903       return true;
2904
2905     // At the moment we can only do local tail calls (in same module, hidden
2906     // or protected) if we are generating PIC.
2907     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2908       return G->getGlobal()->hasHiddenVisibility()
2909           || G->getGlobal()->hasProtectedVisibility();
2910   }
2911
2912   return false;
2913 }
2914
2915 /// isCallCompatibleAddress - Return the immediate to use if the specified
2916 /// 32-bit value is representable in the immediate field of a BxA instruction.
2917 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2918   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2919   if (!C) return 0;
2920
2921   int Addr = C->getZExtValue();
2922   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
2923       SignExtend32<26>(Addr) != Addr)
2924     return 0;  // Top 6 bits have to be sext of immediate.
2925
2926   return DAG.getConstant((int)C->getZExtValue() >> 2,
2927                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2928 }
2929
2930 namespace {
2931
2932 struct TailCallArgumentInfo {
2933   SDValue Arg;
2934   SDValue FrameIdxOp;
2935   int       FrameIdx;
2936
2937   TailCallArgumentInfo() : FrameIdx(0) {}
2938 };
2939
2940 }
2941
2942 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2943 static void
2944 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2945                                            SDValue Chain,
2946                    const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2947                    SmallVector<SDValue, 8> &MemOpChains,
2948                    DebugLoc dl) {
2949   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2950     SDValue Arg = TailCallArgs[i].Arg;
2951     SDValue FIN = TailCallArgs[i].FrameIdxOp;
2952     int FI = TailCallArgs[i].FrameIdx;
2953     // Store relative to framepointer.
2954     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2955                                        MachinePointerInfo::getFixedStack(FI),
2956                                        false, false, 0));
2957   }
2958 }
2959
2960 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2961 /// the appropriate stack slot for the tail call optimized function call.
2962 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2963                                                MachineFunction &MF,
2964                                                SDValue Chain,
2965                                                SDValue OldRetAddr,
2966                                                SDValue OldFP,
2967                                                int SPDiff,
2968                                                bool isPPC64,
2969                                                bool isDarwinABI,
2970                                                DebugLoc dl) {
2971   if (SPDiff) {
2972     // Calculate the new stack slot for the return address.
2973     int SlotSize = isPPC64 ? 8 : 4;
2974     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2975                                                                    isDarwinABI);
2976     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2977                                                           NewRetAddrLoc, true);
2978     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2979     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2980     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2981                          MachinePointerInfo::getFixedStack(NewRetAddr),
2982                          false, false, 0);
2983
2984     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2985     // slot as the FP is never overwritten.
2986     if (isDarwinABI) {
2987       int NewFPLoc =
2988         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2989       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2990                                                           true);
2991       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2992       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2993                            MachinePointerInfo::getFixedStack(NewFPIdx),
2994                            false, false, 0);
2995     }
2996   }
2997   return Chain;
2998 }
2999
3000 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3001 /// the position of the argument.
3002 static void
3003 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3004                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3005                       SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
3006   int Offset = ArgOffset + SPDiff;
3007   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3008   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3009   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3010   SDValue FIN = DAG.getFrameIndex(FI, VT);
3011   TailCallArgumentInfo Info;
3012   Info.Arg = Arg;
3013   Info.FrameIdxOp = FIN;
3014   Info.FrameIdx = FI;
3015   TailCallArguments.push_back(Info);
3016 }
3017
3018 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3019 /// stack slot. Returns the chain as result and the loaded frame pointers in
3020 /// LROpOut/FPOpout. Used when tail calling.
3021 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3022                                                         int SPDiff,
3023                                                         SDValue Chain,
3024                                                         SDValue &LROpOut,
3025                                                         SDValue &FPOpOut,
3026                                                         bool isDarwinABI,
3027                                                         DebugLoc dl) const {
3028   if (SPDiff) {
3029     // Load the LR and FP stack slot for later adjusting.
3030     EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3031     LROpOut = getReturnAddrFrameIndex(DAG);
3032     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3033                           false, false, false, 0);
3034     Chain = SDValue(LROpOut.getNode(), 1);
3035
3036     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3037     // slot as the FP is never overwritten.
3038     if (isDarwinABI) {
3039       FPOpOut = getFramePointerFrameIndex(DAG);
3040       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3041                             false, false, false, 0);
3042       Chain = SDValue(FPOpOut.getNode(), 1);
3043     }
3044   }
3045   return Chain;
3046 }
3047
3048 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3049 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3050 /// specified by the specific parameter attribute. The copy will be passed as
3051 /// a byval function parameter.
3052 /// Sometimes what we are copying is the end of a larger object, the part that
3053 /// does not fit in registers.
3054 static SDValue
3055 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3056                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3057                           DebugLoc dl) {
3058   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3059   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3060                        false, false, MachinePointerInfo(0),
3061                        MachinePointerInfo(0));
3062 }
3063
3064 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3065 /// tail calls.
3066 static void
3067 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3068                  SDValue Arg, SDValue PtrOff, int SPDiff,
3069                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3070                  bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3071                  SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3072                  DebugLoc dl) {
3073   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3074   if (!isTailCall) {
3075     if (isVector) {
3076       SDValue StackPtr;
3077       if (isPPC64)
3078         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3079       else
3080         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3081       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3082                            DAG.getConstant(ArgOffset, PtrVT));
3083     }
3084     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3085                                        MachinePointerInfo(), false, false, 0));
3086   // Calculate and remember argument location.
3087   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3088                                   TailCallArguments);
3089 }
3090
3091 static
3092 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3093                      DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3094                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3095                      SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3096   MachineFunction &MF = DAG.getMachineFunction();
3097
3098   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3099   // might overwrite each other in case of tail call optimization.
3100   SmallVector<SDValue, 8> MemOpChains2;
3101   // Do not flag preceding copytoreg stuff together with the following stuff.
3102   InFlag = SDValue();
3103   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3104                                     MemOpChains2, dl);
3105   if (!MemOpChains2.empty())
3106     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3107                         &MemOpChains2[0], MemOpChains2.size());
3108
3109   // Store the return address to the appropriate stack slot.
3110   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3111                                         isPPC64, isDarwinABI, dl);
3112
3113   // Emit callseq_end just before tailcall node.
3114   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3115                              DAG.getIntPtrConstant(0, true), InFlag);
3116   InFlag = Chain.getValue(1);
3117 }
3118
3119 static
3120 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3121                      SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3122                      SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3123                      SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3124                      const PPCSubtarget &PPCSubTarget) {
3125
3126   bool isPPC64 = PPCSubTarget.isPPC64();
3127   bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3128
3129   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3130   NodeTys.push_back(MVT::Other);   // Returns a chain
3131   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3132
3133   unsigned CallOpc = PPCISD::CALL;
3134
3135   bool needIndirectCall = true;
3136   if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3137     // If this is an absolute destination address, use the munged value.
3138     Callee = SDValue(Dest, 0);
3139     needIndirectCall = false;
3140   }
3141
3142   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3143     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3144     // Use indirect calls for ALL functions calls in JIT mode, since the
3145     // far-call stubs may be outside relocation limits for a BL instruction.
3146     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3147       unsigned OpFlags = 0;
3148       if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3149           (PPCSubTarget.getTargetTriple().isMacOSX() &&
3150            PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3151           (G->getGlobal()->isDeclaration() ||
3152            G->getGlobal()->isWeakForLinker())) {
3153         // PC-relative references to external symbols should go through $stub,
3154         // unless we're building with the leopard linker or later, which
3155         // automatically synthesizes these stubs.
3156         OpFlags = PPCII::MO_DARWIN_STUB;
3157       }
3158
3159       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3160       // every direct call is) turn it into a TargetGlobalAddress /
3161       // TargetExternalSymbol node so that legalize doesn't hack it.
3162       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3163                                           Callee.getValueType(),
3164                                           0, OpFlags);
3165       needIndirectCall = false;
3166     }
3167   }
3168
3169   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3170     unsigned char OpFlags = 0;
3171
3172     if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3173         (PPCSubTarget.getTargetTriple().isMacOSX() &&
3174          PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3175       // PC-relative references to external symbols should go through $stub,
3176       // unless we're building with the leopard linker or later, which
3177       // automatically synthesizes these stubs.
3178       OpFlags = PPCII::MO_DARWIN_STUB;
3179     }
3180
3181     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3182                                          OpFlags);
3183     needIndirectCall = false;
3184   }
3185
3186   if (needIndirectCall) {
3187     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3188     // to do the call, we can't use PPCISD::CALL.
3189     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3190
3191     if (isSVR4ABI && isPPC64) {
3192       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3193       // entry point, but to the function descriptor (the function entry point
3194       // address is part of the function descriptor though).
3195       // The function descriptor is a three doubleword structure with the
3196       // following fields: function entry point, TOC base address and
3197       // environment pointer.
3198       // Thus for a call through a function pointer, the following actions need
3199       // to be performed:
3200       //   1. Save the TOC of the caller in the TOC save area of its stack
3201       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3202       //   2. Load the address of the function entry point from the function
3203       //      descriptor.
3204       //   3. Load the TOC of the callee from the function descriptor into r2.
3205       //   4. Load the environment pointer from the function descriptor into
3206       //      r11.
3207       //   5. Branch to the function entry point address.
3208       //   6. On return of the callee, the TOC of the caller needs to be
3209       //      restored (this is done in FinishCall()).
3210       //
3211       // All those operations are flagged together to ensure that no other
3212       // operations can be scheduled in between. E.g. without flagging the
3213       // operations together, a TOC access in the caller could be scheduled
3214       // between the load of the callee TOC and the branch to the callee, which
3215       // results in the TOC access going through the TOC of the callee instead
3216       // of going through the TOC of the caller, which leads to incorrect code.
3217
3218       // Load the address of the function entry point from the function
3219       // descriptor.
3220       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3221       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3222                                         InFlag.getNode() ? 3 : 2);
3223       Chain = LoadFuncPtr.getValue(1);
3224       InFlag = LoadFuncPtr.getValue(2);
3225
3226       // Load environment pointer into r11.
3227       // Offset of the environment pointer within the function descriptor.
3228       SDValue PtrOff = DAG.getIntPtrConstant(16);
3229
3230       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3231       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3232                                        InFlag);
3233       Chain = LoadEnvPtr.getValue(1);
3234       InFlag = LoadEnvPtr.getValue(2);
3235
3236       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3237                                         InFlag);
3238       Chain = EnvVal.getValue(0);
3239       InFlag = EnvVal.getValue(1);
3240
3241       // Load TOC of the callee into r2. We are using a target-specific load
3242       // with r2 hard coded, because the result of a target-independent load
3243       // would never go directly into r2, since r2 is a reserved register (which
3244       // prevents the register allocator from allocating it), resulting in an
3245       // additional register being allocated and an unnecessary move instruction
3246       // being generated.
3247       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3248       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3249                                        Callee, InFlag);
3250       Chain = LoadTOCPtr.getValue(0);
3251       InFlag = LoadTOCPtr.getValue(1);
3252
3253       MTCTROps[0] = Chain;
3254       MTCTROps[1] = LoadFuncPtr;
3255       MTCTROps[2] = InFlag;
3256     }
3257
3258     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3259                         2 + (InFlag.getNode() != 0));
3260     InFlag = Chain.getValue(1);
3261
3262     NodeTys.clear();
3263     NodeTys.push_back(MVT::Other);
3264     NodeTys.push_back(MVT::Glue);
3265     Ops.push_back(Chain);
3266     CallOpc = PPCISD::BCTRL;
3267     Callee.setNode(0);
3268     // Add use of X11 (holding environment pointer)
3269     if (isSVR4ABI && isPPC64)
3270       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3271     // Add CTR register as callee so a bctr can be emitted later.
3272     if (isTailCall)
3273       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3274   }
3275
3276   // If this is a direct call, pass the chain and the callee.
3277   if (Callee.getNode()) {
3278     Ops.push_back(Chain);
3279     Ops.push_back(Callee);
3280   }
3281   // If this is a tail call add stack pointer delta.
3282   if (isTailCall)
3283     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3284
3285   // Add argument registers to the end of the list so that they are known live
3286   // into the call.
3287   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3288     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3289                                   RegsToPass[i].second.getValueType()));
3290
3291   return CallOpc;
3292 }
3293
3294 static
3295 bool isLocalCall(const SDValue &Callee)
3296 {
3297   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3298     return !G->getGlobal()->isDeclaration() &&
3299            !G->getGlobal()->isWeakForLinker();
3300   return false;
3301 }
3302
3303 SDValue
3304 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3305                                    CallingConv::ID CallConv, bool isVarArg,
3306                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3307                                    DebugLoc dl, SelectionDAG &DAG,
3308                                    SmallVectorImpl<SDValue> &InVals) const {
3309
3310   SmallVector<CCValAssign, 16> RVLocs;
3311   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3312                     getTargetMachine(), RVLocs, *DAG.getContext());
3313   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3314
3315   // Copy all of the result registers out of their specified physreg.
3316   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3317     CCValAssign &VA = RVLocs[i];
3318     assert(VA.isRegLoc() && "Can only return in registers!");
3319
3320     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3321                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3322     Chain = Val.getValue(1);
3323     InFlag = Val.getValue(2);
3324
3325     switch (VA.getLocInfo()) {
3326     default: llvm_unreachable("Unknown loc info!");
3327     case CCValAssign::Full: break;
3328     case CCValAssign::AExt:
3329       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3330       break;
3331     case CCValAssign::ZExt:
3332       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3333                         DAG.getValueType(VA.getValVT()));
3334       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3335       break;
3336     case CCValAssign::SExt:
3337       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3338                         DAG.getValueType(VA.getValVT()));
3339       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3340       break;
3341     }
3342
3343     InVals.push_back(Val);
3344   }
3345
3346   return Chain;
3347 }
3348
3349 SDValue
3350 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3351                               bool isTailCall, bool isVarArg,
3352                               SelectionDAG &DAG,
3353                               SmallVector<std::pair<unsigned, SDValue>, 8>
3354                                 &RegsToPass,
3355                               SDValue InFlag, SDValue Chain,
3356                               SDValue &Callee,
3357                               int SPDiff, unsigned NumBytes,
3358                               const SmallVectorImpl<ISD::InputArg> &Ins,
3359                               SmallVectorImpl<SDValue> &InVals) const {
3360   std::vector<EVT> NodeTys;
3361   SmallVector<SDValue, 8> Ops;
3362   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3363                                  isTailCall, RegsToPass, Ops, NodeTys,
3364                                  PPCSubTarget);
3365
3366   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3367   if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3368     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3369
3370   // When performing tail call optimization the callee pops its arguments off
3371   // the stack. Account for this here so these bytes can be pushed back on in
3372   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3373   int BytesCalleePops =
3374     (CallConv == CallingConv::Fast &&
3375      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3376
3377   // Add a register mask operand representing the call-preserved registers.
3378   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3379   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3380   assert(Mask && "Missing call preserved mask for calling convention");
3381   Ops.push_back(DAG.getRegisterMask(Mask));
3382
3383   if (InFlag.getNode())
3384     Ops.push_back(InFlag);
3385
3386   // Emit tail call.
3387   if (isTailCall) {
3388     assert(((Callee.getOpcode() == ISD::Register &&
3389              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3390             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3391             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3392             isa<ConstantSDNode>(Callee)) &&
3393     "Expecting an global address, external symbol, absolute value or register");
3394
3395     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3396   }
3397
3398   // Add a NOP immediately after the branch instruction when using the 64-bit
3399   // SVR4 ABI. At link time, if caller and callee are in a different module and
3400   // thus have a different TOC, the call will be replaced with a call to a stub
3401   // function which saves the current TOC, loads the TOC of the callee and
3402   // branches to the callee. The NOP will be replaced with a load instruction
3403   // which restores the TOC of the caller from the TOC save slot of the current
3404   // stack frame. If caller and callee belong to the same module (and have the
3405   // same TOC), the NOP will remain unchanged.
3406
3407   bool needsTOCRestore = false;
3408   if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3409     if (CallOpc == PPCISD::BCTRL) {
3410       // This is a call through a function pointer.
3411       // Restore the caller TOC from the save area into R2.
3412       // See PrepareCall() for more information about calls through function
3413       // pointers in the 64-bit SVR4 ABI.
3414       // We are using a target-specific load with r2 hard coded, because the
3415       // result of a target-independent load would never go directly into r2,
3416       // since r2 is a reserved register (which prevents the register allocator
3417       // from allocating it), resulting in an additional register being
3418       // allocated and an unnecessary move instruction being generated.
3419       needsTOCRestore = true;
3420     } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) {
3421       // Otherwise insert NOP for non-local calls.
3422       CallOpc = PPCISD::CALL_NOP;
3423     }
3424   }
3425
3426   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3427   InFlag = Chain.getValue(1);
3428
3429   if (needsTOCRestore) {
3430     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3431     Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3432     InFlag = Chain.getValue(1);
3433   }
3434
3435   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3436                              DAG.getIntPtrConstant(BytesCalleePops, true),
3437                              InFlag);
3438   if (!Ins.empty())
3439     InFlag = Chain.getValue(1);
3440
3441   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3442                          Ins, dl, DAG, InVals);
3443 }
3444
3445 SDValue
3446 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3447                              SmallVectorImpl<SDValue> &InVals) const {
3448   SelectionDAG &DAG                     = CLI.DAG;
3449   DebugLoc &dl                          = CLI.DL;
3450   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3451   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
3452   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
3453   SDValue Chain                         = CLI.Chain;
3454   SDValue Callee                        = CLI.Callee;
3455   bool &isTailCall                      = CLI.IsTailCall;
3456   CallingConv::ID CallConv              = CLI.CallConv;
3457   bool isVarArg                         = CLI.IsVarArg;
3458
3459   if (isTailCall)
3460     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3461                                                    Ins, DAG);
3462
3463   if (PPCSubTarget.isSVR4ABI()) {
3464     if (PPCSubTarget.isPPC64())
3465       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3466                               isTailCall, Outs, OutVals, Ins,
3467                               dl, DAG, InVals);
3468     else
3469       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3470                               isTailCall, Outs, OutVals, Ins,
3471                               dl, DAG, InVals);
3472   }
3473
3474   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3475                           isTailCall, Outs, OutVals, Ins,
3476                           dl, DAG, InVals);
3477 }
3478
3479 SDValue
3480 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3481                                     CallingConv::ID CallConv, bool isVarArg,
3482                                     bool isTailCall,
3483                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3484                                     const SmallVectorImpl<SDValue> &OutVals,
3485                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3486                                     DebugLoc dl, SelectionDAG &DAG,
3487                                     SmallVectorImpl<SDValue> &InVals) const {
3488   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3489   // of the 32-bit SVR4 ABI stack frame layout.
3490
3491   assert((CallConv == CallingConv::C ||
3492           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3493
3494   unsigned PtrByteSize = 4;
3495
3496   MachineFunction &MF = DAG.getMachineFunction();
3497
3498   // Mark this function as potentially containing a function that contains a
3499   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3500   // and restoring the callers stack pointer in this functions epilog. This is
3501   // done because by tail calling the called function might overwrite the value
3502   // in this function's (MF) stack pointer stack slot 0(SP).
3503   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3504       CallConv == CallingConv::Fast)
3505     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3506
3507   // Count how many bytes are to be pushed on the stack, including the linkage
3508   // area, parameter list area and the part of the local variable space which
3509   // contains copies of aggregates which are passed by value.
3510
3511   // Assign locations to all of the outgoing arguments.
3512   SmallVector<CCValAssign, 16> ArgLocs;
3513   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3514                  getTargetMachine(), ArgLocs, *DAG.getContext());
3515
3516   // Reserve space for the linkage area on the stack.
3517   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3518
3519   if (isVarArg) {
3520     // Handle fixed and variable vector arguments differently.
3521     // Fixed vector arguments go into registers as long as registers are
3522     // available. Variable vector arguments always go into memory.
3523     unsigned NumArgs = Outs.size();
3524
3525     for (unsigned i = 0; i != NumArgs; ++i) {
3526       MVT ArgVT = Outs[i].VT;
3527       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3528       bool Result;
3529
3530       if (Outs[i].IsFixed) {
3531         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3532                                CCInfo);
3533       } else {
3534         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3535                                       ArgFlags, CCInfo);
3536       }
3537
3538       if (Result) {
3539 #ifndef NDEBUG
3540         errs() << "Call operand #" << i << " has unhandled type "
3541              << EVT(ArgVT).getEVTString() << "\n";
3542 #endif
3543         llvm_unreachable(0);
3544       }
3545     }
3546   } else {
3547     // All arguments are treated the same.
3548     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3549   }
3550
3551   // Assign locations to all of the outgoing aggregate by value arguments.
3552   SmallVector<CCValAssign, 16> ByValArgLocs;
3553   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3554                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
3555
3556   // Reserve stack space for the allocations in CCInfo.
3557   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3558
3559   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3560
3561   // Size of the linkage area, parameter list area and the part of the local
3562   // space variable where copies of aggregates which are passed by value are
3563   // stored.
3564   unsigned NumBytes = CCByValInfo.getNextStackOffset();
3565
3566   // Calculate by how many bytes the stack has to be adjusted in case of tail
3567   // call optimization.
3568   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3569
3570   // Adjust the stack pointer for the new arguments...
3571   // These operations are automatically eliminated by the prolog/epilog pass
3572   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3573   SDValue CallSeqStart = Chain;
3574
3575   // Load the return address and frame pointer so it can be moved somewhere else
3576   // later.
3577   SDValue LROp, FPOp;
3578   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3579                                        dl);
3580
3581   // Set up a copy of the stack pointer for use loading and storing any
3582   // arguments that may not fit in the registers available for argument
3583   // passing.
3584   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3585
3586   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3587   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3588   SmallVector<SDValue, 8> MemOpChains;
3589
3590   bool seenFloatArg = false;
3591   // Walk the register/memloc assignments, inserting copies/loads.
3592   for (unsigned i = 0, j = 0, e = ArgLocs.size();
3593        i != e;
3594        ++i) {
3595     CCValAssign &VA = ArgLocs[i];
3596     SDValue Arg = OutVals[i];
3597     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3598
3599     if (Flags.isByVal()) {
3600       // Argument is an aggregate which is passed by value, thus we need to
3601       // create a copy of it in the local variable space of the current stack
3602       // frame (which is the stack frame of the caller) and pass the address of
3603       // this copy to the callee.
3604       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3605       CCValAssign &ByValVA = ByValArgLocs[j++];
3606       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3607
3608       // Memory reserved in the local variable space of the callers stack frame.
3609       unsigned LocMemOffset = ByValVA.getLocMemOffset();
3610
3611       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3612       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3613
3614       // Create a copy of the argument in the local area of the current
3615       // stack frame.
3616       SDValue MemcpyCall =
3617         CreateCopyOfByValArgument(Arg, PtrOff,
3618                                   CallSeqStart.getNode()->getOperand(0),
3619                                   Flags, DAG, dl);
3620
3621       // This must go outside the CALLSEQ_START..END.
3622       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3623                            CallSeqStart.getNode()->getOperand(1));
3624       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3625                              NewCallSeqStart.getNode());
3626       Chain = CallSeqStart = NewCallSeqStart;
3627
3628       // Pass the address of the aggregate copy on the stack either in a
3629       // physical register or in the parameter list area of the current stack
3630       // frame to the callee.
3631       Arg = PtrOff;
3632     }
3633
3634     if (VA.isRegLoc()) {
3635       seenFloatArg |= VA.getLocVT().isFloatingPoint();
3636       // Put argument in a physical register.
3637       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3638     } else {
3639       // Put argument in the parameter list area of the current stack frame.
3640       assert(VA.isMemLoc());
3641       unsigned LocMemOffset = VA.getLocMemOffset();
3642
3643       if (!isTailCall) {
3644         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3645         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3646
3647         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3648                                            MachinePointerInfo(),
3649                                            false, false, 0));
3650       } else {
3651         // Calculate and remember argument location.
3652         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3653                                  TailCallArguments);
3654       }
3655     }
3656   }
3657
3658   if (!MemOpChains.empty())
3659     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3660                         &MemOpChains[0], MemOpChains.size());
3661
3662   // Build a sequence of copy-to-reg nodes chained together with token chain
3663   // and flag operands which copy the outgoing args into the appropriate regs.
3664   SDValue InFlag;
3665   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3666     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3667                              RegsToPass[i].second, InFlag);
3668     InFlag = Chain.getValue(1);
3669   }
3670
3671   // Set CR bit 6 to true if this is a vararg call with floating args passed in
3672   // registers.
3673   if (isVarArg) {
3674     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3675     SDValue Ops[] = { Chain, InFlag };
3676
3677     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3678                         dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3679
3680     InFlag = Chain.getValue(1);
3681   }
3682
3683   if (isTailCall)
3684     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3685                     false, TailCallArguments);
3686
3687   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3688                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3689                     Ins, InVals);
3690 }
3691
3692 // Copy an argument into memory, being careful to do this outside the
3693 // call sequence for the call to which the argument belongs.
3694 SDValue
3695 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3696                                               SDValue CallSeqStart,
3697                                               ISD::ArgFlagsTy Flags,
3698                                               SelectionDAG &DAG,
3699                                               DebugLoc dl) const {
3700   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3701                         CallSeqStart.getNode()->getOperand(0),
3702                         Flags, DAG, dl);
3703   // The MEMCPY must go outside the CALLSEQ_START..END.
3704   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3705                              CallSeqStart.getNode()->getOperand(1));
3706   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3707                          NewCallSeqStart.getNode());
3708   return NewCallSeqStart;
3709 }
3710
3711 SDValue
3712 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3713                                     CallingConv::ID CallConv, bool isVarArg,
3714                                     bool isTailCall,
3715                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3716                                     const SmallVectorImpl<SDValue> &OutVals,
3717                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3718                                     DebugLoc dl, SelectionDAG &DAG,
3719                                     SmallVectorImpl<SDValue> &InVals) const {
3720
3721   unsigned NumOps = Outs.size();
3722
3723   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3724   unsigned PtrByteSize = 8;
3725
3726   MachineFunction &MF = DAG.getMachineFunction();
3727
3728   // Mark this function as potentially containing a function that contains a
3729   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3730   // and restoring the callers stack pointer in this functions epilog. This is
3731   // done because by tail calling the called function might overwrite the value
3732   // in this function's (MF) stack pointer stack slot 0(SP).
3733   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3734       CallConv == CallingConv::Fast)
3735     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3736
3737   unsigned nAltivecParamsAtEnd = 0;
3738
3739   // Count how many bytes are to be pushed on the stack, including the linkage
3740   // area, and parameter passing area.  We start with at least 48 bytes, which
3741   // is reserved space for [SP][CR][LR][3 x unused].
3742   // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3743   // of this call.
3744   unsigned NumBytes =
3745     CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3746                                          Outs, OutVals, nAltivecParamsAtEnd);
3747
3748   // Calculate by how many bytes the stack has to be adjusted in case of tail
3749   // call optimization.
3750   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3751
3752   // To protect arguments on the stack from being clobbered in a tail call,
3753   // force all the loads to happen before doing any other lowering.
3754   if (isTailCall)
3755     Chain = DAG.getStackArgumentTokenFactor(Chain);
3756
3757   // Adjust the stack pointer for the new arguments...
3758   // These operations are automatically eliminated by the prolog/epilog pass
3759   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3760   SDValue CallSeqStart = Chain;
3761
3762   // Load the return address and frame pointer so it can be move somewhere else
3763   // later.
3764   SDValue LROp, FPOp;
3765   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3766                                        dl);
3767
3768   // Set up a copy of the stack pointer for use loading and storing any
3769   // arguments that may not fit in the registers available for argument
3770   // passing.
3771   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3772
3773   // Figure out which arguments are going to go in registers, and which in
3774   // memory.  Also, if this is a vararg function, floating point operations
3775   // must be stored to our stack, and loaded into integer regs as well, if
3776   // any integer regs are available for argument passing.
3777   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3778   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3779
3780   static const uint16_t GPR[] = {
3781     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3782     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3783   };
3784   static const uint16_t *FPR = GetFPR();
3785
3786   static const uint16_t VR[] = {
3787     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3788     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3789   };
3790   const unsigned NumGPRs = array_lengthof(GPR);
3791   const unsigned NumFPRs = 13;
3792   const unsigned NumVRs  = array_lengthof(VR);
3793
3794   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3795   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3796
3797   SmallVector<SDValue, 8> MemOpChains;
3798   for (unsigned i = 0; i != NumOps; ++i) {
3799     SDValue Arg = OutVals[i];
3800     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3801
3802     // PtrOff will be used to store the current argument to the stack if a
3803     // register cannot be found for it.
3804     SDValue PtrOff;
3805
3806     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3807
3808     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3809
3810     // Promote integers to 64-bit values.
3811     if (Arg.getValueType() == MVT::i32) {
3812       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3813       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3814       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3815     }
3816
3817     // FIXME memcpy is used way more than necessary.  Correctness first.
3818     // Note: "by value" is code for passing a structure by value, not
3819     // basic types.
3820     if (Flags.isByVal()) {
3821       // Note: Size includes alignment padding, so
3822       //   struct x { short a; char b; }
3823       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
3824       // These are the proper values we need for right-justifying the
3825       // aggregate in a parameter register.
3826       unsigned Size = Flags.getByValSize();
3827
3828       // An empty aggregate parameter takes up no storage and no
3829       // registers.
3830       if (Size == 0)
3831         continue;
3832
3833       // All aggregates smaller than 8 bytes must be passed right-justified.
3834       if (Size==1 || Size==2 || Size==4) {
3835         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3836         if (GPR_idx != NumGPRs) {
3837           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3838                                         MachinePointerInfo(), VT,
3839                                         false, false, 0);
3840           MemOpChains.push_back(Load.getValue(1));
3841           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3842
3843           ArgOffset += PtrByteSize;
3844           continue;
3845         }
3846       }
3847
3848       if (GPR_idx == NumGPRs && Size < 8) {
3849         SDValue Const = DAG.getConstant(PtrByteSize - Size,
3850                                         PtrOff.getValueType());
3851         SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3852         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3853                                                           CallSeqStart,
3854                                                           Flags, DAG, dl);
3855         ArgOffset += PtrByteSize;
3856         continue;
3857       }
3858       // Copy entire object into memory.  There are cases where gcc-generated
3859       // code assumes it is there, even if it could be put entirely into
3860       // registers.  (This is not what the doc says.)
3861
3862       // FIXME: The above statement is likely due to a misunderstanding of the
3863       // documents.  All arguments must be copied into the parameter area BY
3864       // THE CALLEE in the event that the callee takes the address of any
3865       // formal argument.  That has not yet been implemented.  However, it is
3866       // reasonable to use the stack area as a staging area for the register
3867       // load.
3868
3869       // Skip this for small aggregates, as we will use the same slot for a
3870       // right-justified copy, below.
3871       if (Size >= 8)
3872         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3873                                                           CallSeqStart,
3874                                                           Flags, DAG, dl);
3875
3876       // When a register is available, pass a small aggregate right-justified.
3877       if (Size < 8 && GPR_idx != NumGPRs) {
3878         // The easiest way to get this right-justified in a register
3879         // is to copy the structure into the rightmost portion of a
3880         // local variable slot, then load the whole slot into the
3881         // register.
3882         // FIXME: The memcpy seems to produce pretty awful code for
3883         // small aggregates, particularly for packed ones.
3884         // FIXME: It would be preferable to use the slot in the 
3885         // parameter save area instead of a new local variable.
3886         SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3887         SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3888         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3889                                                           CallSeqStart,
3890                                                           Flags, DAG, dl);
3891
3892         // Load the slot into the register.
3893         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3894                                    MachinePointerInfo(),
3895                                    false, false, false, 0);
3896         MemOpChains.push_back(Load.getValue(1));
3897         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3898
3899         // Done with this argument.
3900         ArgOffset += PtrByteSize;
3901         continue;
3902       }
3903
3904       // For aggregates larger than PtrByteSize, copy the pieces of the
3905       // object that fit into registers from the parameter save area.
3906       for (unsigned j=0; j<Size; j+=PtrByteSize) {
3907         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3908         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3909         if (GPR_idx != NumGPRs) {
3910           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3911                                      MachinePointerInfo(),
3912                                      false, false, false, 0);
3913           MemOpChains.push_back(Load.getValue(1));
3914           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3915           ArgOffset += PtrByteSize;
3916         } else {
3917           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3918           break;
3919         }
3920       }
3921       continue;
3922     }
3923
3924     switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3925     default: llvm_unreachable("Unexpected ValueType for argument!");
3926     case MVT::i32:
3927     case MVT::i64:
3928       if (GPR_idx != NumGPRs) {
3929         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3930       } else {
3931         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3932                          true, isTailCall, false, MemOpChains,
3933                          TailCallArguments, dl);
3934       }
3935       ArgOffset += PtrByteSize;
3936       break;
3937     case MVT::f32:
3938     case MVT::f64:
3939       if (FPR_idx != NumFPRs) {
3940         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3941
3942         if (isVarArg) {
3943           // A single float or an aggregate containing only a single float
3944           // must be passed right-justified in the stack doubleword, and
3945           // in the GPR, if one is available.
3946           SDValue StoreOff;
3947           if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3948             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3949             StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3950           } else
3951             StoreOff = PtrOff;
3952
3953           SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3954                                        MachinePointerInfo(), false, false, 0);
3955           MemOpChains.push_back(Store);
3956
3957           // Float varargs are always shadowed in available integer registers
3958           if (GPR_idx != NumGPRs) {
3959             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3960                                        MachinePointerInfo(), false, false,
3961                                        false, 0);
3962             MemOpChains.push_back(Load.getValue(1));
3963             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3964           }
3965         } else if (GPR_idx != NumGPRs)
3966           // If we have any FPRs remaining, we may also have GPRs remaining.
3967           ++GPR_idx;
3968       } else {
3969         // Single-precision floating-point values are mapped to the
3970         // second (rightmost) word of the stack doubleword.
3971         if (Arg.getValueType() == MVT::f32) {
3972           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3973           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3974         }
3975
3976         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3977                          true, isTailCall, false, MemOpChains,
3978                          TailCallArguments, dl);
3979       }
3980       ArgOffset += 8;
3981       break;
3982     case MVT::v4f32:
3983     case MVT::v4i32:
3984     case MVT::v8i16:
3985     case MVT::v16i8:
3986       if (isVarArg) {
3987         // These go aligned on the stack, or in the corresponding R registers
3988         // when within range.  The Darwin PPC ABI doc claims they also go in
3989         // V registers; in fact gcc does this only for arguments that are
3990         // prototyped, not for those that match the ...  We do it for all
3991         // arguments, seems to work.
3992         while (ArgOffset % 16 !=0) {
3993           ArgOffset += PtrByteSize;
3994           if (GPR_idx != NumGPRs)
3995             GPR_idx++;
3996         }
3997         // We could elide this store in the case where the object fits
3998         // entirely in R registers.  Maybe later.
3999         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4000                             DAG.getConstant(ArgOffset, PtrVT));
4001         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4002                                      MachinePointerInfo(), false, false, 0);
4003         MemOpChains.push_back(Store);
4004         if (VR_idx != NumVRs) {
4005           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4006                                      MachinePointerInfo(),
4007                                      false, false, false, 0);
4008           MemOpChains.push_back(Load.getValue(1));
4009           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4010         }
4011         ArgOffset += 16;
4012         for (unsigned i=0; i<16; i+=PtrByteSize) {
4013           if (GPR_idx == NumGPRs)
4014             break;
4015           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4016                                   DAG.getConstant(i, PtrVT));
4017           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4018                                      false, false, false, 0);
4019           MemOpChains.push_back(Load.getValue(1));
4020           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4021         }
4022         break;
4023       }
4024
4025       // Non-varargs Altivec params generally go in registers, but have
4026       // stack space allocated at the end.
4027       if (VR_idx != NumVRs) {
4028         // Doesn't have GPR space allocated.
4029         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4030       } else {
4031         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4032                          true, isTailCall, true, MemOpChains,
4033                          TailCallArguments, dl);
4034         ArgOffset += 16;
4035       }
4036       break;
4037     }
4038   }
4039
4040   if (!MemOpChains.empty())
4041     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4042                         &MemOpChains[0], MemOpChains.size());
4043
4044   // Check if this is an indirect call (MTCTR/BCTRL).
4045   // See PrepareCall() for more information about calls through function
4046   // pointers in the 64-bit SVR4 ABI.
4047   if (!isTailCall &&
4048       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4049       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4050       !isBLACompatibleAddress(Callee, DAG)) {
4051     // Load r2 into a virtual register and store it to the TOC save area.
4052     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4053     // TOC save area offset.
4054     SDValue PtrOff = DAG.getIntPtrConstant(40);
4055     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4056     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4057                          false, false, 0);
4058     // R12 must contain the address of an indirect callee.  This does not
4059     // mean the MTCTR instruction must use R12; it's easier to model this
4060     // as an extra parameter, so do that.
4061     RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4062   }
4063
4064   // Build a sequence of copy-to-reg nodes chained together with token chain
4065   // and flag operands which copy the outgoing args into the appropriate regs.
4066   SDValue InFlag;
4067   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4068     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4069                              RegsToPass[i].second, InFlag);
4070     InFlag = Chain.getValue(1);
4071   }
4072
4073   if (isTailCall)
4074     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4075                     FPOp, true, TailCallArguments);
4076
4077   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4078                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4079                     Ins, InVals);
4080 }
4081
4082 SDValue
4083 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4084                                     CallingConv::ID CallConv, bool isVarArg,
4085                                     bool isTailCall,
4086                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4087                                     const SmallVectorImpl<SDValue> &OutVals,
4088                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4089                                     DebugLoc dl, SelectionDAG &DAG,
4090                                     SmallVectorImpl<SDValue> &InVals) const {
4091
4092   unsigned NumOps = Outs.size();
4093
4094   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4095   bool isPPC64 = PtrVT == MVT::i64;
4096   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4097
4098   MachineFunction &MF = DAG.getMachineFunction();
4099
4100   // Mark this function as potentially containing a function that contains a
4101   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4102   // and restoring the callers stack pointer in this functions epilog. This is
4103   // done because by tail calling the called function might overwrite the value
4104   // in this function's (MF) stack pointer stack slot 0(SP).
4105   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4106       CallConv == CallingConv::Fast)
4107     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4108
4109   unsigned nAltivecParamsAtEnd = 0;
4110
4111   // Count how many bytes are to be pushed on the stack, including the linkage
4112   // area, and parameter passing area.  We start with 24/48 bytes, which is
4113   // prereserved space for [SP][CR][LR][3 x unused].
4114   unsigned NumBytes =
4115     CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4116                                          Outs, OutVals,
4117                                          nAltivecParamsAtEnd);
4118
4119   // Calculate by how many bytes the stack has to be adjusted in case of tail
4120   // call optimization.
4121   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4122
4123   // To protect arguments on the stack from being clobbered in a tail call,
4124   // force all the loads to happen before doing any other lowering.
4125   if (isTailCall)
4126     Chain = DAG.getStackArgumentTokenFactor(Chain);
4127
4128   // Adjust the stack pointer for the new arguments...
4129   // These operations are automatically eliminated by the prolog/epilog pass
4130   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4131   SDValue CallSeqStart = Chain;
4132
4133   // Load the return address and frame pointer so it can be move somewhere else
4134   // later.
4135   SDValue LROp, FPOp;
4136   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4137                                        dl);
4138
4139   // Set up a copy of the stack pointer for use loading and storing any
4140   // arguments that may not fit in the registers available for argument
4141   // passing.
4142   SDValue StackPtr;
4143   if (isPPC64)
4144     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4145   else
4146     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4147
4148   // Figure out which arguments are going to go in registers, and which in
4149   // memory.  Also, if this is a vararg function, floating point operations
4150   // must be stored to our stack, and loaded into integer regs as well, if
4151   // any integer regs are available for argument passing.
4152   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4153   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4154
4155   static const uint16_t GPR_32[] = {           // 32-bit registers.
4156     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4157     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4158   };
4159   static const uint16_t GPR_64[] = {           // 64-bit registers.
4160     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4161     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4162   };
4163   static const uint16_t *FPR = GetFPR();
4164
4165   static const uint16_t VR[] = {
4166     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4167     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4168   };
4169   const unsigned NumGPRs = array_lengthof(GPR_32);
4170   const unsigned NumFPRs = 13;
4171   const unsigned NumVRs  = array_lengthof(VR);
4172
4173   const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4174
4175   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4176   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4177
4178   SmallVector<SDValue, 8> MemOpChains;
4179   for (unsigned i = 0; i != NumOps; ++i) {
4180     SDValue Arg = OutVals[i];
4181     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4182
4183     // PtrOff will be used to store the current argument to the stack if a
4184     // register cannot be found for it.
4185     SDValue PtrOff;
4186
4187     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4188
4189     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4190
4191     // On PPC64, promote integers to 64-bit values.
4192     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4193       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4194       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4195       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4196     }
4197
4198     // FIXME memcpy is used way more than necessary.  Correctness first.
4199     // Note: "by value" is code for passing a structure by value, not
4200     // basic types.
4201     if (Flags.isByVal()) {
4202       unsigned Size = Flags.getByValSize();
4203       // Very small objects are passed right-justified.  Everything else is
4204       // passed left-justified.
4205       if (Size==1 || Size==2) {
4206         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4207         if (GPR_idx != NumGPRs) {
4208           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4209                                         MachinePointerInfo(), VT,
4210                                         false, false, 0);
4211           MemOpChains.push_back(Load.getValue(1));
4212           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4213
4214           ArgOffset += PtrByteSize;
4215         } else {
4216           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4217                                           PtrOff.getValueType());
4218           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4219           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4220                                                             CallSeqStart,
4221                                                             Flags, DAG, dl);
4222           ArgOffset += PtrByteSize;
4223         }
4224         continue;
4225       }
4226       // Copy entire object into memory.  There are cases where gcc-generated
4227       // code assumes it is there, even if it could be put entirely into
4228       // registers.  (This is not what the doc says.)
4229       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4230                                                         CallSeqStart,
4231                                                         Flags, DAG, dl);
4232
4233       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4234       // copy the pieces of the object that fit into registers from the
4235       // parameter save area.
4236       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4237         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4238         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4239         if (GPR_idx != NumGPRs) {
4240           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4241                                      MachinePointerInfo(),
4242                                      false, false, false, 0);
4243           MemOpChains.push_back(Load.getValue(1));
4244           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4245           ArgOffset += PtrByteSize;
4246         } else {
4247           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4248           break;
4249         }
4250       }
4251       continue;
4252     }
4253
4254     switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4255     default: llvm_unreachable("Unexpected ValueType for argument!");
4256     case MVT::i32:
4257     case MVT::i64:
4258       if (GPR_idx != NumGPRs) {
4259         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4260       } else {
4261         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4262                          isPPC64, isTailCall, false, MemOpChains,
4263                          TailCallArguments, dl);
4264       }
4265       ArgOffset += PtrByteSize;
4266       break;
4267     case MVT::f32:
4268     case MVT::f64:
4269       if (FPR_idx != NumFPRs) {
4270         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4271
4272         if (isVarArg) {
4273           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4274                                        MachinePointerInfo(), false, false, 0);
4275           MemOpChains.push_back(Store);
4276
4277           // Float varargs are always shadowed in available integer registers
4278           if (GPR_idx != NumGPRs) {
4279             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4280                                        MachinePointerInfo(), false, false,
4281                                        false, 0);
4282             MemOpChains.push_back(Load.getValue(1));
4283             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4284           }
4285           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4286             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4287             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4288             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4289                                        MachinePointerInfo(),
4290                                        false, false, false, 0);
4291             MemOpChains.push_back(Load.getValue(1));
4292             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4293           }
4294         } else {
4295           // If we have any FPRs remaining, we may also have GPRs remaining.
4296           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4297           // GPRs.
4298           if (GPR_idx != NumGPRs)
4299             ++GPR_idx;
4300           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4301               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4302             ++GPR_idx;
4303         }
4304       } else
4305         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4306                          isPPC64, isTailCall, false, MemOpChains,
4307                          TailCallArguments, dl);
4308       if (isPPC64)
4309         ArgOffset += 8;
4310       else
4311         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4312       break;
4313     case MVT::v4f32:
4314     case MVT::v4i32:
4315     case MVT::v8i16:
4316     case MVT::v16i8:
4317       if (isVarArg) {
4318         // These go aligned on the stack, or in the corresponding R registers
4319         // when within range.  The Darwin PPC ABI doc claims they also go in
4320         // V registers; in fact gcc does this only for arguments that are
4321         // prototyped, not for those that match the ...  We do it for all
4322         // arguments, seems to work.
4323         while (ArgOffset % 16 !=0) {
4324           ArgOffset += PtrByteSize;
4325           if (GPR_idx != NumGPRs)
4326             GPR_idx++;
4327         }
4328         // We could elide this store in the case where the object fits
4329         // entirely in R registers.  Maybe later.
4330         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4331                             DAG.getConstant(ArgOffset, PtrVT));
4332         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4333                                      MachinePointerInfo(), false, false, 0);
4334         MemOpChains.push_back(Store);
4335         if (VR_idx != NumVRs) {
4336           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4337                                      MachinePointerInfo(),
4338                                      false, false, false, 0);
4339           MemOpChains.push_back(Load.getValue(1));
4340           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4341         }
4342         ArgOffset += 16;
4343         for (unsigned i=0; i<16; i+=PtrByteSize) {
4344           if (GPR_idx == NumGPRs)
4345             break;
4346           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4347                                   DAG.getConstant(i, PtrVT));
4348           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4349                                      false, false, false, 0);
4350           MemOpChains.push_back(Load.getValue(1));
4351           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4352         }
4353         break;
4354       }
4355
4356       // Non-varargs Altivec params generally go in registers, but have
4357       // stack space allocated at the end.
4358       if (VR_idx != NumVRs) {
4359         // Doesn't have GPR space allocated.
4360         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4361       } else if (nAltivecParamsAtEnd==0) {
4362         // We are emitting Altivec params in order.
4363         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4364                          isPPC64, isTailCall, true, MemOpChains,
4365                          TailCallArguments, dl);
4366         ArgOffset += 16;
4367       }
4368       break;
4369     }
4370   }
4371   // If all Altivec parameters fit in registers, as they usually do,
4372   // they get stack space following the non-Altivec parameters.  We
4373   // don't track this here because nobody below needs it.
4374   // If there are more Altivec parameters than fit in registers emit
4375   // the stores here.
4376   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4377     unsigned j = 0;
4378     // Offset is aligned; skip 1st 12 params which go in V registers.
4379     ArgOffset = ((ArgOffset+15)/16)*16;
4380     ArgOffset += 12*16;
4381     for (unsigned i = 0; i != NumOps; ++i) {
4382       SDValue Arg = OutVals[i];
4383       EVT ArgType = Outs[i].VT;
4384       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4385           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4386         if (++j > NumVRs) {
4387           SDValue PtrOff;
4388           // We are emitting Altivec params in order.
4389           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4390                            isPPC64, isTailCall, true, MemOpChains,
4391                            TailCallArguments, dl);
4392           ArgOffset += 16;
4393         }
4394       }
4395     }
4396   }
4397
4398   if (!MemOpChains.empty())
4399     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4400                         &MemOpChains[0], MemOpChains.size());
4401
4402   // On Darwin, R12 must contain the address of an indirect callee.  This does
4403   // not mean the MTCTR instruction must use R12; it's easier to model this as
4404   // an extra parameter, so do that.
4405   if (!isTailCall &&
4406       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4407       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4408       !isBLACompatibleAddress(Callee, DAG))
4409     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4410                                                    PPC::R12), Callee));
4411
4412   // Build a sequence of copy-to-reg nodes chained together with token chain
4413   // and flag operands which copy the outgoing args into the appropriate regs.
4414   SDValue InFlag;
4415   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4416     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4417                              RegsToPass[i].second, InFlag);
4418     InFlag = Chain.getValue(1);
4419   }
4420
4421   if (isTailCall)
4422     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4423                     FPOp, true, TailCallArguments);
4424
4425   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4426                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4427                     Ins, InVals);
4428 }
4429
4430 bool
4431 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4432                                   MachineFunction &MF, bool isVarArg,
4433                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
4434                                   LLVMContext &Context) const {
4435   SmallVector<CCValAssign, 16> RVLocs;
4436   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4437                  RVLocs, Context);
4438   return CCInfo.CheckReturn(Outs, RetCC_PPC);
4439 }
4440
4441 SDValue
4442 PPCTargetLowering::LowerReturn(SDValue Chain,
4443                                CallingConv::ID CallConv, bool isVarArg,
4444                                const SmallVectorImpl<ISD::OutputArg> &Outs,
4445                                const SmallVectorImpl<SDValue> &OutVals,
4446                                DebugLoc dl, SelectionDAG &DAG) const {
4447
4448   SmallVector<CCValAssign, 16> RVLocs;
4449   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4450                  getTargetMachine(), RVLocs, *DAG.getContext());
4451   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4452
4453   SDValue Flag;
4454   SmallVector<SDValue, 4> RetOps(1, Chain);
4455
4456   // Copy the result values into the output registers.
4457   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4458     CCValAssign &VA = RVLocs[i];
4459     assert(VA.isRegLoc() && "Can only return in registers!");
4460
4461     SDValue Arg = OutVals[i];
4462
4463     switch (VA.getLocInfo()) {
4464     default: llvm_unreachable("Unknown loc info!");
4465     case CCValAssign::Full: break;
4466     case CCValAssign::AExt:
4467       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4468       break;
4469     case CCValAssign::ZExt:
4470       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4471       break;
4472     case CCValAssign::SExt:
4473       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4474       break;
4475     }
4476
4477     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4478     Flag = Chain.getValue(1);
4479     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4480   }
4481
4482   RetOps[0] = Chain;  // Update chain.
4483
4484   // Add the flag if we have it.
4485   if (Flag.getNode())
4486     RetOps.push_back(Flag);
4487
4488   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4489                      &RetOps[0], RetOps.size());
4490 }
4491
4492 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4493                                    const PPCSubtarget &Subtarget) const {
4494   // When we pop the dynamic allocation we need to restore the SP link.
4495   DebugLoc dl = Op.getDebugLoc();
4496
4497   // Get the corect type for pointers.
4498   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4499
4500   // Construct the stack pointer operand.
4501   bool isPPC64 = Subtarget.isPPC64();
4502   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4503   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4504
4505   // Get the operands for the STACKRESTORE.
4506   SDValue Chain = Op.getOperand(0);
4507   SDValue SaveSP = Op.getOperand(1);
4508
4509   // Load the old link SP.
4510   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4511                                    MachinePointerInfo(),
4512                                    false, false, false, 0);
4513
4514   // Restore the stack pointer.
4515   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4516
4517   // Store the old link SP.
4518   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4519                       false, false, 0);
4520 }
4521
4522
4523
4524 SDValue
4525 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4526   MachineFunction &MF = DAG.getMachineFunction();
4527   bool isPPC64 = PPCSubTarget.isPPC64();
4528   bool isDarwinABI = PPCSubTarget.isDarwinABI();
4529   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4530
4531   // Get current frame pointer save index.  The users of this index will be
4532   // primarily DYNALLOC instructions.
4533   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4534   int RASI = FI->getReturnAddrSaveIndex();
4535
4536   // If the frame pointer save index hasn't been defined yet.
4537   if (!RASI) {
4538     // Find out what the fix offset of the frame pointer save area.
4539     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4540     // Allocate the frame index for frame pointer save area.
4541     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4542     // Save the result.
4543     FI->setReturnAddrSaveIndex(RASI);
4544   }
4545   return DAG.getFrameIndex(RASI, PtrVT);
4546 }
4547
4548 SDValue
4549 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4550   MachineFunction &MF = DAG.getMachineFunction();
4551   bool isPPC64 = PPCSubTarget.isPPC64();
4552   bool isDarwinABI = PPCSubTarget.isDarwinABI();
4553   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4554
4555   // Get current frame pointer save index.  The users of this index will be
4556   // primarily DYNALLOC instructions.
4557   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4558   int FPSI = FI->getFramePointerSaveIndex();
4559
4560   // If the frame pointer save index hasn't been defined yet.
4561   if (!FPSI) {
4562     // Find out what the fix offset of the frame pointer save area.
4563     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4564                                                            isDarwinABI);
4565
4566     // Allocate the frame index for frame pointer save area.
4567     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4568     // Save the result.
4569     FI->setFramePointerSaveIndex(FPSI);
4570   }
4571   return DAG.getFrameIndex(FPSI, PtrVT);
4572 }
4573
4574 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4575                                          SelectionDAG &DAG,
4576                                          const PPCSubtarget &Subtarget) const {
4577   // Get the inputs.
4578   SDValue Chain = Op.getOperand(0);
4579   SDValue Size  = Op.getOperand(1);
4580   DebugLoc dl = Op.getDebugLoc();
4581
4582   // Get the corect type for pointers.
4583   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4584   // Negate the size.
4585   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4586                                   DAG.getConstant(0, PtrVT), Size);
4587   // Construct a node for the frame pointer save index.
4588   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4589   // Build a DYNALLOC node.
4590   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4591   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4592   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4593 }
4594
4595 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4596                                                SelectionDAG &DAG) const {
4597   DebugLoc DL = Op.getDebugLoc();
4598   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4599                      DAG.getVTList(MVT::i32, MVT::Other),
4600                      Op.getOperand(0), Op.getOperand(1));
4601 }
4602
4603 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4604                                                 SelectionDAG &DAG) const {
4605   DebugLoc DL = Op.getDebugLoc();
4606   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4607                      Op.getOperand(0), Op.getOperand(1));
4608 }
4609
4610 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4611 /// possible.
4612 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4613   // Not FP? Not a fsel.
4614   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4615       !Op.getOperand(2).getValueType().isFloatingPoint())
4616     return Op;
4617
4618   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4619
4620   // Cannot handle SETEQ/SETNE.
4621   if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4622
4623   EVT ResVT = Op.getValueType();
4624   EVT CmpVT = Op.getOperand(0).getValueType();
4625   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4626   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
4627   DebugLoc dl = Op.getDebugLoc();
4628
4629   // If the RHS of the comparison is a 0.0, we don't need to do the
4630   // subtraction at all.
4631   if (isFloatingPointZero(RHS))
4632     switch (CC) {
4633     default: break;       // SETUO etc aren't handled by fsel.
4634     case ISD::SETULT:
4635     case ISD::SETLT:
4636       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
4637     case ISD::SETOGE:
4638     case ISD::SETGE:
4639       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
4640         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4641       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4642     case ISD::SETUGT:
4643     case ISD::SETGT:
4644       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
4645     case ISD::SETOLE:
4646     case ISD::SETLE:
4647       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
4648         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4649       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4650                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4651     }
4652
4653   SDValue Cmp;
4654   switch (CC) {
4655   default: break;       // SETUO etc aren't handled by fsel.
4656   case ISD::SETULT:
4657   case ISD::SETLT:
4658     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4659     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4660       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4661       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4662   case ISD::SETOGE:
4663   case ISD::SETGE:
4664     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4665     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4666       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4667       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4668   case ISD::SETUGT:
4669   case ISD::SETGT:
4670     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4671     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4672       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4673       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4674   case ISD::SETOLE:
4675   case ISD::SETLE:
4676     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4677     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4678       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4679       return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4680   }
4681   return Op;
4682 }
4683
4684 // FIXME: Split this code up when LegalizeDAGTypes lands.
4685 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4686                                            DebugLoc dl) const {
4687   assert(Op.getOperand(0).getValueType().isFloatingPoint());
4688   SDValue Src = Op.getOperand(0);
4689   if (Src.getValueType() == MVT::f32)
4690     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4691
4692   SDValue Tmp;
4693   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4694   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4695   case MVT::i32:
4696     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4697                                                          PPCISD::FCTIDZ,
4698                       dl, MVT::f64, Src);
4699     break;
4700   case MVT::i64:
4701     Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4702     break;
4703   }
4704
4705   // Convert the FP value to an int value through memory.
4706   SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4707
4708   // Emit a store to the stack slot.
4709   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4710                                MachinePointerInfo(), false, false, 0);
4711
4712   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
4713   // add in a bias.
4714   if (Op.getValueType() == MVT::i32)
4715     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4716                         DAG.getConstant(4, FIPtr.getValueType()));
4717   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4718                      false, false, false, 0);
4719 }
4720
4721 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4722                                            SelectionDAG &DAG) const {
4723   DebugLoc dl = Op.getDebugLoc();
4724   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4725   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4726     return SDValue();
4727
4728   if (Op.getOperand(0).getValueType() == MVT::i64) {
4729     SDValue SINT = Op.getOperand(0);
4730     // When converting to single-precision, we actually need to convert
4731     // to double-precision first and then round to single-precision.
4732     // To avoid double-rounding effects during that operation, we have
4733     // to prepare the input operand.  Bits that might be truncated when
4734     // converting to double-precision are replaced by a bit that won't
4735     // be lost at this stage, but is below the single-precision rounding
4736     // position.
4737     //
4738     // However, if -enable-unsafe-fp-math is in effect, accept double
4739     // rounding to avoid the extra overhead.
4740     if (Op.getValueType() == MVT::f32 &&
4741         !DAG.getTarget().Options.UnsafeFPMath) {
4742
4743       // Twiddle input to make sure the low 11 bits are zero.  (If this
4744       // is the case, we are guaranteed the value will fit into the 53 bit
4745       // mantissa of an IEEE double-precision value without rounding.)
4746       // If any of those low 11 bits were not zero originally, make sure
4747       // bit 12 (value 2048) is set instead, so that the final rounding
4748       // to single-precision gets the correct result.
4749       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4750                                   SINT, DAG.getConstant(2047, MVT::i64));
4751       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4752                           Round, DAG.getConstant(2047, MVT::i64));
4753       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4754       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4755                           Round, DAG.getConstant(-2048, MVT::i64));
4756
4757       // However, we cannot use that value unconditionally: if the magnitude
4758       // of the input value is small, the bit-twiddling we did above might
4759       // end up visibly changing the output.  Fortunately, in that case, we
4760       // don't need to twiddle bits since the original input will convert
4761       // exactly to double-precision floating-point already.  Therefore,
4762       // construct a conditional to use the original value if the top 11
4763       // bits are all sign-bit copies, and use the rounded value computed
4764       // above otherwise.
4765       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4766                                  SINT, DAG.getConstant(53, MVT::i32));
4767       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4768                          Cond, DAG.getConstant(1, MVT::i64));
4769       Cond = DAG.getSetCC(dl, MVT::i32,
4770                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4771
4772       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4773     }
4774     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4775     SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4776     if (Op.getValueType() == MVT::f32)
4777       FP = DAG.getNode(ISD::FP_ROUND, dl,
4778                        MVT::f32, FP, DAG.getIntPtrConstant(0));
4779     return FP;
4780   }
4781
4782   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4783          "Unhandled SINT_TO_FP type in custom expander!");
4784   // Since we only generate this in 64-bit mode, we can take advantage of
4785   // 64-bit registers.  In particular, sign extend the input value into the
4786   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4787   // then lfd it and fcfid it.
4788   MachineFunction &MF = DAG.getMachineFunction();
4789   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4790   int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4791   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4792   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4793
4794   SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4795                                 Op.getOperand(0));
4796
4797   // STD the extended value into the stack slot.
4798   MachineMemOperand *MMO =
4799     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4800                             MachineMemOperand::MOStore, 8, 8);
4801   SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4802   SDValue Store =
4803     DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4804                             Ops, 4, MVT::i64, MMO);
4805   // Load the value as a double.
4806   SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4807                            false, false, false, 0);
4808
4809   // FCFID it and return it.
4810   SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4811   if (Op.getValueType() == MVT::f32)
4812     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4813   return FP;
4814 }
4815
4816 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4817                                             SelectionDAG &DAG) const {
4818   DebugLoc dl = Op.getDebugLoc();
4819   /*
4820    The rounding mode is in bits 30:31 of FPSR, and has the following
4821    settings:
4822      00 Round to nearest
4823      01 Round to 0
4824      10 Round to +inf
4825      11 Round to -inf
4826
4827   FLT_ROUNDS, on the other hand, expects the following:
4828     -1 Undefined
4829      0 Round to 0
4830      1 Round to nearest
4831      2 Round to +inf
4832      3 Round to -inf
4833
4834   To perform the conversion, we do:
4835     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4836   */
4837
4838   MachineFunction &MF = DAG.getMachineFunction();
4839   EVT VT = Op.getValueType();
4840   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4841   SDValue MFFSreg, InFlag;
4842
4843   // Save FP Control Word to register
4844   EVT NodeTys[] = {
4845     MVT::f64,    // return register
4846     MVT::Glue    // unused in this context
4847   };
4848   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4849
4850   // Save FP register to stack slot
4851   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4852   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4853   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4854                                StackSlot, MachinePointerInfo(), false, false,0);
4855
4856   // Load FP Control Word from low 32 bits of stack slot.
4857   SDValue Four = DAG.getConstant(4, PtrVT);
4858   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4859   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4860                             false, false, false, 0);
4861
4862   // Transform as necessary
4863   SDValue CWD1 =
4864     DAG.getNode(ISD::AND, dl, MVT::i32,
4865                 CWD, DAG.getConstant(3, MVT::i32));
4866   SDValue CWD2 =
4867     DAG.getNode(ISD::SRL, dl, MVT::i32,
4868                 DAG.getNode(ISD::AND, dl, MVT::i32,
4869                             DAG.getNode(ISD::XOR, dl, MVT::i32,
4870                                         CWD, DAG.getConstant(3, MVT::i32)),
4871                             DAG.getConstant(3, MVT::i32)),
4872                 DAG.getConstant(1, MVT::i32));
4873
4874   SDValue RetVal =
4875     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4876
4877   return DAG.getNode((VT.getSizeInBits() < 16 ?
4878                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4879 }
4880
4881 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4882   EVT VT = Op.getValueType();
4883   unsigned BitWidth = VT.getSizeInBits();
4884   DebugLoc dl = Op.getDebugLoc();
4885   assert(Op.getNumOperands() == 3 &&
4886          VT == Op.getOperand(1).getValueType() &&
4887          "Unexpected SHL!");
4888
4889   // Expand into a bunch of logical ops.  Note that these ops
4890   // depend on the PPC behavior for oversized shift amounts.
4891   SDValue Lo = Op.getOperand(0);
4892   SDValue Hi = Op.getOperand(1);
4893   SDValue Amt = Op.getOperand(2);
4894   EVT AmtVT = Amt.getValueType();
4895
4896   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4897                              DAG.getConstant(BitWidth, AmtVT), Amt);
4898   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4899   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4900   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4901   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4902                              DAG.getConstant(-BitWidth, AmtVT));
4903   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4904   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4905   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4906   SDValue OutOps[] = { OutLo, OutHi };
4907   return DAG.getMergeValues(OutOps, 2, dl);
4908 }
4909
4910 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4911   EVT VT = Op.getValueType();
4912   DebugLoc dl = Op.getDebugLoc();
4913   unsigned BitWidth = VT.getSizeInBits();
4914   assert(Op.getNumOperands() == 3 &&
4915          VT == Op.getOperand(1).getValueType() &&
4916          "Unexpected SRL!");
4917
4918   // Expand into a bunch of logical ops.  Note that these ops
4919   // depend on the PPC behavior for oversized shift amounts.
4920   SDValue Lo = Op.getOperand(0);
4921   SDValue Hi = Op.getOperand(1);
4922   SDValue Amt = Op.getOperand(2);
4923   EVT AmtVT = Amt.getValueType();
4924
4925   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4926                              DAG.getConstant(BitWidth, AmtVT), Amt);
4927   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4928   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4929   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4930   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4931                              DAG.getConstant(-BitWidth, AmtVT));
4932   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4933   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4934   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4935   SDValue OutOps[] = { OutLo, OutHi };
4936   return DAG.getMergeValues(OutOps, 2, dl);
4937 }
4938
4939 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4940   DebugLoc dl = Op.getDebugLoc();
4941   EVT VT = Op.getValueType();
4942   unsigned BitWidth = VT.getSizeInBits();
4943   assert(Op.getNumOperands() == 3 &&
4944          VT == Op.getOperand(1).getValueType() &&
4945          "Unexpected SRA!");
4946
4947   // Expand into a bunch of logical ops, followed by a select_cc.
4948   SDValue Lo = Op.getOperand(0);
4949   SDValue Hi = Op.getOperand(1);
4950   SDValue Amt = Op.getOperand(2);
4951   EVT AmtVT = Amt.getValueType();
4952
4953   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4954                              DAG.getConstant(BitWidth, AmtVT), Amt);
4955   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4956   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4957   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4958   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4959                              DAG.getConstant(-BitWidth, AmtVT));
4960   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4961   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4962   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4963                                   Tmp4, Tmp6, ISD::SETLE);
4964   SDValue OutOps[] = { OutLo, OutHi };
4965   return DAG.getMergeValues(OutOps, 2, dl);
4966 }
4967
4968 //===----------------------------------------------------------------------===//
4969 // Vector related lowering.
4970 //
4971
4972 /// BuildSplatI - Build a canonical splati of Val with an element size of
4973 /// SplatSize.  Cast the result to VT.
4974 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4975                              SelectionDAG &DAG, DebugLoc dl) {
4976   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4977
4978   static const EVT VTys[] = { // canonical VT to use for each size.
4979     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4980   };
4981
4982   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4983
4984   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4985   if (Val == -1)
4986     SplatSize = 1;
4987
4988   EVT CanonicalVT = VTys[SplatSize-1];
4989
4990   // Build a canonical splat for this value.
4991   SDValue Elt = DAG.getConstant(Val, MVT::i32);
4992   SmallVector<SDValue, 8> Ops;
4993   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4994   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4995                               &Ops[0], Ops.size());
4996   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
4997 }
4998
4999 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5000 /// specified intrinsic ID.
5001 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5002                                 SelectionDAG &DAG, DebugLoc dl,
5003                                 EVT DestVT = MVT::Other) {
5004   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5005   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5006                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5007 }
5008
5009 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5010 /// specified intrinsic ID.
5011 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5012                                 SDValue Op2, SelectionDAG &DAG,
5013                                 DebugLoc dl, EVT DestVT = MVT::Other) {
5014   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5015   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5016                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5017 }
5018
5019
5020 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5021 /// amount.  The result has the specified value type.
5022 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5023                              EVT VT, SelectionDAG &DAG, DebugLoc dl) {
5024   // Force LHS/RHS to be the right type.
5025   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5026   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5027
5028   int Ops[16];
5029   for (unsigned i = 0; i != 16; ++i)
5030     Ops[i] = i + Amt;
5031   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5032   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5033 }
5034
5035 // If this is a case we can't handle, return null and let the default
5036 // expansion code take care of it.  If we CAN select this case, and if it
5037 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5038 // this case more efficiently than a constant pool load, lower it to the
5039 // sequence of ops that should be used.
5040 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5041                                              SelectionDAG &DAG) const {
5042   DebugLoc dl = Op.getDebugLoc();
5043   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5044   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5045
5046   // Check if this is a splat of a constant value.
5047   APInt APSplatBits, APSplatUndef;
5048   unsigned SplatBitSize;
5049   bool HasAnyUndefs;
5050   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5051                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5052     return SDValue();
5053
5054   unsigned SplatBits = APSplatBits.getZExtValue();
5055   unsigned SplatUndef = APSplatUndef.getZExtValue();
5056   unsigned SplatSize = SplatBitSize / 8;
5057
5058   // First, handle single instruction cases.
5059
5060   // All zeros?
5061   if (SplatBits == 0) {
5062     // Canonicalize all zero vectors to be v4i32.
5063     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5064       SDValue Z = DAG.getConstant(0, MVT::i32);
5065       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5066       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5067     }
5068     return Op;
5069   }
5070
5071   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5072   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5073                     (32-SplatBitSize));
5074   if (SextVal >= -16 && SextVal <= 15)
5075     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5076
5077
5078   // Two instruction sequences.
5079
5080   // If this value is in the range [-32,30] and is even, use:
5081   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5082   // If this value is in the range [17,31] and is odd, use:
5083   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5084   // If this value is in the range [-31,-17] and is odd, use:
5085   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5086   // Note the last two are three-instruction sequences.
5087   if (SextVal >= -32 && SextVal <= 31) {
5088     // To avoid having these optimizations undone by constant folding,
5089     // we convert to a pseudo that will be expanded later into one of
5090     // the above forms.
5091     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5092     EVT VT = Op.getValueType();
5093     int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5094     SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5095     return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5096   }
5097
5098   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5099   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5100   // for fneg/fabs.
5101   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5102     // Make -1 and vspltisw -1:
5103     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5104
5105     // Make the VSLW intrinsic, computing 0x8000_0000.
5106     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5107                                    OnesV, DAG, dl);
5108
5109     // xor by OnesV to invert it.
5110     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5111     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5112   }
5113
5114   // Check to see if this is a wide variety of vsplti*, binop self cases.
5115   static const signed char SplatCsts[] = {
5116     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5117     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5118   };
5119
5120   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5121     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5122     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5123     int i = SplatCsts[idx];
5124
5125     // Figure out what shift amount will be used by altivec if shifted by i in
5126     // this splat size.
5127     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5128
5129     // vsplti + shl self.
5130     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5131       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5132       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5133         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5134         Intrinsic::ppc_altivec_vslw
5135       };
5136       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5137       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5138     }
5139
5140     // vsplti + srl self.
5141     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5142       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5143       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5144         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5145         Intrinsic::ppc_altivec_vsrw
5146       };
5147       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5148       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5149     }
5150
5151     // vsplti + sra self.
5152     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5153       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5154       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5155         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5156         Intrinsic::ppc_altivec_vsraw
5157       };
5158       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5159       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5160     }
5161
5162     // vsplti + rol self.
5163     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5164                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5165       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5166       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5167         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5168         Intrinsic::ppc_altivec_vrlw
5169       };
5170       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5171       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5172     }
5173
5174     // t = vsplti c, result = vsldoi t, t, 1
5175     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5176       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5177       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5178     }
5179     // t = vsplti c, result = vsldoi t, t, 2
5180     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5181       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5182       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5183     }
5184     // t = vsplti c, result = vsldoi t, t, 3
5185     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5186       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5187       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5188     }
5189   }
5190
5191   return SDValue();
5192 }
5193
5194 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5195 /// the specified operations to build the shuffle.
5196 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5197                                       SDValue RHS, SelectionDAG &DAG,
5198                                       DebugLoc dl) {
5199   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5200   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5201   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5202
5203   enum {
5204     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5205     OP_VMRGHW,
5206     OP_VMRGLW,
5207     OP_VSPLTISW0,
5208     OP_VSPLTISW1,
5209     OP_VSPLTISW2,
5210     OP_VSPLTISW3,
5211     OP_VSLDOI4,
5212     OP_VSLDOI8,
5213     OP_VSLDOI12
5214   };
5215
5216   if (OpNum == OP_COPY) {
5217     if (LHSID == (1*9+2)*9+3) return LHS;
5218     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5219     return RHS;
5220   }
5221
5222   SDValue OpLHS, OpRHS;
5223   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5224   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5225
5226   int ShufIdxs[16];
5227   switch (OpNum) {
5228   default: llvm_unreachable("Unknown i32 permute!");
5229   case OP_VMRGHW:
5230     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5231     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5232     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5233     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5234     break;
5235   case OP_VMRGLW:
5236     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5237     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5238     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5239     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5240     break;
5241   case OP_VSPLTISW0:
5242     for (unsigned i = 0; i != 16; ++i)
5243       ShufIdxs[i] = (i&3)+0;
5244     break;
5245   case OP_VSPLTISW1:
5246     for (unsigned i = 0; i != 16; ++i)
5247       ShufIdxs[i] = (i&3)+4;
5248     break;
5249   case OP_VSPLTISW2:
5250     for (unsigned i = 0; i != 16; ++i)
5251       ShufIdxs[i] = (i&3)+8;
5252     break;
5253   case OP_VSPLTISW3:
5254     for (unsigned i = 0; i != 16; ++i)
5255       ShufIdxs[i] = (i&3)+12;
5256     break;
5257   case OP_VSLDOI4:
5258     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5259   case OP_VSLDOI8:
5260     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5261   case OP_VSLDOI12:
5262     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5263   }
5264   EVT VT = OpLHS.getValueType();
5265   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5266   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5267   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5268   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5269 }
5270
5271 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
5272 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
5273 /// return the code it can be lowered into.  Worst case, it can always be
5274 /// lowered into a vperm.
5275 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5276                                                SelectionDAG &DAG) const {
5277   DebugLoc dl = Op.getDebugLoc();
5278   SDValue V1 = Op.getOperand(0);
5279   SDValue V2 = Op.getOperand(1);
5280   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5281   EVT VT = Op.getValueType();
5282
5283   // Cases that are handled by instructions that take permute immediates
5284   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5285   // selected by the instruction selector.
5286   if (V2.getOpcode() == ISD::UNDEF) {
5287     if (PPC::isSplatShuffleMask(SVOp, 1) ||
5288         PPC::isSplatShuffleMask(SVOp, 2) ||
5289         PPC::isSplatShuffleMask(SVOp, 4) ||
5290         PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5291         PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5292         PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5293         PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5294         PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5295         PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5296         PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5297         PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5298         PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5299       return Op;
5300     }
5301   }
5302
5303   // Altivec has a variety of "shuffle immediates" that take two vector inputs
5304   // and produce a fixed permutation.  If any of these match, do not lower to
5305   // VPERM.
5306   if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5307       PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5308       PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5309       PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5310       PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5311       PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5312       PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5313       PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5314       PPC::isVMRGHShuffleMask(SVOp, 4, false))
5315     return Op;
5316
5317   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
5318   // perfect shuffle table to emit an optimal matching sequence.
5319   ArrayRef<int> PermMask = SVOp->getMask();
5320
5321   unsigned PFIndexes[4];
5322   bool isFourElementShuffle = true;
5323   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5324     unsigned EltNo = 8;   // Start out undef.
5325     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
5326       if (PermMask[i*4+j] < 0)
5327         continue;   // Undef, ignore it.
5328
5329       unsigned ByteSource = PermMask[i*4+j];
5330       if ((ByteSource & 3) != j) {
5331         isFourElementShuffle = false;
5332         break;
5333       }
5334
5335       if (EltNo == 8) {
5336         EltNo = ByteSource/4;
5337       } else if (EltNo != ByteSource/4) {
5338         isFourElementShuffle = false;
5339         break;
5340       }
5341     }
5342     PFIndexes[i] = EltNo;
5343   }
5344
5345   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5346   // perfect shuffle vector to determine if it is cost effective to do this as
5347   // discrete instructions, or whether we should use a vperm.
5348   if (isFourElementShuffle) {
5349     // Compute the index in the perfect shuffle table.
5350     unsigned PFTableIndex =
5351       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5352
5353     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5354     unsigned Cost  = (PFEntry >> 30);
5355
5356     // Determining when to avoid vperm is tricky.  Many things affect the cost
5357     // of vperm, particularly how many times the perm mask needs to be computed.
5358     // For example, if the perm mask can be hoisted out of a loop or is already
5359     // used (perhaps because there are multiple permutes with the same shuffle
5360     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
5361     // the loop requires an extra register.
5362     //
5363     // As a compromise, we only emit discrete instructions if the shuffle can be
5364     // generated in 3 or fewer operations.  When we have loop information
5365     // available, if this block is within a loop, we should avoid using vperm
5366     // for 3-operation perms and use a constant pool load instead.
5367     if (Cost < 3)
5368       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5369   }
5370
5371   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5372   // vector that will get spilled to the constant pool.
5373   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5374
5375   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5376   // that it is in input element units, not in bytes.  Convert now.
5377   EVT EltVT = V1.getValueType().getVectorElementType();
5378   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5379
5380   SmallVector<SDValue, 16> ResultMask;
5381   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5382     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5383
5384     for (unsigned j = 0; j != BytesPerElement; ++j)
5385       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5386                                            MVT::i32));
5387   }
5388
5389   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5390                                     &ResultMask[0], ResultMask.size());
5391   return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5392 }
5393
5394 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5395 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
5396 /// information about the intrinsic.
5397 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5398                                   bool &isDot) {
5399   unsigned IntrinsicID =
5400     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5401   CompareOpc = -1;
5402   isDot = false;
5403   switch (IntrinsicID) {
5404   default: return false;
5405     // Comparison predicates.
5406   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
5407   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5408   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
5409   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
5410   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5411   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5412   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5413   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5414   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5415   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5416   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5417   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5418   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5419
5420     // Normal Comparisons.
5421   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
5422   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
5423   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
5424   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
5425   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
5426   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
5427   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
5428   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
5429   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
5430   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
5431   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
5432   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
5433   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
5434   }
5435   return true;
5436 }
5437
5438 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5439 /// lower, do it, otherwise return null.
5440 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5441                                                    SelectionDAG &DAG) const {
5442   // If this is a lowered altivec predicate compare, CompareOpc is set to the
5443   // opcode number of the comparison.
5444   DebugLoc dl = Op.getDebugLoc();
5445   int CompareOpc;
5446   bool isDot;
5447   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5448     return SDValue();    // Don't custom lower most intrinsics.
5449
5450   // If this is a non-dot comparison, make the VCMP node and we are done.
5451   if (!isDot) {
5452     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5453                               Op.getOperand(1), Op.getOperand(2),
5454                               DAG.getConstant(CompareOpc, MVT::i32));
5455     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5456   }
5457
5458   // Create the PPCISD altivec 'dot' comparison node.
5459   SDValue Ops[] = {
5460     Op.getOperand(2),  // LHS
5461     Op.getOperand(3),  // RHS
5462     DAG.getConstant(CompareOpc, MVT::i32)
5463   };
5464   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5465   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5466
5467   // Now that we have the comparison, emit a copy from the CR to a GPR.
5468   // This is flagged to the above dot comparison.
5469   SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5470                                 DAG.getRegister(PPC::CR6, MVT::i32),
5471                                 CompNode.getValue(1));
5472
5473   // Unpack the result based on how the target uses it.
5474   unsigned BitNo;   // Bit # of CR6.
5475   bool InvertBit;   // Invert result?
5476   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5477   default:  // Can't happen, don't crash on invalid number though.
5478   case 0:   // Return the value of the EQ bit of CR6.
5479     BitNo = 0; InvertBit = false;
5480     break;
5481   case 1:   // Return the inverted value of the EQ bit of CR6.
5482     BitNo = 0; InvertBit = true;
5483     break;
5484   case 2:   // Return the value of the LT bit of CR6.
5485     BitNo = 2; InvertBit = false;
5486     break;
5487   case 3:   // Return the inverted value of the LT bit of CR6.
5488     BitNo = 2; InvertBit = true;
5489     break;
5490   }
5491
5492   // Shift the bit into the low position.
5493   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5494                       DAG.getConstant(8-(3-BitNo), MVT::i32));
5495   // Isolate the bit.
5496   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5497                       DAG.getConstant(1, MVT::i32));
5498
5499   // If we are supposed to, toggle the bit.
5500   if (InvertBit)
5501     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5502                         DAG.getConstant(1, MVT::i32));
5503   return Flags;
5504 }
5505
5506 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5507                                                    SelectionDAG &DAG) const {
5508   DebugLoc dl = Op.getDebugLoc();
5509   // Create a stack slot that is 16-byte aligned.
5510   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5511   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5512   EVT PtrVT = getPointerTy();
5513   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5514
5515   // Store the input value into Value#0 of the stack slot.
5516   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5517                                Op.getOperand(0), FIdx, MachinePointerInfo(),
5518                                false, false, 0);
5519   // Load it out.
5520   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5521                      false, false, false, 0);
5522 }
5523
5524 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5525   DebugLoc dl = Op.getDebugLoc();
5526   if (Op.getValueType() == MVT::v4i32) {
5527     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5528
5529     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
5530     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5531
5532     SDValue RHSSwap =   // = vrlw RHS, 16
5533       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5534
5535     // Shrinkify inputs to v8i16.
5536     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5537     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5538     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5539
5540     // Low parts multiplied together, generating 32-bit results (we ignore the
5541     // top parts).
5542     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5543                                         LHS, RHS, DAG, dl, MVT::v4i32);
5544
5545     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5546                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5547     // Shift the high parts up 16 bits.
5548     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5549                               Neg16, DAG, dl);
5550     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5551   } else if (Op.getValueType() == MVT::v8i16) {
5552     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5553
5554     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5555
5556     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5557                             LHS, RHS, Zero, DAG, dl);
5558   } else if (Op.getValueType() == MVT::v16i8) {
5559     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5560
5561     // Multiply the even 8-bit parts, producing 16-bit sums.
5562     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5563                                            LHS, RHS, DAG, dl, MVT::v8i16);
5564     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5565
5566     // Multiply the odd 8-bit parts, producing 16-bit sums.
5567     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5568                                           LHS, RHS, DAG, dl, MVT::v8i16);
5569     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5570
5571     // Merge the results together.
5572     int Ops[16];
5573     for (unsigned i = 0; i != 8; ++i) {
5574       Ops[i*2  ] = 2*i+1;
5575       Ops[i*2+1] = 2*i+1+16;
5576     }
5577     return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5578   } else {
5579     llvm_unreachable("Unknown mul to lower!");
5580   }
5581 }
5582
5583 /// LowerOperation - Provide custom lowering hooks for some operations.
5584 ///
5585 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5586   switch (Op.getOpcode()) {
5587   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5588   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5589   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
5590   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5591   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5592   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5593   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5594   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
5595   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
5596   case ISD::VASTART:
5597     return LowerVASTART(Op, DAG, PPCSubTarget);
5598
5599   case ISD::VAARG:
5600     return LowerVAARG(Op, DAG, PPCSubTarget);
5601
5602   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5603   case ISD::DYNAMIC_STACKALLOC:
5604     return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5605
5606   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
5607   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
5608
5609   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
5610   case ISD::FP_TO_UINT:
5611   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
5612                                                        Op.getDebugLoc());
5613   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5614   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5615
5616   // Lower 64-bit shifts.
5617   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
5618   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
5619   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
5620
5621   // Vector-related lowering.
5622   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5623   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5624   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5625   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5626   case ISD::MUL:                return LowerMUL(Op, DAG);
5627
5628   // Frame & Return address.
5629   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5630   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5631   }
5632 }
5633
5634 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5635                                            SmallVectorImpl<SDValue>&Results,
5636                                            SelectionDAG &DAG) const {
5637   const TargetMachine &TM = getTargetMachine();
5638   DebugLoc dl = N->getDebugLoc();
5639   switch (N->getOpcode()) {
5640   default:
5641     llvm_unreachable("Do not know how to custom type legalize this operation!");
5642   case ISD::VAARG: {
5643     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5644         || TM.getSubtarget<PPCSubtarget>().isPPC64())
5645       return;
5646
5647     EVT VT = N->getValueType(0);
5648
5649     if (VT == MVT::i64) {
5650       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5651
5652       Results.push_back(NewNode);
5653       Results.push_back(NewNode.getValue(1));
5654     }
5655     return;
5656   }
5657   case ISD::FP_ROUND_INREG: {
5658     assert(N->getValueType(0) == MVT::ppcf128);
5659     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5660     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5661                              MVT::f64, N->getOperand(0),
5662                              DAG.getIntPtrConstant(0));
5663     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5664                              MVT::f64, N->getOperand(0),
5665                              DAG.getIntPtrConstant(1));
5666
5667     // Add the two halves of the long double in round-to-zero mode.
5668     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5669
5670     // We know the low half is about to be thrown away, so just use something
5671     // convenient.
5672     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5673                                 FPreg, FPreg));
5674     return;
5675   }
5676   case ISD::FP_TO_SINT:
5677     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5678     return;
5679   }
5680 }
5681
5682
5683 //===----------------------------------------------------------------------===//
5684 //  Other Lowering Code
5685 //===----------------------------------------------------------------------===//
5686
5687 MachineBasicBlock *
5688 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5689                                     bool is64bit, unsigned BinOpcode) const {
5690   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5691   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5692
5693   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5694   MachineFunction *F = BB->getParent();
5695   MachineFunction::iterator It = BB;
5696   ++It;
5697
5698   unsigned dest = MI->getOperand(0).getReg();
5699   unsigned ptrA = MI->getOperand(1).getReg();
5700   unsigned ptrB = MI->getOperand(2).getReg();
5701   unsigned incr = MI->getOperand(3).getReg();
5702   DebugLoc dl = MI->getDebugLoc();
5703
5704   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5705   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5706   F->insert(It, loopMBB);
5707   F->insert(It, exitMBB);
5708   exitMBB->splice(exitMBB->begin(), BB,
5709                   llvm::next(MachineBasicBlock::iterator(MI)),
5710                   BB->end());
5711   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5712
5713   MachineRegisterInfo &RegInfo = F->getRegInfo();
5714   unsigned TmpReg = (!BinOpcode) ? incr :
5715     RegInfo.createVirtualRegister(
5716        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5717                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
5718
5719   //  thisMBB:
5720   //   ...
5721   //   fallthrough --> loopMBB
5722   BB->addSuccessor(loopMBB);
5723
5724   //  loopMBB:
5725   //   l[wd]arx dest, ptr
5726   //   add r0, dest, incr
5727   //   st[wd]cx. r0, ptr
5728   //   bne- loopMBB
5729   //   fallthrough --> exitMBB
5730   BB = loopMBB;
5731   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5732     .addReg(ptrA).addReg(ptrB);
5733   if (BinOpcode)
5734     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5735   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5736     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5737   BuildMI(BB, dl, TII->get(PPC::BCC))
5738     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5739   BB->addSuccessor(loopMBB);
5740   BB->addSuccessor(exitMBB);
5741
5742   //  exitMBB:
5743   //   ...
5744   BB = exitMBB;
5745   return BB;
5746 }
5747
5748 MachineBasicBlock *
5749 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5750                                             MachineBasicBlock *BB,
5751                                             bool is8bit,    // operation
5752                                             unsigned BinOpcode) const {
5753   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5754   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5755   // In 64 bit mode we have to use 64 bits for addresses, even though the
5756   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
5757   // registers without caring whether they're 32 or 64, but here we're
5758   // doing actual arithmetic on the addresses.
5759   bool is64bit = PPCSubTarget.isPPC64();
5760   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5761
5762   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5763   MachineFunction *F = BB->getParent();
5764   MachineFunction::iterator It = BB;
5765   ++It;
5766
5767   unsigned dest = MI->getOperand(0).getReg();
5768   unsigned ptrA = MI->getOperand(1).getReg();
5769   unsigned ptrB = MI->getOperand(2).getReg();
5770   unsigned incr = MI->getOperand(3).getReg();
5771   DebugLoc dl = MI->getDebugLoc();
5772
5773   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5774   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5775   F->insert(It, loopMBB);
5776   F->insert(It, exitMBB);
5777   exitMBB->splice(exitMBB->begin(), BB,
5778                   llvm::next(MachineBasicBlock::iterator(MI)),
5779                   BB->end());
5780   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5781
5782   MachineRegisterInfo &RegInfo = F->getRegInfo();
5783   const TargetRegisterClass *RC =
5784     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5785               (const TargetRegisterClass *) &PPC::GPRCRegClass;
5786   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5787   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5788   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5789   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5790   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5791   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5792   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5793   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5794   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5795   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5796   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5797   unsigned Ptr1Reg;
5798   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5799
5800   //  thisMBB:
5801   //   ...
5802   //   fallthrough --> loopMBB
5803   BB->addSuccessor(loopMBB);
5804
5805   // The 4-byte load must be aligned, while a char or short may be
5806   // anywhere in the word.  Hence all this nasty bookkeeping code.
5807   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
5808   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5809   //   xori shift, shift1, 24 [16]
5810   //   rlwinm ptr, ptr1, 0, 0, 29
5811   //   slw incr2, incr, shift
5812   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5813   //   slw mask, mask2, shift
5814   //  loopMBB:
5815   //   lwarx tmpDest, ptr
5816   //   add tmp, tmpDest, incr2
5817   //   andc tmp2, tmpDest, mask
5818   //   and tmp3, tmp, mask
5819   //   or tmp4, tmp3, tmp2
5820   //   stwcx. tmp4, ptr
5821   //   bne- loopMBB
5822   //   fallthrough --> exitMBB
5823   //   srw dest, tmpDest, shift
5824   if (ptrA != ZeroReg) {
5825     Ptr1Reg = RegInfo.createVirtualRegister(RC);
5826     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5827       .addReg(ptrA).addReg(ptrB);
5828   } else {
5829     Ptr1Reg = ptrB;
5830   }
5831   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5832       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5833   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5834       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5835   if (is64bit)
5836     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5837       .addReg(Ptr1Reg).addImm(0).addImm(61);
5838   else
5839     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5840       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5841   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5842       .addReg(incr).addReg(ShiftReg);
5843   if (is8bit)
5844     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5845   else {
5846     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5847     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5848   }
5849   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5850       .addReg(Mask2Reg).addReg(ShiftReg);
5851
5852   BB = loopMBB;
5853   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5854     .addReg(ZeroReg).addReg(PtrReg);
5855   if (BinOpcode)
5856     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5857       .addReg(Incr2Reg).addReg(TmpDestReg);
5858   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5859     .addReg(TmpDestReg).addReg(MaskReg);
5860   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5861     .addReg(TmpReg).addReg(MaskReg);
5862   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5863     .addReg(Tmp3Reg).addReg(Tmp2Reg);
5864   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5865     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5866   BuildMI(BB, dl, TII->get(PPC::BCC))
5867     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5868   BB->addSuccessor(loopMBB);
5869   BB->addSuccessor(exitMBB);
5870
5871   //  exitMBB:
5872   //   ...
5873   BB = exitMBB;
5874   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5875     .addReg(ShiftReg);
5876   return BB;
5877 }
5878
5879 llvm::MachineBasicBlock*
5880 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
5881                                     MachineBasicBlock *MBB) const {
5882   DebugLoc DL = MI->getDebugLoc();
5883   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5884
5885   MachineFunction *MF = MBB->getParent();
5886   MachineRegisterInfo &MRI = MF->getRegInfo();
5887
5888   const BasicBlock *BB = MBB->getBasicBlock();
5889   MachineFunction::iterator I = MBB;
5890   ++I;
5891
5892   // Memory Reference
5893   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
5894   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
5895
5896   unsigned DstReg = MI->getOperand(0).getReg();
5897   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
5898   assert(RC->hasType(MVT::i32) && "Invalid destination!");
5899   unsigned mainDstReg = MRI.createVirtualRegister(RC);
5900   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
5901
5902   MVT PVT = getPointerTy();
5903   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
5904          "Invalid Pointer Size!");
5905   // For v = setjmp(buf), we generate
5906   //
5907   // thisMBB:
5908   //  SjLjSetup mainMBB
5909   //  bl mainMBB
5910   //  v_restore = 1
5911   //  b sinkMBB
5912   //
5913   // mainMBB:
5914   //  buf[LabelOffset] = LR
5915   //  v_main = 0
5916   //
5917   // sinkMBB:
5918   //  v = phi(main, restore)
5919   //
5920
5921   MachineBasicBlock *thisMBB = MBB;
5922   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
5923   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
5924   MF->insert(I, mainMBB);
5925   MF->insert(I, sinkMBB);
5926
5927   MachineInstrBuilder MIB;
5928
5929   // Transfer the remainder of BB and its successor edges to sinkMBB.
5930   sinkMBB->splice(sinkMBB->begin(), MBB,
5931                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
5932   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
5933
5934   // Note that the structure of the jmp_buf used here is not compatible
5935   // with that used by libc, and is not designed to be. Specifically, it
5936   // stores only those 'reserved' registers that LLVM does not otherwise
5937   // understand how to spill. Also, by convention, by the time this
5938   // intrinsic is called, Clang has already stored the frame address in the
5939   // first slot of the buffer and stack address in the third. Following the
5940   // X86 target code, we'll store the jump address in the second slot. We also
5941   // need to save the TOC pointer (R2) to handle jumps between shared
5942   // libraries, and that will be stored in the fourth slot. The thread
5943   // identifier (R13) is not affected.
5944
5945   // thisMBB:
5946   const int64_t LabelOffset = 1 * PVT.getStoreSize();
5947   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
5948
5949   // Prepare IP either in reg.
5950   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
5951   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
5952   unsigned BufReg = MI->getOperand(1).getReg();
5953
5954   if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
5955     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
5956             .addReg(PPC::X2)
5957             .addImm(TOCOffset / 4)
5958             .addReg(BufReg);
5959
5960     MIB.setMemRefs(MMOBegin, MMOEnd);
5961   }
5962
5963   // Setup
5964   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCL)).addMBB(mainMBB);
5965   MIB.addRegMask(PPCRegInfo->getNoPreservedMask());
5966
5967   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
5968
5969   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
5970           .addMBB(mainMBB);
5971   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
5972
5973   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
5974   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
5975
5976   // mainMBB:
5977   //  mainDstReg = 0
5978   MIB = BuildMI(mainMBB, DL,
5979     TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
5980
5981   // Store IP
5982   if (PPCSubTarget.isPPC64()) {
5983     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
5984             .addReg(LabelReg)
5985             .addImm(LabelOffset / 4)
5986             .addReg(BufReg);
5987   } else {
5988     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
5989             .addReg(LabelReg)
5990             .addImm(LabelOffset)
5991             .addReg(BufReg);
5992   }
5993
5994   MIB.setMemRefs(MMOBegin, MMOEnd);
5995
5996   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
5997   mainMBB->addSuccessor(sinkMBB);
5998
5999   // sinkMBB:
6000   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6001           TII->get(PPC::PHI), DstReg)
6002     .addReg(mainDstReg).addMBB(mainMBB)
6003     .addReg(restoreDstReg).addMBB(thisMBB);
6004
6005   MI->eraseFromParent();
6006   return sinkMBB;
6007 }
6008
6009 MachineBasicBlock *
6010 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6011                                      MachineBasicBlock *MBB) const {
6012   DebugLoc DL = MI->getDebugLoc();
6013   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6014
6015   MachineFunction *MF = MBB->getParent();
6016   MachineRegisterInfo &MRI = MF->getRegInfo();
6017
6018   // Memory Reference
6019   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6020   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6021
6022   MVT PVT = getPointerTy();
6023   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6024          "Invalid Pointer Size!");
6025
6026   const TargetRegisterClass *RC =
6027     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6028   unsigned Tmp = MRI.createVirtualRegister(RC);
6029   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6030   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6031   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6032
6033   MachineInstrBuilder MIB;
6034
6035   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6036   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6037   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6038
6039   unsigned BufReg = MI->getOperand(0).getReg();
6040
6041   // Reload FP (the jumped-to function may not have had a
6042   // frame pointer, and if so, then its r31 will be restored
6043   // as necessary).
6044   if (PVT == MVT::i64) {
6045     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6046             .addImm(0)
6047             .addReg(BufReg);
6048   } else {
6049     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6050             .addImm(0)
6051             .addReg(BufReg);
6052   }
6053   MIB.setMemRefs(MMOBegin, MMOEnd);
6054
6055   // Reload IP
6056   if (PVT == MVT::i64) {
6057     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6058             .addImm(LabelOffset / 4)
6059             .addReg(BufReg);
6060   } else {
6061     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6062             .addImm(LabelOffset)
6063             .addReg(BufReg);
6064   }
6065   MIB.setMemRefs(MMOBegin, MMOEnd);
6066
6067   // Reload SP
6068   if (PVT == MVT::i64) {
6069     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6070             .addImm(SPOffset / 4)
6071             .addReg(BufReg);
6072   } else {
6073     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6074             .addImm(SPOffset)
6075             .addReg(BufReg);
6076   }
6077   MIB.setMemRefs(MMOBegin, MMOEnd);
6078
6079   // FIXME: When we also support base pointers, that register must also be
6080   // restored here.
6081
6082   // Reload TOC
6083   if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6084     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6085             .addImm(TOCOffset / 4)
6086             .addReg(BufReg);
6087
6088     MIB.setMemRefs(MMOBegin, MMOEnd);
6089   }
6090
6091   // Jump
6092   BuildMI(*MBB, MI, DL,
6093           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6094   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6095
6096   MI->eraseFromParent();
6097   return MBB;
6098 }
6099
6100 MachineBasicBlock *
6101 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6102                                                MachineBasicBlock *BB) const {
6103   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6104       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6105     return emitEHSjLjSetJmp(MI, BB);
6106   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6107              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6108     return emitEHSjLjLongJmp(MI, BB);
6109   }
6110
6111   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6112
6113   // To "insert" these instructions we actually have to insert their
6114   // control-flow patterns.
6115   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6116   MachineFunction::iterator It = BB;
6117   ++It;
6118
6119   MachineFunction *F = BB->getParent();
6120
6121   if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6122                                  MI->getOpcode() == PPC::SELECT_CC_I8)) {
6123     unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
6124                                          PPC::ISEL8 : PPC::ISEL;
6125     unsigned SelectPred = MI->getOperand(4).getImm();
6126     DebugLoc dl = MI->getDebugLoc();
6127
6128     unsigned SubIdx;
6129     bool SwapOps;
6130     switch (SelectPred) {
6131     default: llvm_unreachable("invalid predicate for isel");
6132     case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
6133     case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
6134     case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
6135     case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
6136     case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
6137     case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
6138     case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
6139     case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
6140     }
6141
6142     BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
6143       .addReg(MI->getOperand(SwapOps? 3 : 2).getReg())
6144       .addReg(MI->getOperand(SwapOps? 2 : 3).getReg())
6145       .addReg(MI->getOperand(1).getReg(), 0, SubIdx);
6146   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6147              MI->getOpcode() == PPC::SELECT_CC_I8 ||
6148              MI->getOpcode() == PPC::SELECT_CC_F4 ||
6149              MI->getOpcode() == PPC::SELECT_CC_F8 ||
6150              MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6151
6152
6153     // The incoming instruction knows the destination vreg to set, the
6154     // condition code register to branch on, the true/false values to
6155     // select between, and a branch opcode to use.
6156
6157     //  thisMBB:
6158     //  ...
6159     //   TrueVal = ...
6160     //   cmpTY ccX, r1, r2
6161     //   bCC copy1MBB
6162     //   fallthrough --> copy0MBB
6163     MachineBasicBlock *thisMBB = BB;
6164     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6165     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6166     unsigned SelectPred = MI->getOperand(4).getImm();
6167     DebugLoc dl = MI->getDebugLoc();
6168     F->insert(It, copy0MBB);
6169     F->insert(It, sinkMBB);
6170
6171     // Transfer the remainder of BB and its successor edges to sinkMBB.
6172     sinkMBB->splice(sinkMBB->begin(), BB,
6173                     llvm::next(MachineBasicBlock::iterator(MI)),
6174                     BB->end());
6175     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6176
6177     // Next, add the true and fallthrough blocks as its successors.
6178     BB->addSuccessor(copy0MBB);
6179     BB->addSuccessor(sinkMBB);
6180
6181     BuildMI(BB, dl, TII->get(PPC::BCC))
6182       .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6183
6184     //  copy0MBB:
6185     //   %FalseValue = ...
6186     //   # fallthrough to sinkMBB
6187     BB = copy0MBB;
6188
6189     // Update machine-CFG edges
6190     BB->addSuccessor(sinkMBB);
6191
6192     //  sinkMBB:
6193     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6194     //  ...
6195     BB = sinkMBB;
6196     BuildMI(*BB, BB->begin(), dl,
6197             TII->get(PPC::PHI), MI->getOperand(0).getReg())
6198       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6199       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6200   }
6201   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6202     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6203   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6204     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6205   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6206     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6207   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6208     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6209
6210   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6211     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6212   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6213     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6214   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6215     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6216   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6217     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6218
6219   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6220     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6221   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6222     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6223   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6224     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6225   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6226     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6227
6228   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6229     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6230   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6231     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6232   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6233     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6234   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6235     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6236
6237   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6238     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6239   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6240     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6241   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6242     BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6243   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6244     BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6245
6246   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6247     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6248   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6249     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6250   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6251     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6252   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6253     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6254
6255   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6256     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6257   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6258     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6259   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6260     BB = EmitAtomicBinary(MI, BB, false, 0);
6261   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6262     BB = EmitAtomicBinary(MI, BB, true, 0);
6263
6264   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6265            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6266     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6267
6268     unsigned dest   = MI->getOperand(0).getReg();
6269     unsigned ptrA   = MI->getOperand(1).getReg();
6270     unsigned ptrB   = MI->getOperand(2).getReg();
6271     unsigned oldval = MI->getOperand(3).getReg();
6272     unsigned newval = MI->getOperand(4).getReg();
6273     DebugLoc dl     = MI->getDebugLoc();
6274
6275     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6276     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6277     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6278     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6279     F->insert(It, loop1MBB);
6280     F->insert(It, loop2MBB);
6281     F->insert(It, midMBB);
6282     F->insert(It, exitMBB);
6283     exitMBB->splice(exitMBB->begin(), BB,
6284                     llvm::next(MachineBasicBlock::iterator(MI)),
6285                     BB->end());
6286     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6287
6288     //  thisMBB:
6289     //   ...
6290     //   fallthrough --> loopMBB
6291     BB->addSuccessor(loop1MBB);
6292
6293     // loop1MBB:
6294     //   l[wd]arx dest, ptr
6295     //   cmp[wd] dest, oldval
6296     //   bne- midMBB
6297     // loop2MBB:
6298     //   st[wd]cx. newval, ptr
6299     //   bne- loopMBB
6300     //   b exitBB
6301     // midMBB:
6302     //   st[wd]cx. dest, ptr
6303     // exitBB:
6304     BB = loop1MBB;
6305     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6306       .addReg(ptrA).addReg(ptrB);
6307     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6308       .addReg(oldval).addReg(dest);
6309     BuildMI(BB, dl, TII->get(PPC::BCC))
6310       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6311     BB->addSuccessor(loop2MBB);
6312     BB->addSuccessor(midMBB);
6313
6314     BB = loop2MBB;
6315     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6316       .addReg(newval).addReg(ptrA).addReg(ptrB);
6317     BuildMI(BB, dl, TII->get(PPC::BCC))
6318       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6319     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6320     BB->addSuccessor(loop1MBB);
6321     BB->addSuccessor(exitMBB);
6322
6323     BB = midMBB;
6324     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6325       .addReg(dest).addReg(ptrA).addReg(ptrB);
6326     BB->addSuccessor(exitMBB);
6327
6328     //  exitMBB:
6329     //   ...
6330     BB = exitMBB;
6331   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6332              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6333     // We must use 64-bit registers for addresses when targeting 64-bit,
6334     // since we're actually doing arithmetic on them.  Other registers
6335     // can be 32-bit.
6336     bool is64bit = PPCSubTarget.isPPC64();
6337     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6338
6339     unsigned dest   = MI->getOperand(0).getReg();
6340     unsigned ptrA   = MI->getOperand(1).getReg();
6341     unsigned ptrB   = MI->getOperand(2).getReg();
6342     unsigned oldval = MI->getOperand(3).getReg();
6343     unsigned newval = MI->getOperand(4).getReg();
6344     DebugLoc dl     = MI->getDebugLoc();
6345
6346     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6347     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6348     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6349     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6350     F->insert(It, loop1MBB);
6351     F->insert(It, loop2MBB);
6352     F->insert(It, midMBB);
6353     F->insert(It, exitMBB);
6354     exitMBB->splice(exitMBB->begin(), BB,
6355                     llvm::next(MachineBasicBlock::iterator(MI)),
6356                     BB->end());
6357     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6358
6359     MachineRegisterInfo &RegInfo = F->getRegInfo();
6360     const TargetRegisterClass *RC =
6361       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6362                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6363     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6364     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6365     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6366     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6367     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6368     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6369     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6370     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6371     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6372     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6373     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6374     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6375     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6376     unsigned Ptr1Reg;
6377     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6378     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6379     //  thisMBB:
6380     //   ...
6381     //   fallthrough --> loopMBB
6382     BB->addSuccessor(loop1MBB);
6383
6384     // The 4-byte load must be aligned, while a char or short may be
6385     // anywhere in the word.  Hence all this nasty bookkeeping code.
6386     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6387     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6388     //   xori shift, shift1, 24 [16]
6389     //   rlwinm ptr, ptr1, 0, 0, 29
6390     //   slw newval2, newval, shift
6391     //   slw oldval2, oldval,shift
6392     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6393     //   slw mask, mask2, shift
6394     //   and newval3, newval2, mask
6395     //   and oldval3, oldval2, mask
6396     // loop1MBB:
6397     //   lwarx tmpDest, ptr
6398     //   and tmp, tmpDest, mask
6399     //   cmpw tmp, oldval3
6400     //   bne- midMBB
6401     // loop2MBB:
6402     //   andc tmp2, tmpDest, mask
6403     //   or tmp4, tmp2, newval3
6404     //   stwcx. tmp4, ptr
6405     //   bne- loop1MBB
6406     //   b exitBB
6407     // midMBB:
6408     //   stwcx. tmpDest, ptr
6409     // exitBB:
6410     //   srw dest, tmpDest, shift
6411     if (ptrA != ZeroReg) {
6412       Ptr1Reg = RegInfo.createVirtualRegister(RC);
6413       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6414         .addReg(ptrA).addReg(ptrB);
6415     } else {
6416       Ptr1Reg = ptrB;
6417     }
6418     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6419         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6420     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6421         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6422     if (is64bit)
6423       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6424         .addReg(Ptr1Reg).addImm(0).addImm(61);
6425     else
6426       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6427         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6428     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6429         .addReg(newval).addReg(ShiftReg);
6430     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6431         .addReg(oldval).addReg(ShiftReg);
6432     if (is8bit)
6433       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6434     else {
6435       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6436       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6437         .addReg(Mask3Reg).addImm(65535);
6438     }
6439     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6440         .addReg(Mask2Reg).addReg(ShiftReg);
6441     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6442         .addReg(NewVal2Reg).addReg(MaskReg);
6443     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6444         .addReg(OldVal2Reg).addReg(MaskReg);
6445
6446     BB = loop1MBB;
6447     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6448         .addReg(ZeroReg).addReg(PtrReg);
6449     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6450         .addReg(TmpDestReg).addReg(MaskReg);
6451     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6452         .addReg(TmpReg).addReg(OldVal3Reg);
6453     BuildMI(BB, dl, TII->get(PPC::BCC))
6454         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6455     BB->addSuccessor(loop2MBB);
6456     BB->addSuccessor(midMBB);
6457
6458     BB = loop2MBB;
6459     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6460         .addReg(TmpDestReg).addReg(MaskReg);
6461     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6462         .addReg(Tmp2Reg).addReg(NewVal3Reg);
6463     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6464         .addReg(ZeroReg).addReg(PtrReg);
6465     BuildMI(BB, dl, TII->get(PPC::BCC))
6466       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6467     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6468     BB->addSuccessor(loop1MBB);
6469     BB->addSuccessor(exitMBB);
6470
6471     BB = midMBB;
6472     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6473       .addReg(ZeroReg).addReg(PtrReg);
6474     BB->addSuccessor(exitMBB);
6475
6476     //  exitMBB:
6477     //   ...
6478     BB = exitMBB;
6479     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6480       .addReg(ShiftReg);
6481   } else if (MI->getOpcode() == PPC::FADDrtz) {
6482     // This pseudo performs an FADD with rounding mode temporarily forced
6483     // to round-to-zero.  We emit this via custom inserter since the FPSCR
6484     // is not modeled at the SelectionDAG level.
6485     unsigned Dest = MI->getOperand(0).getReg();
6486     unsigned Src1 = MI->getOperand(1).getReg();
6487     unsigned Src2 = MI->getOperand(2).getReg();
6488     DebugLoc dl   = MI->getDebugLoc();
6489
6490     MachineRegisterInfo &RegInfo = F->getRegInfo();
6491     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6492
6493     // Save FPSCR value.
6494     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6495
6496     // Set rounding mode to round-to-zero.
6497     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6498     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6499
6500     // Perform addition.
6501     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6502
6503     // Restore FPSCR value.
6504     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6505   } else {
6506     llvm_unreachable("Unexpected instr type to insert");
6507   }
6508
6509   MI->eraseFromParent();   // The pseudo instruction is gone now.
6510   return BB;
6511 }
6512
6513 //===----------------------------------------------------------------------===//
6514 // Target Optimization Hooks
6515 //===----------------------------------------------------------------------===//
6516
6517 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6518                                              DAGCombinerInfo &DCI) const {
6519   const TargetMachine &TM = getTargetMachine();
6520   SelectionDAG &DAG = DCI.DAG;
6521   DebugLoc dl = N->getDebugLoc();
6522   switch (N->getOpcode()) {
6523   default: break;
6524   case PPCISD::SHL:
6525     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6526       if (C->isNullValue())   // 0 << V -> 0.
6527         return N->getOperand(0);
6528     }
6529     break;
6530   case PPCISD::SRL:
6531     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6532       if (C->isNullValue())   // 0 >>u V -> 0.
6533         return N->getOperand(0);
6534     }
6535     break;
6536   case PPCISD::SRA:
6537     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6538       if (C->isNullValue() ||   //  0 >>s V -> 0.
6539           C->isAllOnesValue())    // -1 >>s V -> -1.
6540         return N->getOperand(0);
6541     }
6542     break;
6543
6544   case ISD::SINT_TO_FP:
6545     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6546       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6547         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6548         // We allow the src/dst to be either f32/f64, but the intermediate
6549         // type must be i64.
6550         if (N->getOperand(0).getValueType() == MVT::i64 &&
6551             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6552           SDValue Val = N->getOperand(0).getOperand(0);
6553           if (Val.getValueType() == MVT::f32) {
6554             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6555             DCI.AddToWorklist(Val.getNode());
6556           }
6557
6558           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6559           DCI.AddToWorklist(Val.getNode());
6560           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6561           DCI.AddToWorklist(Val.getNode());
6562           if (N->getValueType(0) == MVT::f32) {
6563             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6564                               DAG.getIntPtrConstant(0));
6565             DCI.AddToWorklist(Val.getNode());
6566           }
6567           return Val;
6568         } else if (N->getOperand(0).getValueType() == MVT::i32) {
6569           // If the intermediate type is i32, we can avoid the load/store here
6570           // too.
6571         }
6572       }
6573     }
6574     break;
6575   case ISD::STORE:
6576     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6577     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6578         !cast<StoreSDNode>(N)->isTruncatingStore() &&
6579         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6580         N->getOperand(1).getValueType() == MVT::i32 &&
6581         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6582       SDValue Val = N->getOperand(1).getOperand(0);
6583       if (Val.getValueType() == MVT::f32) {
6584         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6585         DCI.AddToWorklist(Val.getNode());
6586       }
6587       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6588       DCI.AddToWorklist(Val.getNode());
6589
6590       Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6591                         N->getOperand(2), N->getOperand(3));
6592       DCI.AddToWorklist(Val.getNode());
6593       return Val;
6594     }
6595
6596     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6597     if (cast<StoreSDNode>(N)->isUnindexed() &&
6598         N->getOperand(1).getOpcode() == ISD::BSWAP &&
6599         N->getOperand(1).getNode()->hasOneUse() &&
6600         (N->getOperand(1).getValueType() == MVT::i32 ||
6601          N->getOperand(1).getValueType() == MVT::i16)) {
6602       SDValue BSwapOp = N->getOperand(1).getOperand(0);
6603       // Do an any-extend to 32-bits if this is a half-word input.
6604       if (BSwapOp.getValueType() == MVT::i16)
6605         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6606
6607       SDValue Ops[] = {
6608         N->getOperand(0), BSwapOp, N->getOperand(2),
6609         DAG.getValueType(N->getOperand(1).getValueType())
6610       };
6611       return
6612         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6613                                 Ops, array_lengthof(Ops),
6614                                 cast<StoreSDNode>(N)->getMemoryVT(),
6615                                 cast<StoreSDNode>(N)->getMemOperand());
6616     }
6617     break;
6618   case ISD::BSWAP:
6619     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6620     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6621         N->getOperand(0).hasOneUse() &&
6622         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6623       SDValue Load = N->getOperand(0);
6624       LoadSDNode *LD = cast<LoadSDNode>(Load);
6625       // Create the byte-swapping load.
6626       SDValue Ops[] = {
6627         LD->getChain(),    // Chain
6628         LD->getBasePtr(),  // Ptr
6629         DAG.getValueType(N->getValueType(0)) // VT
6630       };
6631       SDValue BSLoad =
6632         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6633                                 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6634                                 LD->getMemoryVT(), LD->getMemOperand());
6635
6636       // If this is an i16 load, insert the truncate.
6637       SDValue ResVal = BSLoad;
6638       if (N->getValueType(0) == MVT::i16)
6639         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6640
6641       // First, combine the bswap away.  This makes the value produced by the
6642       // load dead.
6643       DCI.CombineTo(N, ResVal);
6644
6645       // Next, combine the load away, we give it a bogus result value but a real
6646       // chain result.  The result value is dead because the bswap is dead.
6647       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6648
6649       // Return N so it doesn't get rechecked!
6650       return SDValue(N, 0);
6651     }
6652
6653     break;
6654   case PPCISD::VCMP: {
6655     // If a VCMPo node already exists with exactly the same operands as this
6656     // node, use its result instead of this node (VCMPo computes both a CR6 and
6657     // a normal output).
6658     //
6659     if (!N->getOperand(0).hasOneUse() &&
6660         !N->getOperand(1).hasOneUse() &&
6661         !N->getOperand(2).hasOneUse()) {
6662
6663       // Scan all of the users of the LHS, looking for VCMPo's that match.
6664       SDNode *VCMPoNode = 0;
6665
6666       SDNode *LHSN = N->getOperand(0).getNode();
6667       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6668            UI != E; ++UI)
6669         if (UI->getOpcode() == PPCISD::VCMPo &&
6670             UI->getOperand(1) == N->getOperand(1) &&
6671             UI->getOperand(2) == N->getOperand(2) &&
6672             UI->getOperand(0) == N->getOperand(0)) {
6673           VCMPoNode = *UI;
6674           break;
6675         }
6676
6677       // If there is no VCMPo node, or if the flag value has a single use, don't
6678       // transform this.
6679       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6680         break;
6681
6682       // Look at the (necessarily single) use of the flag value.  If it has a
6683       // chain, this transformation is more complex.  Note that multiple things
6684       // could use the value result, which we should ignore.
6685       SDNode *FlagUser = 0;
6686       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6687            FlagUser == 0; ++UI) {
6688         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6689         SDNode *User = *UI;
6690         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6691           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6692             FlagUser = User;
6693             break;
6694           }
6695         }
6696       }
6697
6698       // If the user is a MFCR instruction, we know this is safe.  Otherwise we
6699       // give up for right now.
6700       if (FlagUser->getOpcode() == PPCISD::MFCR)
6701         return SDValue(VCMPoNode, 0);
6702     }
6703     break;
6704   }
6705   case ISD::BR_CC: {
6706     // If this is a branch on an altivec predicate comparison, lower this so
6707     // that we don't have to do a MFCR: instead, branch directly on CR6.  This
6708     // lowering is done pre-legalize, because the legalizer lowers the predicate
6709     // compare down to code that is difficult to reassemble.
6710     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6711     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6712     int CompareOpc;
6713     bool isDot;
6714
6715     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6716         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6717         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6718       assert(isDot && "Can't compare against a vector result!");
6719
6720       // If this is a comparison against something other than 0/1, then we know
6721       // that the condition is never/always true.
6722       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6723       if (Val != 0 && Val != 1) {
6724         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
6725           return N->getOperand(0);
6726         // Always !=, turn it into an unconditional branch.
6727         return DAG.getNode(ISD::BR, dl, MVT::Other,
6728                            N->getOperand(0), N->getOperand(4));
6729       }
6730
6731       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6732
6733       // Create the PPCISD altivec 'dot' comparison node.
6734       SDValue Ops[] = {
6735         LHS.getOperand(2),  // LHS of compare
6736         LHS.getOperand(3),  // RHS of compare
6737         DAG.getConstant(CompareOpc, MVT::i32)
6738       };
6739       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
6740       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6741
6742       // Unpack the result based on how the target uses it.
6743       PPC::Predicate CompOpc;
6744       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6745       default:  // Can't happen, don't crash on invalid number though.
6746       case 0:   // Branch on the value of the EQ bit of CR6.
6747         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6748         break;
6749       case 1:   // Branch on the inverted value of the EQ bit of CR6.
6750         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6751         break;
6752       case 2:   // Branch on the value of the LT bit of CR6.
6753         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6754         break;
6755       case 3:   // Branch on the inverted value of the LT bit of CR6.
6756         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6757         break;
6758       }
6759
6760       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6761                          DAG.getConstant(CompOpc, MVT::i32),
6762                          DAG.getRegister(PPC::CR6, MVT::i32),
6763                          N->getOperand(4), CompNode.getValue(1));
6764     }
6765     break;
6766   }
6767   }
6768
6769   return SDValue();
6770 }
6771
6772 //===----------------------------------------------------------------------===//
6773 // Inline Assembly Support
6774 //===----------------------------------------------------------------------===//
6775
6776 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6777                                                        APInt &KnownZero,
6778                                                        APInt &KnownOne,
6779                                                        const SelectionDAG &DAG,
6780                                                        unsigned Depth) const {
6781   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6782   switch (Op.getOpcode()) {
6783   default: break;
6784   case PPCISD::LBRX: {
6785     // lhbrx is known to have the top bits cleared out.
6786     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6787       KnownZero = 0xFFFF0000;
6788     break;
6789   }
6790   case ISD::INTRINSIC_WO_CHAIN: {
6791     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6792     default: break;
6793     case Intrinsic::ppc_altivec_vcmpbfp_p:
6794     case Intrinsic::ppc_altivec_vcmpeqfp_p:
6795     case Intrinsic::ppc_altivec_vcmpequb_p:
6796     case Intrinsic::ppc_altivec_vcmpequh_p:
6797     case Intrinsic::ppc_altivec_vcmpequw_p:
6798     case Intrinsic::ppc_altivec_vcmpgefp_p:
6799     case Intrinsic::ppc_altivec_vcmpgtfp_p:
6800     case Intrinsic::ppc_altivec_vcmpgtsb_p:
6801     case Intrinsic::ppc_altivec_vcmpgtsh_p:
6802     case Intrinsic::ppc_altivec_vcmpgtsw_p:
6803     case Intrinsic::ppc_altivec_vcmpgtub_p:
6804     case Intrinsic::ppc_altivec_vcmpgtuh_p:
6805     case Intrinsic::ppc_altivec_vcmpgtuw_p:
6806       KnownZero = ~1U;  // All bits but the low one are known to be zero.
6807       break;
6808     }
6809   }
6810   }
6811 }
6812
6813
6814 /// getConstraintType - Given a constraint, return the type of
6815 /// constraint it is for this target.
6816 PPCTargetLowering::ConstraintType
6817 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6818   if (Constraint.size() == 1) {
6819     switch (Constraint[0]) {
6820     default: break;
6821     case 'b':
6822     case 'r':
6823     case 'f':
6824     case 'v':
6825     case 'y':
6826       return C_RegisterClass;
6827     case 'Z':
6828       // FIXME: While Z does indicate a memory constraint, it specifically
6829       // indicates an r+r address (used in conjunction with the 'y' modifier
6830       // in the replacement string). Currently, we're forcing the base
6831       // register to be r0 in the asm printer (which is interpreted as zero)
6832       // and forming the complete address in the second register. This is
6833       // suboptimal.
6834       return C_Memory;
6835     }
6836   }
6837   return TargetLowering::getConstraintType(Constraint);
6838 }
6839
6840 /// Examine constraint type and operand type and determine a weight value.
6841 /// This object must already have been set up with the operand type
6842 /// and the current alternative constraint selected.
6843 TargetLowering::ConstraintWeight
6844 PPCTargetLowering::getSingleConstraintMatchWeight(
6845     AsmOperandInfo &info, const char *constraint) const {
6846   ConstraintWeight weight = CW_Invalid;
6847   Value *CallOperandVal = info.CallOperandVal;
6848     // If we don't have a value, we can't do a match,
6849     // but allow it at the lowest weight.
6850   if (CallOperandVal == NULL)
6851     return CW_Default;
6852   Type *type = CallOperandVal->getType();
6853   // Look at the constraint type.
6854   switch (*constraint) {
6855   default:
6856     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6857     break;
6858   case 'b':
6859     if (type->isIntegerTy())
6860       weight = CW_Register;
6861     break;
6862   case 'f':
6863     if (type->isFloatTy())
6864       weight = CW_Register;
6865     break;
6866   case 'd':
6867     if (type->isDoubleTy())
6868       weight = CW_Register;
6869     break;
6870   case 'v':
6871     if (type->isVectorTy())
6872       weight = CW_Register;
6873     break;
6874   case 'y':
6875     weight = CW_Register;
6876     break;
6877   case 'Z':
6878     weight = CW_Memory;
6879     break;
6880   }
6881   return weight;
6882 }
6883
6884 std::pair<unsigned, const TargetRegisterClass*>
6885 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6886                                                 EVT VT) const {
6887   if (Constraint.size() == 1) {
6888     // GCC RS6000 Constraint Letters
6889     switch (Constraint[0]) {
6890     case 'b':   // R1-R31
6891       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6892         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
6893       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
6894     case 'r':   // R0-R31
6895       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6896         return std::make_pair(0U, &PPC::G8RCRegClass);
6897       return std::make_pair(0U, &PPC::GPRCRegClass);
6898     case 'f':
6899       if (VT == MVT::f32 || VT == MVT::i32)
6900         return std::make_pair(0U, &PPC::F4RCRegClass);
6901       if (VT == MVT::f64 || VT == MVT::i64)
6902         return std::make_pair(0U, &PPC::F8RCRegClass);
6903       break;
6904     case 'v':
6905       return std::make_pair(0U, &PPC::VRRCRegClass);
6906     case 'y':   // crrc
6907       return std::make_pair(0U, &PPC::CRRCRegClass);
6908     }
6909   }
6910
6911   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6912 }
6913
6914
6915 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6916 /// vector.  If it is invalid, don't add anything to Ops.
6917 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6918                                                      std::string &Constraint,
6919                                                      std::vector<SDValue>&Ops,
6920                                                      SelectionDAG &DAG) const {
6921   SDValue Result(0,0);
6922
6923   // Only support length 1 constraints.
6924   if (Constraint.length() > 1) return;
6925
6926   char Letter = Constraint[0];
6927   switch (Letter) {
6928   default: break;
6929   case 'I':
6930   case 'J':
6931   case 'K':
6932   case 'L':
6933   case 'M':
6934   case 'N':
6935   case 'O':
6936   case 'P': {
6937     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6938     if (!CST) return; // Must be an immediate to match.
6939     unsigned Value = CST->getZExtValue();
6940     switch (Letter) {
6941     default: llvm_unreachable("Unknown constraint letter!");
6942     case 'I':  // "I" is a signed 16-bit constant.
6943       if ((short)Value == (int)Value)
6944         Result = DAG.getTargetConstant(Value, Op.getValueType());
6945       break;
6946     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
6947     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
6948       if ((short)Value == 0)
6949         Result = DAG.getTargetConstant(Value, Op.getValueType());
6950       break;
6951     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
6952       if ((Value >> 16) == 0)
6953         Result = DAG.getTargetConstant(Value, Op.getValueType());
6954       break;
6955     case 'M':  // "M" is a constant that is greater than 31.
6956       if (Value > 31)
6957         Result = DAG.getTargetConstant(Value, Op.getValueType());
6958       break;
6959     case 'N':  // "N" is a positive constant that is an exact power of two.
6960       if ((int)Value > 0 && isPowerOf2_32(Value))
6961         Result = DAG.getTargetConstant(Value, Op.getValueType());
6962       break;
6963     case 'O':  // "O" is the constant zero.
6964       if (Value == 0)
6965         Result = DAG.getTargetConstant(Value, Op.getValueType());
6966       break;
6967     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
6968       if ((short)-Value == (int)-Value)
6969         Result = DAG.getTargetConstant(Value, Op.getValueType());
6970       break;
6971     }
6972     break;
6973   }
6974   }
6975
6976   if (Result.getNode()) {
6977     Ops.push_back(Result);
6978     return;
6979   }
6980
6981   // Handle standard constraint letters.
6982   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6983 }
6984
6985 // isLegalAddressingMode - Return true if the addressing mode represented
6986 // by AM is legal for this target, for a load/store of the specified type.
6987 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6988                                               Type *Ty) const {
6989   // FIXME: PPC does not allow r+i addressing modes for vectors!
6990
6991   // PPC allows a sign-extended 16-bit immediate field.
6992   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
6993     return false;
6994
6995   // No global is ever allowed as a base.
6996   if (AM.BaseGV)
6997     return false;
6998
6999   // PPC only support r+r,
7000   switch (AM.Scale) {
7001   case 0:  // "r+i" or just "i", depending on HasBaseReg.
7002     break;
7003   case 1:
7004     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
7005       return false;
7006     // Otherwise we have r+r or r+i.
7007     break;
7008   case 2:
7009     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
7010       return false;
7011     // Allow 2*r as r+r.
7012     break;
7013   default:
7014     // No other scales are supported.
7015     return false;
7016   }
7017
7018   return true;
7019 }
7020
7021 /// isLegalAddressImmediate - Return true if the integer value can be used
7022 /// as the offset of the target addressing mode for load / store of the
7023 /// given type.
7024 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
7025   // PPC allows a sign-extended 16-bit immediate field.
7026   return (V > -(1 << 16) && V < (1 << 16)-1);
7027 }
7028
7029 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
7030   return false;
7031 }
7032
7033 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7034                                            SelectionDAG &DAG) const {
7035   MachineFunction &MF = DAG.getMachineFunction();
7036   MachineFrameInfo *MFI = MF.getFrameInfo();
7037   MFI->setReturnAddressIsTaken(true);
7038
7039   DebugLoc dl = Op.getDebugLoc();
7040   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7041
7042   // Make sure the function does not optimize away the store of the RA to
7043   // the stack.
7044   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7045   FuncInfo->setLRStoreRequired();
7046   bool isPPC64 = PPCSubTarget.isPPC64();
7047   bool isDarwinABI = PPCSubTarget.isDarwinABI();
7048
7049   if (Depth > 0) {
7050     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7051     SDValue Offset =
7052
7053       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7054                       isPPC64? MVT::i64 : MVT::i32);
7055     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7056                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7057                                    FrameAddr, Offset),
7058                        MachinePointerInfo(), false, false, false, 0);
7059   }
7060
7061   // Just load the return address off the stack.
7062   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7063   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7064                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7065 }
7066
7067 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7068                                           SelectionDAG &DAG) const {
7069   DebugLoc dl = Op.getDebugLoc();
7070   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7071
7072   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7073   bool isPPC64 = PtrVT == MVT::i64;
7074
7075   MachineFunction &MF = DAG.getMachineFunction();
7076   MachineFrameInfo *MFI = MF.getFrameInfo();
7077   MFI->setFrameAddressIsTaken(true);
7078
7079   // Naked functions never have a frame pointer, and so we use r1. For all
7080   // other functions, this decision must be delayed until during PEI.
7081   unsigned FrameReg;
7082   if (MF.getFunction()->getAttributes().hasAttribute(
7083         AttributeSet::FunctionIndex, Attribute::Naked))
7084     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7085   else
7086     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7087
7088   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7089                                          PtrVT);
7090   while (Depth--)
7091     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7092                             FrameAddr, MachinePointerInfo(), false, false,
7093                             false, 0);
7094   return FrameAddr;
7095 }
7096
7097 bool
7098 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7099   // The PowerPC target isn't yet aware of offsets.
7100   return false;
7101 }
7102
7103 /// getOptimalMemOpType - Returns the target specific optimal type for load
7104 /// and store operations as a result of memset, memcpy, and memmove
7105 /// lowering. If DstAlign is zero that means it's safe to destination
7106 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7107 /// means there isn't a need to check it against alignment requirement,
7108 /// probably because the source does not need to be loaded. If 'IsMemset' is
7109 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7110 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7111 /// source is constant so it does not need to be loaded.
7112 /// It returns EVT::Other if the type should be determined using generic
7113 /// target-independent logic.
7114 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7115                                            unsigned DstAlign, unsigned SrcAlign,
7116                                            bool IsMemset, bool ZeroMemset,
7117                                            bool MemcpyStrSrc,
7118                                            MachineFunction &MF) const {
7119   if (this->PPCSubTarget.isPPC64()) {
7120     return MVT::i64;
7121   } else {
7122     return MVT::i32;
7123   }
7124 }
7125
7126 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7127                                                       bool *Fast) const {
7128   if (DisablePPCUnaligned)
7129     return false;
7130
7131   // PowerPC supports unaligned memory access for simple non-vector types.
7132   // Although accessing unaligned addresses is not as efficient as accessing
7133   // aligned addresses, it is generally more efficient than manual expansion,
7134   // and generally only traps for software emulation when crossing page
7135   // boundaries.
7136
7137   if (!VT.isSimple())
7138     return false;
7139
7140   if (VT.getSimpleVT().isVector())
7141     return false;
7142
7143   if (VT == MVT::ppcf128)
7144     return false;
7145
7146   if (Fast)
7147     *Fast = true;
7148
7149   return true;
7150 }
7151
7152 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
7153 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
7154 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
7155 /// is expanded to mul + add.
7156 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
7157   if (!VT.isSimple())
7158     return false;
7159
7160   switch (VT.getSimpleVT().SimpleTy) {
7161   case MVT::f32:
7162   case MVT::f64:
7163   case MVT::v4f32:
7164     return true;
7165   default:
7166     break;
7167   }
7168
7169   return false;
7170 }
7171
7172 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7173   if (DisableILPPref)
7174     return TargetLowering::getSchedulingPreference(N);
7175
7176   return Sched::ILP;
7177 }
7178