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