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