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