[PowerPC] Implement the vpopcnt instructions for POWER8
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
59
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61                                      const PPCSubtarget &STI)
62     : TargetLowering(TM), Subtarget(STI) {
63   // Use _setjmp/_longjmp instead of setjmp/longjmp.
64   setUseUnderscoreSetJmp(true);
65   setUseUnderscoreLongJmp(true);
66
67   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68   // arguments are at least 4/8 bytes aligned.
69   bool isPPC64 = Subtarget.isPPC64();
70   setMinStackArgumentAlignment(isPPC64 ? 8:4);
71
72   // Set up the register classes.
73   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76
77   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78   for (MVT VT : MVT::integer_valuetypes()) {
79     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
81   }
82
83   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84
85   // PowerPC has pre-inc load and store's.
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
92   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
96
97   if (Subtarget.useCRBits()) {
98     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
99
100     if (isPPC64 || Subtarget.hasFPCVT()) {
101       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
102       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
103                          isPPC64 ? MVT::i64 : MVT::i32);
104       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
105       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
106                          isPPC64 ? MVT::i64 : MVT::i32);
107     } else {
108       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
109       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
110     }
111
112     // PowerPC does not support direct load / store of condition registers
113     setOperationAction(ISD::LOAD, MVT::i1, Custom);
114     setOperationAction(ISD::STORE, MVT::i1, Custom);
115
116     // FIXME: Remove this once the ANDI glue bug is fixed:
117     if (ANDIGlueBug)
118       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
119
120     for (MVT VT : MVT::integer_valuetypes()) {
121       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
122       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
123       setTruncStoreAction(VT, MVT::i1, Expand);
124     }
125
126     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
127   }
128
129   // This is used in the ppcf128->int sequence.  Note it has different semantics
130   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
131   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
132
133   // We do not currently implement these libm ops for PowerPC.
134   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
135   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
136   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
137   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
138   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
140
141   // PowerPC has no SREM/UREM instructions
142   setOperationAction(ISD::SREM, MVT::i32, Expand);
143   setOperationAction(ISD::UREM, MVT::i32, Expand);
144   setOperationAction(ISD::SREM, MVT::i64, Expand);
145   setOperationAction(ISD::UREM, MVT::i64, Expand);
146
147   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
148   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
149   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
150   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
151   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
152   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
153   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
154   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
155   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
156
157   // We don't support sin/cos/sqrt/fmod/pow
158   setOperationAction(ISD::FSIN , MVT::f64, Expand);
159   setOperationAction(ISD::FCOS , MVT::f64, Expand);
160   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
161   setOperationAction(ISD::FREM , MVT::f64, Expand);
162   setOperationAction(ISD::FPOW , MVT::f64, Expand);
163   setOperationAction(ISD::FMA  , MVT::f64, Legal);
164   setOperationAction(ISD::FSIN , MVT::f32, Expand);
165   setOperationAction(ISD::FCOS , MVT::f32, Expand);
166   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
167   setOperationAction(ISD::FREM , MVT::f32, Expand);
168   setOperationAction(ISD::FPOW , MVT::f32, Expand);
169   setOperationAction(ISD::FMA  , MVT::f32, Legal);
170
171   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
172
173   // If we're enabling GP optimizations, use hardware square root
174   if (!Subtarget.hasFSQRT() &&
175       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
176         Subtarget.hasFRE()))
177     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
178
179   if (!Subtarget.hasFSQRT() &&
180       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
181         Subtarget.hasFRES()))
182     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
183
184   if (Subtarget.hasFCPSGN()) {
185     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
186     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
187   } else {
188     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
189     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
190   }
191
192   if (Subtarget.hasFPRND()) {
193     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
194     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
195     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
196     setOperationAction(ISD::FROUND, MVT::f64, Legal);
197
198     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
199     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
200     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
201     setOperationAction(ISD::FROUND, MVT::f32, Legal);
202   }
203
204   // PowerPC does not have BSWAP, CTPOP or CTTZ
205   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
206   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
207   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
208   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
209   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
213
214   if (Subtarget.hasPOPCNTD()) {
215     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
216     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
217   } else {
218     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
219     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
220   }
221
222   // PowerPC does not have ROTR
223   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
224   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
225
226   if (!Subtarget.useCRBits()) {
227     // PowerPC does not have Select
228     setOperationAction(ISD::SELECT, MVT::i32, Expand);
229     setOperationAction(ISD::SELECT, MVT::i64, Expand);
230     setOperationAction(ISD::SELECT, MVT::f32, Expand);
231     setOperationAction(ISD::SELECT, MVT::f64, Expand);
232   }
233
234   // PowerPC wants to turn select_cc of FP into fsel when possible.
235   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
236   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
237
238   // PowerPC wants to optimize integer setcc a bit
239   if (!Subtarget.useCRBits())
240     setOperationAction(ISD::SETCC, MVT::i32, Custom);
241
242   // PowerPC does not have BRCOND which requires SetCC
243   if (!Subtarget.useCRBits())
244     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
245
246   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
247
248   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
249   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250
251   // PowerPC does not have [U|S]INT_TO_FP
252   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
253   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
254
255   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
256   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
257   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
258   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
259
260   // We cannot sextinreg(i1).  Expand to shifts.
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
262
263   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
264   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
265   // support continuation, user-level threading, and etc.. As a result, no
266   // other SjLj exception interfaces are implemented and please don't build
267   // your own exception handling based on them.
268   // LLVM/Clang supports zero-cost DWARF exception handling.
269   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
270   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
271
272   // We want to legalize GlobalAddress and ConstantPool nodes into the
273   // appropriate instructions to materialize the address.
274   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
275   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
276   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
277   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
278   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
279   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
280   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
281   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
282   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
283   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
284
285   // TRAP is legal.
286   setOperationAction(ISD::TRAP, MVT::Other, Legal);
287
288   // TRAMPOLINE is custom lowered.
289   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
290   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
291
292   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
293   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
294
295   if (Subtarget.isSVR4ABI()) {
296     if (isPPC64) {
297       // VAARG always uses double-word chunks, so promote anything smaller.
298       setOperationAction(ISD::VAARG, MVT::i1, Promote);
299       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
300       setOperationAction(ISD::VAARG, MVT::i8, Promote);
301       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
302       setOperationAction(ISD::VAARG, MVT::i16, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i32, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::Other, Expand);
307     } else {
308       // VAARG is custom lowered with the 32-bit SVR4 ABI.
309       setOperationAction(ISD::VAARG, MVT::Other, Custom);
310       setOperationAction(ISD::VAARG, MVT::i64, Custom);
311     }
312   } else
313     setOperationAction(ISD::VAARG, MVT::Other, Expand);
314
315   if (Subtarget.isSVR4ABI() && !isPPC64)
316     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
317     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
318   else
319     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
320
321   // Use the default implementation.
322   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
323   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
324   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
325   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
326   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
327
328   // We want to custom lower some of our intrinsics.
329   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
330
331   // To handle counter-based loop conditions.
332   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
333
334   // Comparisons that require checking two conditions.
335   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
336   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
337   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
338   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
339   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
347
348   if (Subtarget.has64BitSupport()) {
349     // They also have instructions for converting between i64 and fp.
350     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
351     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
352     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
353     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
354     // This is just the low 32 bits of a (signed) fp->i64 conversion.
355     // We cannot do this with Promote because i64 is not a legal type.
356     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
357
358     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
359       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
360   } else {
361     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
362     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
363   }
364
365   // With the instructions enabled under FPCVT, we can do everything.
366   if (Subtarget.hasFPCVT()) {
367     if (Subtarget.has64BitSupport()) {
368       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
369       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
370       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
371       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
372     }
373
374     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
375     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
376     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
377     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
378   }
379
380   if (Subtarget.use64BitRegs()) {
381     // 64-bit PowerPC implementations can support i64 types directly
382     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
383     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
384     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
385     // 64-bit PowerPC wants to expand i128 shifts itself.
386     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
387     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
388     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
389   } else {
390     // 32-bit PowerPC wants to expand i64 shifts itself.
391     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
392     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
393     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
394   }
395
396   if (Subtarget.hasAltivec()) {
397     // First set operation action for all vector types to expand. Then we
398     // will selectively turn on ones that can be effectively codegen'd.
399     for (MVT VT : MVT::vector_valuetypes()) {
400       // add/sub are legal for all supported vector VT's.
401       setOperationAction(ISD::ADD , VT, Legal);
402       setOperationAction(ISD::SUB , VT, Legal);
403
404       // Vector popcnt instructions introduced in P8
405       if (Subtarget.hasP8Altivec()) 
406         setOperationAction(ISD::CTPOP, VT, Legal);
407       else 
408         setOperationAction(ISD::CTPOP, VT, Expand);
409
410       // We promote all shuffles to v16i8.
411       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
412       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
413
414       // We promote all non-typed operations to v4i32.
415       setOperationAction(ISD::AND   , VT, Promote);
416       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
417       setOperationAction(ISD::OR    , VT, Promote);
418       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
419       setOperationAction(ISD::XOR   , VT, Promote);
420       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
421       setOperationAction(ISD::LOAD  , VT, Promote);
422       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
423       setOperationAction(ISD::SELECT, VT, Promote);
424       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
425       setOperationAction(ISD::STORE, VT, Promote);
426       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
427
428       // No other operations are legal.
429       setOperationAction(ISD::MUL , VT, Expand);
430       setOperationAction(ISD::SDIV, VT, Expand);
431       setOperationAction(ISD::SREM, VT, Expand);
432       setOperationAction(ISD::UDIV, VT, Expand);
433       setOperationAction(ISD::UREM, VT, Expand);
434       setOperationAction(ISD::FDIV, VT, Expand);
435       setOperationAction(ISD::FREM, VT, Expand);
436       setOperationAction(ISD::FNEG, VT, Expand);
437       setOperationAction(ISD::FSQRT, VT, Expand);
438       setOperationAction(ISD::FLOG, VT, Expand);
439       setOperationAction(ISD::FLOG10, VT, Expand);
440       setOperationAction(ISD::FLOG2, VT, Expand);
441       setOperationAction(ISD::FEXP, VT, Expand);
442       setOperationAction(ISD::FEXP2, VT, Expand);
443       setOperationAction(ISD::FSIN, VT, Expand);
444       setOperationAction(ISD::FCOS, VT, Expand);
445       setOperationAction(ISD::FABS, VT, Expand);
446       setOperationAction(ISD::FPOWI, VT, Expand);
447       setOperationAction(ISD::FFLOOR, VT, Expand);
448       setOperationAction(ISD::FCEIL,  VT, Expand);
449       setOperationAction(ISD::FTRUNC, VT, Expand);
450       setOperationAction(ISD::FRINT,  VT, Expand);
451       setOperationAction(ISD::FNEARBYINT, VT, Expand);
452       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
453       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
454       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
455       setOperationAction(ISD::MULHU, VT, Expand);
456       setOperationAction(ISD::MULHS, VT, Expand);
457       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
458       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
459       setOperationAction(ISD::UDIVREM, VT, Expand);
460       setOperationAction(ISD::SDIVREM, VT, Expand);
461       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
462       setOperationAction(ISD::FPOW, VT, Expand);
463       setOperationAction(ISD::BSWAP, VT, Expand);
464       setOperationAction(ISD::CTLZ, VT, Expand);
465       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
466       setOperationAction(ISD::CTTZ, VT, Expand);
467       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
468       setOperationAction(ISD::VSELECT, VT, Expand);
469       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470
471       for (MVT InnerVT : MVT::vector_valuetypes()) {
472         setTruncStoreAction(VT, InnerVT, Expand);
473         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
474         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
475         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
476       }
477     }
478
479     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
480     // with merges, splats, etc.
481     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
482
483     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
484     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
485     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
486     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
487     setOperationAction(ISD::SELECT, MVT::v4i32,
488                        Subtarget.useCRBits() ? Legal : Expand);
489     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
490     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
491     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
492     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
493     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
494     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
495     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
496     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
497     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
498
499     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
500     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
501     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
502     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
503
504     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
505     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
506
507     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
508       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
509       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
510     }
511
512     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
513     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
515
516     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
517     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
518
519     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
520     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
521     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
522     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
523
524     // Altivec does not contain unordered floating-point compare instructions
525     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
526     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
527     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
528     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
529
530     if (Subtarget.hasVSX()) {
531       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
532       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
533
534       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
535       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
536       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
537       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
538       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
539
540       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
541
542       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
543       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
544
545       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
546       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
547
548       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
549       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
550       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
551       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
552       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
553
554       // Share the Altivec comparison restrictions.
555       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
556       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
557       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
558       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
559
560       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
561       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
562
563       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
564
565       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
566
567       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
568       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
569
570       // VSX v2i64 only supports non-arithmetic operations.
571       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
572       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
573
574       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
575       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
576       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
577
578       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
579
580       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
581       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
582       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
583       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
584
585       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
586
587       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
588       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
589       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
590       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
591
592       // Vector operation legalization checks the result type of
593       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
594       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
595       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
596       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
597       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
598
599       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
600     }
601
602     if (Subtarget.hasP8Altivec()) 
603       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
604   }
605
606   if (Subtarget.has64BitSupport())
607     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
608
609   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
610
611   if (!isPPC64) {
612     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
613     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
614   }
615
616   setBooleanContents(ZeroOrOneBooleanContent);
617   // Altivec instructions set fields to all zeros or all ones.
618   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
619
620   if (!isPPC64) {
621     // These libcalls are not available in 32-bit.
622     setLibcallName(RTLIB::SHL_I128, nullptr);
623     setLibcallName(RTLIB::SRL_I128, nullptr);
624     setLibcallName(RTLIB::SRA_I128, nullptr);
625   }
626
627   if (isPPC64) {
628     setStackPointerRegisterToSaveRestore(PPC::X1);
629     setExceptionPointerRegister(PPC::X3);
630     setExceptionSelectorRegister(PPC::X4);
631   } else {
632     setStackPointerRegisterToSaveRestore(PPC::R1);
633     setExceptionPointerRegister(PPC::R3);
634     setExceptionSelectorRegister(PPC::R4);
635   }
636
637   // We have target-specific dag combine patterns for the following nodes:
638   setTargetDAGCombine(ISD::SINT_TO_FP);
639   if (Subtarget.hasFPCVT())
640     setTargetDAGCombine(ISD::UINT_TO_FP);
641   setTargetDAGCombine(ISD::LOAD);
642   setTargetDAGCombine(ISD::STORE);
643   setTargetDAGCombine(ISD::BR_CC);
644   if (Subtarget.useCRBits())
645     setTargetDAGCombine(ISD::BRCOND);
646   setTargetDAGCombine(ISD::BSWAP);
647   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
648   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
649   setTargetDAGCombine(ISD::INTRINSIC_VOID);
650
651   setTargetDAGCombine(ISD::SIGN_EXTEND);
652   setTargetDAGCombine(ISD::ZERO_EXTEND);
653   setTargetDAGCombine(ISD::ANY_EXTEND);
654
655   if (Subtarget.useCRBits()) {
656     setTargetDAGCombine(ISD::TRUNCATE);
657     setTargetDAGCombine(ISD::SETCC);
658     setTargetDAGCombine(ISD::SELECT_CC);
659   }
660
661   // Use reciprocal estimates.
662   if (TM.Options.UnsafeFPMath) {
663     setTargetDAGCombine(ISD::FDIV);
664     setTargetDAGCombine(ISD::FSQRT);
665   }
666
667   // Darwin long double math library functions have $LDBL128 appended.
668   if (Subtarget.isDarwin()) {
669     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
670     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
671     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
672     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
673     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
674     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
675     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
676     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
677     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
678     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
679   }
680
681   // With 32 condition bits, we don't need to sink (and duplicate) compares
682   // aggressively in CodeGenPrep.
683   if (Subtarget.useCRBits())
684     setHasMultipleConditionRegisters();
685
686   setMinFunctionAlignment(2);
687   if (Subtarget.isDarwin())
688     setPrefFunctionAlignment(4);
689
690   switch (Subtarget.getDarwinDirective()) {
691   default: break;
692   case PPC::DIR_970:
693   case PPC::DIR_A2:
694   case PPC::DIR_E500mc:
695   case PPC::DIR_E5500:
696   case PPC::DIR_PWR4:
697   case PPC::DIR_PWR5:
698   case PPC::DIR_PWR5X:
699   case PPC::DIR_PWR6:
700   case PPC::DIR_PWR6X:
701   case PPC::DIR_PWR7:
702   case PPC::DIR_PWR8:
703     setPrefFunctionAlignment(4);
704     setPrefLoopAlignment(4);
705     break;
706   }
707
708   setInsertFencesForAtomic(true);
709
710   if (Subtarget.enableMachineScheduler())
711     setSchedulingPreference(Sched::Source);
712   else
713     setSchedulingPreference(Sched::Hybrid);
714
715   computeRegisterProperties();
716
717   // The Freescale cores do better with aggressive inlining of memcpy and
718   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
719   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
720       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
721     MaxStoresPerMemset = 32;
722     MaxStoresPerMemsetOptSize = 16;
723     MaxStoresPerMemcpy = 32;
724     MaxStoresPerMemcpyOptSize = 8;
725     MaxStoresPerMemmove = 32;
726     MaxStoresPerMemmoveOptSize = 8;
727   }
728 }
729
730 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
731 /// the desired ByVal argument alignment.
732 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
733                              unsigned MaxMaxAlign) {
734   if (MaxAlign == MaxMaxAlign)
735     return;
736   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
737     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
738       MaxAlign = 32;
739     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
740       MaxAlign = 16;
741   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
742     unsigned EltAlign = 0;
743     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
744     if (EltAlign > MaxAlign)
745       MaxAlign = EltAlign;
746   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
747     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
748       unsigned EltAlign = 0;
749       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
750       if (EltAlign > MaxAlign)
751         MaxAlign = EltAlign;
752       if (MaxAlign == MaxMaxAlign)
753         break;
754     }
755   }
756 }
757
758 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
759 /// function arguments in the caller parameter area.
760 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
761   // Darwin passes everything on 4 byte boundary.
762   if (Subtarget.isDarwin())
763     return 4;
764
765   // 16byte and wider vectors are passed on 16byte boundary.
766   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
767   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
768   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
769     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
770   return Align;
771 }
772
773 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
774   switch (Opcode) {
775   default: return nullptr;
776   case PPCISD::FSEL:            return "PPCISD::FSEL";
777   case PPCISD::FCFID:           return "PPCISD::FCFID";
778   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
779   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
780   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
781   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
782   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
783   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
784   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
785   case PPCISD::FRE:             return "PPCISD::FRE";
786   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
787   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
788   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
789   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
790   case PPCISD::VPERM:           return "PPCISD::VPERM";
791   case PPCISD::CMPB:            return "PPCISD::CMPB";
792   case PPCISD::Hi:              return "PPCISD::Hi";
793   case PPCISD::Lo:              return "PPCISD::Lo";
794   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
795   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
796   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
797   case PPCISD::SRL:             return "PPCISD::SRL";
798   case PPCISD::SRA:             return "PPCISD::SRA";
799   case PPCISD::SHL:             return "PPCISD::SHL";
800   case PPCISD::CALL:            return "PPCISD::CALL";
801   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
802   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
803   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
804   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
805   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
806   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
807   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
808   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
809   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
810   case PPCISD::VCMP:            return "PPCISD::VCMP";
811   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
812   case PPCISD::LBRX:            return "PPCISD::LBRX";
813   case PPCISD::STBRX:           return "PPCISD::STBRX";
814   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
815   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
816   case PPCISD::LARX:            return "PPCISD::LARX";
817   case PPCISD::STCX:            return "PPCISD::STCX";
818   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
819   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
820   case PPCISD::BDZ:             return "PPCISD::BDZ";
821   case PPCISD::MFFS:            return "PPCISD::MFFS";
822   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
823   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
824   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
825   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
826   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
827   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
828   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
829   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
830   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
831   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
832   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
833   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
834   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
835   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
836   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
837   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
838   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
839   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
840   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
841   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
842   case PPCISD::SC:              return "PPCISD::SC";
843   }
844 }
845
846 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
847   if (!VT.isVector())
848     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
849   return VT.changeVectorElementTypeToInteger();
850 }
851
852 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
853   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
854   return true;
855 }
856
857 //===----------------------------------------------------------------------===//
858 // Node matching predicates, for use by the tblgen matching code.
859 //===----------------------------------------------------------------------===//
860
861 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
862 static bool isFloatingPointZero(SDValue Op) {
863   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
864     return CFP->getValueAPF().isZero();
865   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
866     // Maybe this has already been legalized into the constant pool?
867     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
868       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
869         return CFP->getValueAPF().isZero();
870   }
871   return false;
872 }
873
874 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
875 /// true if Op is undef or if it matches the specified value.
876 static bool isConstantOrUndef(int Op, int Val) {
877   return Op < 0 || Op == Val;
878 }
879
880 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
881 /// VPKUHUM instruction.
882 /// The ShuffleKind distinguishes between big-endian operations with
883 /// two different inputs (0), either-endian operations with two identical
884 /// inputs (1), and little-endian operantion with two different inputs (2).
885 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
886 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
887                                SelectionDAG &DAG) {
888   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
889   if (ShuffleKind == 0) {
890     if (IsLE)
891       return false;
892     for (unsigned i = 0; i != 16; ++i)
893       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
894         return false;
895   } else if (ShuffleKind == 2) {
896     if (!IsLE)
897       return false;
898     for (unsigned i = 0; i != 16; ++i)
899       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
900         return false;
901   } else if (ShuffleKind == 1) {
902     unsigned j = IsLE ? 0 : 1;
903     for (unsigned i = 0; i != 8; ++i)
904       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
905           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
906         return false;
907   }
908   return true;
909 }
910
911 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
912 /// VPKUWUM instruction.
913 /// The ShuffleKind distinguishes between big-endian operations with
914 /// two different inputs (0), either-endian operations with two identical
915 /// inputs (1), and little-endian operantion with two different inputs (2).
916 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
917 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
918                                SelectionDAG &DAG) {
919   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
920   if (ShuffleKind == 0) {
921     if (IsLE)
922       return false;
923     for (unsigned i = 0; i != 16; i += 2)
924       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
925           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
926         return false;
927   } else if (ShuffleKind == 2) {
928     if (!IsLE)
929       return false;
930     for (unsigned i = 0; i != 16; i += 2)
931       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
932           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
933         return false;
934   } else if (ShuffleKind == 1) {
935     unsigned j = IsLE ? 0 : 2;
936     for (unsigned i = 0; i != 8; i += 2)
937       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
938           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
939           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
940           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
941         return false;
942   }
943   return true;
944 }
945
946 /// isVMerge - Common function, used to match vmrg* shuffles.
947 ///
948 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
949                      unsigned LHSStart, unsigned RHSStart) {
950   if (N->getValueType(0) != MVT::v16i8)
951     return false;
952   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
953          "Unsupported merge size!");
954
955   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
956     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
957       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
958                              LHSStart+j+i*UnitSize) ||
959           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
960                              RHSStart+j+i*UnitSize))
961         return false;
962     }
963   return true;
964 }
965
966 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
967 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
968 /// The ShuffleKind distinguishes between big-endian merges with two 
969 /// different inputs (0), either-endian merges with two identical inputs (1),
970 /// and little-endian merges with two different inputs (2).  For the latter,
971 /// the input operands are swapped (see PPCInstrAltivec.td).
972 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
973                              unsigned ShuffleKind, SelectionDAG &DAG) {
974   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
975     if (ShuffleKind == 1) // unary
976       return isVMerge(N, UnitSize, 0, 0);
977     else if (ShuffleKind == 2) // swapped
978       return isVMerge(N, UnitSize, 0, 16);
979     else
980       return false;
981   } else {
982     if (ShuffleKind == 1) // unary
983       return isVMerge(N, UnitSize, 8, 8);
984     else if (ShuffleKind == 0) // normal
985       return isVMerge(N, UnitSize, 8, 24);
986     else
987       return false;
988   }
989 }
990
991 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
992 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
993 /// The ShuffleKind distinguishes between big-endian merges with two 
994 /// different inputs (0), either-endian merges with two identical inputs (1),
995 /// and little-endian merges with two different inputs (2).  For the latter,
996 /// the input operands are swapped (see PPCInstrAltivec.td).
997 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
998                              unsigned ShuffleKind, SelectionDAG &DAG) {
999   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1000     if (ShuffleKind == 1) // unary
1001       return isVMerge(N, UnitSize, 8, 8);
1002     else if (ShuffleKind == 2) // swapped
1003       return isVMerge(N, UnitSize, 8, 24);
1004     else
1005       return false;
1006   } else {
1007     if (ShuffleKind == 1) // unary
1008       return isVMerge(N, UnitSize, 0, 0);
1009     else if (ShuffleKind == 0) // normal
1010       return isVMerge(N, UnitSize, 0, 16);
1011     else
1012       return false;
1013   }
1014 }
1015
1016
1017 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1018 /// amount, otherwise return -1.
1019 /// The ShuffleKind distinguishes between big-endian operations with two 
1020 /// different inputs (0), either-endian operations with two identical inputs
1021 /// (1), and little-endian operations with two different inputs (2).  For the
1022 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1023 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1024                              SelectionDAG &DAG) {
1025   if (N->getValueType(0) != MVT::v16i8)
1026     return -1;
1027
1028   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1029
1030   // Find the first non-undef value in the shuffle mask.
1031   unsigned i;
1032   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1033     /*search*/;
1034
1035   if (i == 16) return -1;  // all undef.
1036
1037   // Otherwise, check to see if the rest of the elements are consecutively
1038   // numbered from this value.
1039   unsigned ShiftAmt = SVOp->getMaskElt(i);
1040   if (ShiftAmt < i) return -1;
1041
1042   ShiftAmt -= i;
1043   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1044
1045   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1046     // Check the rest of the elements to see if they are consecutive.
1047     for (++i; i != 16; ++i)
1048       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1049         return -1;
1050   } else if (ShuffleKind == 1) {
1051     // Check the rest of the elements to see if they are consecutive.
1052     for (++i; i != 16; ++i)
1053       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1054         return -1;
1055   } else
1056     return -1;
1057
1058   if (ShuffleKind == 2 && isLE)
1059     ShiftAmt = 16 - ShiftAmt;
1060
1061   return ShiftAmt;
1062 }
1063
1064 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1065 /// specifies a splat of a single element that is suitable for input to
1066 /// VSPLTB/VSPLTH/VSPLTW.
1067 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1068   assert(N->getValueType(0) == MVT::v16i8 &&
1069          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1070
1071   // This is a splat operation if each element of the permute is the same, and
1072   // if the value doesn't reference the second vector.
1073   unsigned ElementBase = N->getMaskElt(0);
1074
1075   // FIXME: Handle UNDEF elements too!
1076   if (ElementBase >= 16)
1077     return false;
1078
1079   // Check that the indices are consecutive, in the case of a multi-byte element
1080   // splatted with a v16i8 mask.
1081   for (unsigned i = 1; i != EltSize; ++i)
1082     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1083       return false;
1084
1085   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1086     if (N->getMaskElt(i) < 0) continue;
1087     for (unsigned j = 0; j != EltSize; ++j)
1088       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1089         return false;
1090   }
1091   return true;
1092 }
1093
1094 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1095 /// are -0.0.
1096 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1097   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1098
1099   APInt APVal, APUndef;
1100   unsigned BitSize;
1101   bool HasAnyUndefs;
1102
1103   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1104     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1105       return CFP->getValueAPF().isNegZero();
1106
1107   return false;
1108 }
1109
1110 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1111 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1112 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1113                                 SelectionDAG &DAG) {
1114   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1115   assert(isSplatShuffleMask(SVOp, EltSize));
1116   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1117     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1118   else
1119     return SVOp->getMaskElt(0) / EltSize;
1120 }
1121
1122 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1123 /// by using a vspltis[bhw] instruction of the specified element size, return
1124 /// the constant being splatted.  The ByteSize field indicates the number of
1125 /// bytes of each element [124] -> [bhw].
1126 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1127   SDValue OpVal(nullptr, 0);
1128
1129   // If ByteSize of the splat is bigger than the element size of the
1130   // build_vector, then we have a case where we are checking for a splat where
1131   // multiple elements of the buildvector are folded together into a single
1132   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1133   unsigned EltSize = 16/N->getNumOperands();
1134   if (EltSize < ByteSize) {
1135     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1136     SDValue UniquedVals[4];
1137     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1138
1139     // See if all of the elements in the buildvector agree across.
1140     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1141       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1142       // If the element isn't a constant, bail fully out.
1143       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1144
1145
1146       if (!UniquedVals[i&(Multiple-1)].getNode())
1147         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1148       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1149         return SDValue();  // no match.
1150     }
1151
1152     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1153     // either constant or undef values that are identical for each chunk.  See
1154     // if these chunks can form into a larger vspltis*.
1155
1156     // Check to see if all of the leading entries are either 0 or -1.  If
1157     // neither, then this won't fit into the immediate field.
1158     bool LeadingZero = true;
1159     bool LeadingOnes = true;
1160     for (unsigned i = 0; i != Multiple-1; ++i) {
1161       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1162
1163       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1164       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1165     }
1166     // Finally, check the least significant entry.
1167     if (LeadingZero) {
1168       if (!UniquedVals[Multiple-1].getNode())
1169         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1170       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1171       if (Val < 16)
1172         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1173     }
1174     if (LeadingOnes) {
1175       if (!UniquedVals[Multiple-1].getNode())
1176         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1177       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1178       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1179         return DAG.getTargetConstant(Val, MVT::i32);
1180     }
1181
1182     return SDValue();
1183   }
1184
1185   // Check to see if this buildvec has a single non-undef value in its elements.
1186   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1187     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1188     if (!OpVal.getNode())
1189       OpVal = N->getOperand(i);
1190     else if (OpVal != N->getOperand(i))
1191       return SDValue();
1192   }
1193
1194   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1195
1196   unsigned ValSizeInBytes = EltSize;
1197   uint64_t Value = 0;
1198   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1199     Value = CN->getZExtValue();
1200   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1201     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1202     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1203   }
1204
1205   // If the splat value is larger than the element value, then we can never do
1206   // this splat.  The only case that we could fit the replicated bits into our
1207   // immediate field for would be zero, and we prefer to use vxor for it.
1208   if (ValSizeInBytes < ByteSize) return SDValue();
1209
1210   // If the element value is larger than the splat value, cut it in half and
1211   // check to see if the two halves are equal.  Continue doing this until we
1212   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1213   while (ValSizeInBytes > ByteSize) {
1214     ValSizeInBytes >>= 1;
1215
1216     // If the top half equals the bottom half, we're still ok.
1217     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1218          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1219       return SDValue();
1220   }
1221
1222   // Properly sign extend the value.
1223   int MaskVal = SignExtend32(Value, ByteSize * 8);
1224
1225   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1226   if (MaskVal == 0) return SDValue();
1227
1228   // Finally, if this value fits in a 5 bit sext field, return it
1229   if (SignExtend32<5>(MaskVal) == MaskVal)
1230     return DAG.getTargetConstant(MaskVal, MVT::i32);
1231   return SDValue();
1232 }
1233
1234 //===----------------------------------------------------------------------===//
1235 //  Addressing Mode Selection
1236 //===----------------------------------------------------------------------===//
1237
1238 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1239 /// or 64-bit immediate, and if the value can be accurately represented as a
1240 /// sign extension from a 16-bit value.  If so, this returns true and the
1241 /// immediate.
1242 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1243   if (!isa<ConstantSDNode>(N))
1244     return false;
1245
1246   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1247   if (N->getValueType(0) == MVT::i32)
1248     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1249   else
1250     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1251 }
1252 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1253   return isIntS16Immediate(Op.getNode(), Imm);
1254 }
1255
1256
1257 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1258 /// can be represented as an indexed [r+r] operation.  Returns false if it
1259 /// can be more efficiently represented with [r+imm].
1260 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1261                                             SDValue &Index,
1262                                             SelectionDAG &DAG) const {
1263   short imm = 0;
1264   if (N.getOpcode() == ISD::ADD) {
1265     if (isIntS16Immediate(N.getOperand(1), imm))
1266       return false;    // r+i
1267     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1268       return false;    // r+i
1269
1270     Base = N.getOperand(0);
1271     Index = N.getOperand(1);
1272     return true;
1273   } else if (N.getOpcode() == ISD::OR) {
1274     if (isIntS16Immediate(N.getOperand(1), imm))
1275       return false;    // r+i can fold it if we can.
1276
1277     // If this is an or of disjoint bitfields, we can codegen this as an add
1278     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1279     // disjoint.
1280     APInt LHSKnownZero, LHSKnownOne;
1281     APInt RHSKnownZero, RHSKnownOne;
1282     DAG.computeKnownBits(N.getOperand(0),
1283                          LHSKnownZero, LHSKnownOne);
1284
1285     if (LHSKnownZero.getBoolValue()) {
1286       DAG.computeKnownBits(N.getOperand(1),
1287                            RHSKnownZero, RHSKnownOne);
1288       // If all of the bits are known zero on the LHS or RHS, the add won't
1289       // carry.
1290       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1291         Base = N.getOperand(0);
1292         Index = N.getOperand(1);
1293         return true;
1294       }
1295     }
1296   }
1297
1298   return false;
1299 }
1300
1301 // If we happen to be doing an i64 load or store into a stack slot that has
1302 // less than a 4-byte alignment, then the frame-index elimination may need to
1303 // use an indexed load or store instruction (because the offset may not be a
1304 // multiple of 4). The extra register needed to hold the offset comes from the
1305 // register scavenger, and it is possible that the scavenger will need to use
1306 // an emergency spill slot. As a result, we need to make sure that a spill slot
1307 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1308 // stack slot.
1309 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1310   // FIXME: This does not handle the LWA case.
1311   if (VT != MVT::i64)
1312     return;
1313
1314   // NOTE: We'll exclude negative FIs here, which come from argument
1315   // lowering, because there are no known test cases triggering this problem
1316   // using packed structures (or similar). We can remove this exclusion if
1317   // we find such a test case. The reason why this is so test-case driven is
1318   // because this entire 'fixup' is only to prevent crashes (from the
1319   // register scavenger) on not-really-valid inputs. For example, if we have:
1320   //   %a = alloca i1
1321   //   %b = bitcast i1* %a to i64*
1322   //   store i64* a, i64 b
1323   // then the store should really be marked as 'align 1', but is not. If it
1324   // were marked as 'align 1' then the indexed form would have been
1325   // instruction-selected initially, and the problem this 'fixup' is preventing
1326   // won't happen regardless.
1327   if (FrameIdx < 0)
1328     return;
1329
1330   MachineFunction &MF = DAG.getMachineFunction();
1331   MachineFrameInfo *MFI = MF.getFrameInfo();
1332
1333   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1334   if (Align >= 4)
1335     return;
1336
1337   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1338   FuncInfo->setHasNonRISpills();
1339 }
1340
1341 /// Returns true if the address N can be represented by a base register plus
1342 /// a signed 16-bit displacement [r+imm], and if it is not better
1343 /// represented as reg+reg.  If Aligned is true, only accept displacements
1344 /// suitable for STD and friends, i.e. multiples of 4.
1345 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1346                                             SDValue &Base,
1347                                             SelectionDAG &DAG,
1348                                             bool Aligned) const {
1349   // FIXME dl should come from parent load or store, not from address
1350   SDLoc dl(N);
1351   // If this can be more profitably realized as r+r, fail.
1352   if (SelectAddressRegReg(N, Disp, Base, DAG))
1353     return false;
1354
1355   if (N.getOpcode() == ISD::ADD) {
1356     short imm = 0;
1357     if (isIntS16Immediate(N.getOperand(1), imm) &&
1358         (!Aligned || (imm & 3) == 0)) {
1359       Disp = DAG.getTargetConstant(imm, N.getValueType());
1360       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1361         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1362         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1363       } else {
1364         Base = N.getOperand(0);
1365       }
1366       return true; // [r+i]
1367     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1368       // Match LOAD (ADD (X, Lo(G))).
1369       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1370              && "Cannot handle constant offsets yet!");
1371       Disp = N.getOperand(1).getOperand(0);  // The global address.
1372       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1373              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1374              Disp.getOpcode() == ISD::TargetConstantPool ||
1375              Disp.getOpcode() == ISD::TargetJumpTable);
1376       Base = N.getOperand(0);
1377       return true;  // [&g+r]
1378     }
1379   } else if (N.getOpcode() == ISD::OR) {
1380     short imm = 0;
1381     if (isIntS16Immediate(N.getOperand(1), imm) &&
1382         (!Aligned || (imm & 3) == 0)) {
1383       // If this is an or of disjoint bitfields, we can codegen this as an add
1384       // (for better address arithmetic) if the LHS and RHS of the OR are
1385       // provably disjoint.
1386       APInt LHSKnownZero, LHSKnownOne;
1387       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1388
1389       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1390         // If all of the bits are known zero on the LHS or RHS, the add won't
1391         // carry.
1392         if (FrameIndexSDNode *FI =
1393               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1394           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1395           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1396         } else {
1397           Base = N.getOperand(0);
1398         }
1399         Disp = DAG.getTargetConstant(imm, N.getValueType());
1400         return true;
1401       }
1402     }
1403   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1404     // Loading from a constant address.
1405
1406     // If this address fits entirely in a 16-bit sext immediate field, codegen
1407     // this as "d, 0"
1408     short Imm;
1409     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1410       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1411       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1412                              CN->getValueType(0));
1413       return true;
1414     }
1415
1416     // Handle 32-bit sext immediates with LIS + addr mode.
1417     if ((CN->getValueType(0) == MVT::i32 ||
1418          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1419         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1420       int Addr = (int)CN->getZExtValue();
1421
1422       // Otherwise, break this down into an LIS + disp.
1423       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1424
1425       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1426       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1427       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1428       return true;
1429     }
1430   }
1431
1432   Disp = DAG.getTargetConstant(0, getPointerTy());
1433   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1434     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1435     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1436   } else
1437     Base = N;
1438   return true;      // [r+0]
1439 }
1440
1441 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1442 /// represented as an indexed [r+r] operation.
1443 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1444                                                 SDValue &Index,
1445                                                 SelectionDAG &DAG) const {
1446   // Check to see if we can easily represent this as an [r+r] address.  This
1447   // will fail if it thinks that the address is more profitably represented as
1448   // reg+imm, e.g. where imm = 0.
1449   if (SelectAddressRegReg(N, Base, Index, DAG))
1450     return true;
1451
1452   // If the operand is an addition, always emit this as [r+r], since this is
1453   // better (for code size, and execution, as the memop does the add for free)
1454   // than emitting an explicit add.
1455   if (N.getOpcode() == ISD::ADD) {
1456     Base = N.getOperand(0);
1457     Index = N.getOperand(1);
1458     return true;
1459   }
1460
1461   // Otherwise, do it the hard way, using R0 as the base register.
1462   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1463                          N.getValueType());
1464   Index = N;
1465   return true;
1466 }
1467
1468 /// getPreIndexedAddressParts - returns true by value, base pointer and
1469 /// offset pointer and addressing mode by reference if the node's address
1470 /// can be legally represented as pre-indexed load / store address.
1471 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1472                                                   SDValue &Offset,
1473                                                   ISD::MemIndexedMode &AM,
1474                                                   SelectionDAG &DAG) const {
1475   if (DisablePPCPreinc) return false;
1476
1477   bool isLoad = true;
1478   SDValue Ptr;
1479   EVT VT;
1480   unsigned Alignment;
1481   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1482     Ptr = LD->getBasePtr();
1483     VT = LD->getMemoryVT();
1484     Alignment = LD->getAlignment();
1485   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1486     Ptr = ST->getBasePtr();
1487     VT  = ST->getMemoryVT();
1488     Alignment = ST->getAlignment();
1489     isLoad = false;
1490   } else
1491     return false;
1492
1493   // PowerPC doesn't have preinc load/store instructions for vectors.
1494   if (VT.isVector())
1495     return false;
1496
1497   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1498
1499     // Common code will reject creating a pre-inc form if the base pointer
1500     // is a frame index, or if N is a store and the base pointer is either
1501     // the same as or a predecessor of the value being stored.  Check for
1502     // those situations here, and try with swapped Base/Offset instead.
1503     bool Swap = false;
1504
1505     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1506       Swap = true;
1507     else if (!isLoad) {
1508       SDValue Val = cast<StoreSDNode>(N)->getValue();
1509       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1510         Swap = true;
1511     }
1512
1513     if (Swap)
1514       std::swap(Base, Offset);
1515
1516     AM = ISD::PRE_INC;
1517     return true;
1518   }
1519
1520   // LDU/STU can only handle immediates that are a multiple of 4.
1521   if (VT != MVT::i64) {
1522     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1523       return false;
1524   } else {
1525     // LDU/STU need an address with at least 4-byte alignment.
1526     if (Alignment < 4)
1527       return false;
1528
1529     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1530       return false;
1531   }
1532
1533   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1534     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1535     // sext i32 to i64 when addr mode is r+i.
1536     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1537         LD->getExtensionType() == ISD::SEXTLOAD &&
1538         isa<ConstantSDNode>(Offset))
1539       return false;
1540   }
1541
1542   AM = ISD::PRE_INC;
1543   return true;
1544 }
1545
1546 //===----------------------------------------------------------------------===//
1547 //  LowerOperation implementation
1548 //===----------------------------------------------------------------------===//
1549
1550 /// GetLabelAccessInfo - Return true if we should reference labels using a
1551 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1552 static bool GetLabelAccessInfo(const TargetMachine &TM,
1553                                const PPCSubtarget &Subtarget,
1554                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1555                                const GlobalValue *GV = nullptr) {
1556   HiOpFlags = PPCII::MO_HA;
1557   LoOpFlags = PPCII::MO_LO;
1558
1559   // Don't use the pic base if not in PIC relocation model.
1560   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1561
1562   if (isPIC) {
1563     HiOpFlags |= PPCII::MO_PIC_FLAG;
1564     LoOpFlags |= PPCII::MO_PIC_FLAG;
1565   }
1566
1567   // If this is a reference to a global value that requires a non-lazy-ptr, make
1568   // sure that instruction lowering adds it.
1569   if (GV && Subtarget.hasLazyResolverStub(GV, TM)) {
1570     HiOpFlags |= PPCII::MO_NLP_FLAG;
1571     LoOpFlags |= PPCII::MO_NLP_FLAG;
1572
1573     if (GV->hasHiddenVisibility()) {
1574       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1575       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1576     }
1577   }
1578
1579   return isPIC;
1580 }
1581
1582 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1583                              SelectionDAG &DAG) {
1584   EVT PtrVT = HiPart.getValueType();
1585   SDValue Zero = DAG.getConstant(0, PtrVT);
1586   SDLoc DL(HiPart);
1587
1588   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1589   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1590
1591   // With PIC, the first instruction is actually "GR+hi(&G)".
1592   if (isPIC)
1593     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1594                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1595
1596   // Generate non-pic code that has direct accesses to the constant pool.
1597   // The address of the global is just (hi(&g)+lo(&g)).
1598   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1599 }
1600
1601 static void setUsesTOCBasePtr(MachineFunction &MF) {
1602   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1603   FuncInfo->setUsesTOCBasePtr();
1604 }
1605
1606 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1607   setUsesTOCBasePtr(DAG.getMachineFunction());
1608 }
1609
1610 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1611                                              SelectionDAG &DAG) const {
1612   EVT PtrVT = Op.getValueType();
1613   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1614   const Constant *C = CP->getConstVal();
1615
1616   // 64-bit SVR4 ABI code is always position-independent.
1617   // The actual address of the GlobalValue is stored in the TOC.
1618   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1619     setUsesTOCBasePtr(DAG);
1620     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1621     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1622                        DAG.getRegister(PPC::X2, MVT::i64));
1623   }
1624
1625   unsigned MOHiFlag, MOLoFlag;
1626   bool isPIC =
1627       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1628
1629   if (isPIC && Subtarget.isSVR4ABI()) {
1630     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1631                                            PPCII::MO_PIC_FLAG);
1632     SDLoc DL(CP);
1633     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1634                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1635   }
1636
1637   SDValue CPIHi =
1638     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1639   SDValue CPILo =
1640     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1641   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1642 }
1643
1644 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1645   EVT PtrVT = Op.getValueType();
1646   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1647
1648   // 64-bit SVR4 ABI code is always position-independent.
1649   // The actual address of the GlobalValue is stored in the TOC.
1650   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1651     setUsesTOCBasePtr(DAG);
1652     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1653     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1654                        DAG.getRegister(PPC::X2, MVT::i64));
1655   }
1656
1657   unsigned MOHiFlag, MOLoFlag;
1658   bool isPIC =
1659       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1660
1661   if (isPIC && Subtarget.isSVR4ABI()) {
1662     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1663                                         PPCII::MO_PIC_FLAG);
1664     SDLoc DL(GA);
1665     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1666                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1667   }
1668
1669   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1670   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1671   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1672 }
1673
1674 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1675                                              SelectionDAG &DAG) const {
1676   EVT PtrVT = Op.getValueType();
1677   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1678   const BlockAddress *BA = BASDN->getBlockAddress();
1679
1680   // 64-bit SVR4 ABI code is always position-independent.
1681   // The actual BlockAddress is stored in the TOC.
1682   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1683     setUsesTOCBasePtr(DAG);
1684     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1685     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1686                        DAG.getRegister(PPC::X2, MVT::i64));
1687   }
1688
1689   unsigned MOHiFlag, MOLoFlag;
1690   bool isPIC =
1691       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1692   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1693   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1694   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1695 }
1696
1697 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1698                                               SelectionDAG &DAG) const {
1699
1700   // FIXME: TLS addresses currently use medium model code sequences,
1701   // which is the most useful form.  Eventually support for small and
1702   // large models could be added if users need it, at the cost of
1703   // additional complexity.
1704   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1705   SDLoc dl(GA);
1706   const GlobalValue *GV = GA->getGlobal();
1707   EVT PtrVT = getPointerTy();
1708   bool is64bit = Subtarget.isPPC64();
1709   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1710   PICLevel::Level picLevel = M->getPICLevel();
1711
1712   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1713
1714   if (Model == TLSModel::LocalExec) {
1715     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1716                                                PPCII::MO_TPREL_HA);
1717     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1718                                                PPCII::MO_TPREL_LO);
1719     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1720                                      is64bit ? MVT::i64 : MVT::i32);
1721     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1722     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1723   }
1724
1725   if (Model == TLSModel::InitialExec) {
1726     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1727     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1728                                                 PPCII::MO_TLS);
1729     SDValue GOTPtr;
1730     if (is64bit) {
1731       setUsesTOCBasePtr(DAG);
1732       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1733       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1734                            PtrVT, GOTReg, TGA);
1735     } else
1736       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1737     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1738                                    PtrVT, TGA, GOTPtr);
1739     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1740   }
1741
1742   if (Model == TLSModel::GeneralDynamic) {
1743     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1744     SDValue GOTPtr;
1745     if (is64bit) {
1746       setUsesTOCBasePtr(DAG);
1747       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1748       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1749                                    GOTReg, TGA);
1750     } else {
1751       if (picLevel == PICLevel::Small)
1752         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1753       else
1754         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1755     }
1756     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl,
1757                                    PtrVT, GOTPtr, TGA);
1758     return DAG.getNode(PPCISD::GET_TLS_ADDR, dl, PtrVT, GOTEntry, TGA);
1759   }
1760
1761   if (Model == TLSModel::LocalDynamic) {
1762     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1763     SDValue GOTPtr;
1764     if (is64bit) {
1765       setUsesTOCBasePtr(DAG);
1766       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1767       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1768                            GOTReg, TGA);
1769     } else {
1770       if (picLevel == PICLevel::Small)
1771         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1772       else
1773         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1774     }
1775     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1776                                    GOTPtr, TGA);
1777     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1778                                   PtrVT, GOTEntry, TGA);
1779     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
1780                                       PtrVT, TLSAddr, TGA);
1781     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1782   }
1783
1784   llvm_unreachable("Unknown TLS model!");
1785 }
1786
1787 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1788                                               SelectionDAG &DAG) const {
1789   EVT PtrVT = Op.getValueType();
1790   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1791   SDLoc DL(GSDN);
1792   const GlobalValue *GV = GSDN->getGlobal();
1793
1794   // 64-bit SVR4 ABI code is always position-independent.
1795   // The actual address of the GlobalValue is stored in the TOC.
1796   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1797     setUsesTOCBasePtr(DAG);
1798     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1799     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1800                        DAG.getRegister(PPC::X2, MVT::i64));
1801   }
1802
1803   unsigned MOHiFlag, MOLoFlag;
1804   bool isPIC =
1805       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
1806
1807   if (isPIC && Subtarget.isSVR4ABI()) {
1808     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1809                                             GSDN->getOffset(),
1810                                             PPCII::MO_PIC_FLAG);
1811     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1812                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1813   }
1814
1815   SDValue GAHi =
1816     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1817   SDValue GALo =
1818     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1819
1820   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1821
1822   // If the global reference is actually to a non-lazy-pointer, we have to do an
1823   // extra load to get the address of the global.
1824   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1825     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1826                       false, false, false, 0);
1827   return Ptr;
1828 }
1829
1830 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1831   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1832   SDLoc dl(Op);
1833
1834   if (Op.getValueType() == MVT::v2i64) {
1835     // When the operands themselves are v2i64 values, we need to do something
1836     // special because VSX has no underlying comparison operations for these.
1837     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1838       // Equality can be handled by casting to the legal type for Altivec
1839       // comparisons, everything else needs to be expanded.
1840       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1841         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1842                  DAG.getSetCC(dl, MVT::v4i32,
1843                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1844                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1845                    CC));
1846       }
1847
1848       return SDValue();
1849     }
1850
1851     // We handle most of these in the usual way.
1852     return Op;
1853   }
1854
1855   // If we're comparing for equality to zero, expose the fact that this is
1856   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1857   // fold the new nodes.
1858   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1859     if (C->isNullValue() && CC == ISD::SETEQ) {
1860       EVT VT = Op.getOperand(0).getValueType();
1861       SDValue Zext = Op.getOperand(0);
1862       if (VT.bitsLT(MVT::i32)) {
1863         VT = MVT::i32;
1864         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1865       }
1866       unsigned Log2b = Log2_32(VT.getSizeInBits());
1867       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1868       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1869                                 DAG.getConstant(Log2b, MVT::i32));
1870       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1871     }
1872     // Leave comparisons against 0 and -1 alone for now, since they're usually
1873     // optimized.  FIXME: revisit this when we can custom lower all setcc
1874     // optimizations.
1875     if (C->isAllOnesValue() || C->isNullValue())
1876       return SDValue();
1877   }
1878
1879   // If we have an integer seteq/setne, turn it into a compare against zero
1880   // by xor'ing the rhs with the lhs, which is faster than setting a
1881   // condition register, reading it back out, and masking the correct bit.  The
1882   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1883   // the result to other bit-twiddling opportunities.
1884   EVT LHSVT = Op.getOperand(0).getValueType();
1885   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1886     EVT VT = Op.getValueType();
1887     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1888                                 Op.getOperand(1));
1889     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1890   }
1891   return SDValue();
1892 }
1893
1894 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1895                                       const PPCSubtarget &Subtarget) const {
1896   SDNode *Node = Op.getNode();
1897   EVT VT = Node->getValueType(0);
1898   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1899   SDValue InChain = Node->getOperand(0);
1900   SDValue VAListPtr = Node->getOperand(1);
1901   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1902   SDLoc dl(Node);
1903
1904   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1905
1906   // gpr_index
1907   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1908                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1909                                     false, false, false, 0);
1910   InChain = GprIndex.getValue(1);
1911
1912   if (VT == MVT::i64) {
1913     // Check if GprIndex is even
1914     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1915                                  DAG.getConstant(1, MVT::i32));
1916     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1917                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1918     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1919                                           DAG.getConstant(1, MVT::i32));
1920     // Align GprIndex to be even if it isn't
1921     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1922                            GprIndex);
1923   }
1924
1925   // fpr index is 1 byte after gpr
1926   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1927                                DAG.getConstant(1, MVT::i32));
1928
1929   // fpr
1930   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1931                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1932                                     false, false, false, 0);
1933   InChain = FprIndex.getValue(1);
1934
1935   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1936                                        DAG.getConstant(8, MVT::i32));
1937
1938   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1939                                         DAG.getConstant(4, MVT::i32));
1940
1941   // areas
1942   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1943                                      MachinePointerInfo(), false, false,
1944                                      false, 0);
1945   InChain = OverflowArea.getValue(1);
1946
1947   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1948                                     MachinePointerInfo(), false, false,
1949                                     false, 0);
1950   InChain = RegSaveArea.getValue(1);
1951
1952   // select overflow_area if index > 8
1953   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1954                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1955
1956   // adjustment constant gpr_index * 4/8
1957   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1958                                     VT.isInteger() ? GprIndex : FprIndex,
1959                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1960                                                     MVT::i32));
1961
1962   // OurReg = RegSaveArea + RegConstant
1963   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1964                                RegConstant);
1965
1966   // Floating types are 32 bytes into RegSaveArea
1967   if (VT.isFloatingPoint())
1968     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1969                          DAG.getConstant(32, MVT::i32));
1970
1971   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1972   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1973                                    VT.isInteger() ? GprIndex : FprIndex,
1974                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1975                                                    MVT::i32));
1976
1977   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1978                               VT.isInteger() ? VAListPtr : FprPtr,
1979                               MachinePointerInfo(SV),
1980                               MVT::i8, false, false, 0);
1981
1982   // determine if we should load from reg_save_area or overflow_area
1983   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1984
1985   // increase overflow_area by 4/8 if gpr/fpr > 8
1986   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1987                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1988                                           MVT::i32));
1989
1990   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1991                              OverflowAreaPlusN);
1992
1993   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1994                               OverflowAreaPtr,
1995                               MachinePointerInfo(),
1996                               MVT::i32, false, false, 0);
1997
1998   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1999                      false, false, false, 0);
2000 }
2001
2002 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2003                                        const PPCSubtarget &Subtarget) const {
2004   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2005
2006   // We have to copy the entire va_list struct:
2007   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2008   return DAG.getMemcpy(Op.getOperand(0), Op,
2009                        Op.getOperand(1), Op.getOperand(2),
2010                        DAG.getConstant(12, MVT::i32), 8, false, true,
2011                        MachinePointerInfo(), MachinePointerInfo());
2012 }
2013
2014 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2015                                                   SelectionDAG &DAG) const {
2016   return Op.getOperand(0);
2017 }
2018
2019 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2020                                                 SelectionDAG &DAG) const {
2021   SDValue Chain = Op.getOperand(0);
2022   SDValue Trmp = Op.getOperand(1); // trampoline
2023   SDValue FPtr = Op.getOperand(2); // nested function
2024   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2025   SDLoc dl(Op);
2026
2027   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2028   bool isPPC64 = (PtrVT == MVT::i64);
2029   Type *IntPtrTy =
2030     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2031                                                              *DAG.getContext());
2032
2033   TargetLowering::ArgListTy Args;
2034   TargetLowering::ArgListEntry Entry;
2035
2036   Entry.Ty = IntPtrTy;
2037   Entry.Node = Trmp; Args.push_back(Entry);
2038
2039   // TrampSize == (isPPC64 ? 48 : 40);
2040   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2041                                isPPC64 ? MVT::i64 : MVT::i32);
2042   Args.push_back(Entry);
2043
2044   Entry.Node = FPtr; Args.push_back(Entry);
2045   Entry.Node = Nest; Args.push_back(Entry);
2046
2047   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2048   TargetLowering::CallLoweringInfo CLI(DAG);
2049   CLI.setDebugLoc(dl).setChain(Chain)
2050     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2051                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2052                std::move(Args), 0);
2053
2054   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2055   return CallResult.second;
2056 }
2057
2058 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2059                                         const PPCSubtarget &Subtarget) const {
2060   MachineFunction &MF = DAG.getMachineFunction();
2061   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2062
2063   SDLoc dl(Op);
2064
2065   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2066     // vastart just stores the address of the VarArgsFrameIndex slot into the
2067     // memory location argument.
2068     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2069     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2070     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2071     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2072                         MachinePointerInfo(SV),
2073                         false, false, 0);
2074   }
2075
2076   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2077   // We suppose the given va_list is already allocated.
2078   //
2079   // typedef struct {
2080   //  char gpr;     /* index into the array of 8 GPRs
2081   //                 * stored in the register save area
2082   //                 * gpr=0 corresponds to r3,
2083   //                 * gpr=1 to r4, etc.
2084   //                 */
2085   //  char fpr;     /* index into the array of 8 FPRs
2086   //                 * stored in the register save area
2087   //                 * fpr=0 corresponds to f1,
2088   //                 * fpr=1 to f2, etc.
2089   //                 */
2090   //  char *overflow_arg_area;
2091   //                /* location on stack that holds
2092   //                 * the next overflow argument
2093   //                 */
2094   //  char *reg_save_area;
2095   //               /* where r3:r10 and f1:f8 (if saved)
2096   //                * are stored
2097   //                */
2098   // } va_list[1];
2099
2100
2101   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2102   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2103
2104
2105   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2106
2107   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2108                                             PtrVT);
2109   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2110                                  PtrVT);
2111
2112   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2113   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2114
2115   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2116   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2117
2118   uint64_t FPROffset = 1;
2119   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2120
2121   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2122
2123   // Store first byte : number of int regs
2124   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2125                                          Op.getOperand(1),
2126                                          MachinePointerInfo(SV),
2127                                          MVT::i8, false, false, 0);
2128   uint64_t nextOffset = FPROffset;
2129   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2130                                   ConstFPROffset);
2131
2132   // Store second byte : number of float regs
2133   SDValue secondStore =
2134     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2135                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2136                       false, false, 0);
2137   nextOffset += StackOffset;
2138   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2139
2140   // Store second word : arguments given on stack
2141   SDValue thirdStore =
2142     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2143                  MachinePointerInfo(SV, nextOffset),
2144                  false, false, 0);
2145   nextOffset += FrameOffset;
2146   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2147
2148   // Store third word : arguments given in registers
2149   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2150                       MachinePointerInfo(SV, nextOffset),
2151                       false, false, 0);
2152
2153 }
2154
2155 #include "PPCGenCallingConv.inc"
2156
2157 // Function whose sole purpose is to kill compiler warnings 
2158 // stemming from unused functions included from PPCGenCallingConv.inc.
2159 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2160   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2161 }
2162
2163 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2164                                       CCValAssign::LocInfo &LocInfo,
2165                                       ISD::ArgFlagsTy &ArgFlags,
2166                                       CCState &State) {
2167   return true;
2168 }
2169
2170 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2171                                              MVT &LocVT,
2172                                              CCValAssign::LocInfo &LocInfo,
2173                                              ISD::ArgFlagsTy &ArgFlags,
2174                                              CCState &State) {
2175   static const MCPhysReg ArgRegs[] = {
2176     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2177     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2178   };
2179   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2180
2181   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2182
2183   // Skip one register if the first unallocated register has an even register
2184   // number and there are still argument registers available which have not been
2185   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2186   // need to skip a register if RegNum is odd.
2187   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2188     State.AllocateReg(ArgRegs[RegNum]);
2189   }
2190
2191   // Always return false here, as this function only makes sure that the first
2192   // unallocated register has an odd register number and does not actually
2193   // allocate a register for the current argument.
2194   return false;
2195 }
2196
2197 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2198                                                MVT &LocVT,
2199                                                CCValAssign::LocInfo &LocInfo,
2200                                                ISD::ArgFlagsTy &ArgFlags,
2201                                                CCState &State) {
2202   static const MCPhysReg ArgRegs[] = {
2203     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2204     PPC::F8
2205   };
2206
2207   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2208
2209   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2210
2211   // If there is only one Floating-point register left we need to put both f64
2212   // values of a split ppc_fp128 value on the stack.
2213   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2214     State.AllocateReg(ArgRegs[RegNum]);
2215   }
2216
2217   // Always return false here, as this function only makes sure that the two f64
2218   // values a ppc_fp128 value is split into are both passed in registers or both
2219   // passed on the stack and does not actually allocate a register for the
2220   // current argument.
2221   return false;
2222 }
2223
2224 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2225 /// on Darwin.
2226 static const MCPhysReg *GetFPR() {
2227   static const MCPhysReg FPR[] = {
2228     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2229     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2230   };
2231
2232   return FPR;
2233 }
2234
2235 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2236 /// the stack.
2237 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2238                                        unsigned PtrByteSize) {
2239   unsigned ArgSize = ArgVT.getStoreSize();
2240   if (Flags.isByVal())
2241     ArgSize = Flags.getByValSize();
2242
2243   // Round up to multiples of the pointer size, except for array members,
2244   // which are always packed.
2245   if (!Flags.isInConsecutiveRegs())
2246     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2247
2248   return ArgSize;
2249 }
2250
2251 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2252 /// on the stack.
2253 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2254                                             ISD::ArgFlagsTy Flags,
2255                                             unsigned PtrByteSize) {
2256   unsigned Align = PtrByteSize;
2257
2258   // Altivec parameters are padded to a 16 byte boundary.
2259   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2260       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2261       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2262     Align = 16;
2263
2264   // ByVal parameters are aligned as requested.
2265   if (Flags.isByVal()) {
2266     unsigned BVAlign = Flags.getByValAlign();
2267     if (BVAlign > PtrByteSize) {
2268       if (BVAlign % PtrByteSize != 0)
2269           llvm_unreachable(
2270             "ByVal alignment is not a multiple of the pointer size");
2271
2272       Align = BVAlign;
2273     }
2274   }
2275
2276   // Array members are always packed to their original alignment.
2277   if (Flags.isInConsecutiveRegs()) {
2278     // If the array member was split into multiple registers, the first
2279     // needs to be aligned to the size of the full type.  (Except for
2280     // ppcf128, which is only aligned as its f64 components.)
2281     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2282       Align = OrigVT.getStoreSize();
2283     else
2284       Align = ArgVT.getStoreSize();
2285   }
2286
2287   return Align;
2288 }
2289
2290 /// CalculateStackSlotUsed - Return whether this argument will use its
2291 /// stack slot (instead of being passed in registers).  ArgOffset,
2292 /// AvailableFPRs, and AvailableVRs must hold the current argument
2293 /// position, and will be updated to account for this argument.
2294 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2295                                    ISD::ArgFlagsTy Flags,
2296                                    unsigned PtrByteSize,
2297                                    unsigned LinkageSize,
2298                                    unsigned ParamAreaSize,
2299                                    unsigned &ArgOffset,
2300                                    unsigned &AvailableFPRs,
2301                                    unsigned &AvailableVRs) {
2302   bool UseMemory = false;
2303
2304   // Respect alignment of argument on the stack.
2305   unsigned Align =
2306     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2307   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2308   // If there's no space left in the argument save area, we must
2309   // use memory (this check also catches zero-sized arguments).
2310   if (ArgOffset >= LinkageSize + ParamAreaSize)
2311     UseMemory = true;
2312
2313   // Allocate argument on the stack.
2314   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2315   if (Flags.isInConsecutiveRegsLast())
2316     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2317   // If we overran the argument save area, we must use memory
2318   // (this check catches arguments passed partially in memory)
2319   if (ArgOffset > LinkageSize + ParamAreaSize)
2320     UseMemory = true;
2321
2322   // However, if the argument is actually passed in an FPR or a VR,
2323   // we don't use memory after all.
2324   if (!Flags.isByVal()) {
2325     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2326       if (AvailableFPRs > 0) {
2327         --AvailableFPRs;
2328         return false;
2329       }
2330     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2331         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2332         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2333       if (AvailableVRs > 0) {
2334         --AvailableVRs;
2335         return false;
2336       }
2337   }
2338
2339   return UseMemory;
2340 }
2341
2342 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2343 /// ensure minimum alignment required for target.
2344 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2345                                      unsigned NumBytes) {
2346   unsigned TargetAlign = Lowering->getStackAlignment();
2347   unsigned AlignMask = TargetAlign - 1;
2348   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2349   return NumBytes;
2350 }
2351
2352 SDValue
2353 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2354                                         CallingConv::ID CallConv, bool isVarArg,
2355                                         const SmallVectorImpl<ISD::InputArg>
2356                                           &Ins,
2357                                         SDLoc dl, SelectionDAG &DAG,
2358                                         SmallVectorImpl<SDValue> &InVals)
2359                                           const {
2360   if (Subtarget.isSVR4ABI()) {
2361     if (Subtarget.isPPC64())
2362       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2363                                          dl, DAG, InVals);
2364     else
2365       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2366                                          dl, DAG, InVals);
2367   } else {
2368     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2369                                        dl, DAG, InVals);
2370   }
2371 }
2372
2373 SDValue
2374 PPCTargetLowering::LowerFormalArguments_32SVR4(
2375                                       SDValue Chain,
2376                                       CallingConv::ID CallConv, bool isVarArg,
2377                                       const SmallVectorImpl<ISD::InputArg>
2378                                         &Ins,
2379                                       SDLoc dl, SelectionDAG &DAG,
2380                                       SmallVectorImpl<SDValue> &InVals) const {
2381
2382   // 32-bit SVR4 ABI Stack Frame Layout:
2383   //              +-----------------------------------+
2384   //        +-->  |            Back chain             |
2385   //        |     +-----------------------------------+
2386   //        |     | Floating-point register save area |
2387   //        |     +-----------------------------------+
2388   //        |     |    General register save area     |
2389   //        |     +-----------------------------------+
2390   //        |     |          CR save word             |
2391   //        |     +-----------------------------------+
2392   //        |     |         VRSAVE save word          |
2393   //        |     +-----------------------------------+
2394   //        |     |         Alignment padding         |
2395   //        |     +-----------------------------------+
2396   //        |     |     Vector register save area     |
2397   //        |     +-----------------------------------+
2398   //        |     |       Local variable space        |
2399   //        |     +-----------------------------------+
2400   //        |     |        Parameter list area        |
2401   //        |     +-----------------------------------+
2402   //        |     |           LR save word            |
2403   //        |     +-----------------------------------+
2404   // SP-->  +---  |            Back chain             |
2405   //              +-----------------------------------+
2406   //
2407   // Specifications:
2408   //   System V Application Binary Interface PowerPC Processor Supplement
2409   //   AltiVec Technology Programming Interface Manual
2410
2411   MachineFunction &MF = DAG.getMachineFunction();
2412   MachineFrameInfo *MFI = MF.getFrameInfo();
2413   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2414
2415   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2416   // Potential tail calls could cause overwriting of argument stack slots.
2417   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2418                        (CallConv == CallingConv::Fast));
2419   unsigned PtrByteSize = 4;
2420
2421   // Assign locations to all of the incoming arguments.
2422   SmallVector<CCValAssign, 16> ArgLocs;
2423   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2424                  *DAG.getContext());
2425
2426   // Reserve space for the linkage area on the stack.
2427   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2428   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2429
2430   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2431
2432   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2433     CCValAssign &VA = ArgLocs[i];
2434
2435     // Arguments stored in registers.
2436     if (VA.isRegLoc()) {
2437       const TargetRegisterClass *RC;
2438       EVT ValVT = VA.getValVT();
2439
2440       switch (ValVT.getSimpleVT().SimpleTy) {
2441         default:
2442           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2443         case MVT::i1:
2444         case MVT::i32:
2445           RC = &PPC::GPRCRegClass;
2446           break;
2447         case MVT::f32:
2448           RC = &PPC::F4RCRegClass;
2449           break;
2450         case MVT::f64:
2451           if (Subtarget.hasVSX())
2452             RC = &PPC::VSFRCRegClass;
2453           else
2454             RC = &PPC::F8RCRegClass;
2455           break;
2456         case MVT::v16i8:
2457         case MVT::v8i16:
2458         case MVT::v4i32:
2459         case MVT::v4f32:
2460           RC = &PPC::VRRCRegClass;
2461           break;
2462         case MVT::v2f64:
2463         case MVT::v2i64:
2464           RC = &PPC::VSHRCRegClass;
2465           break;
2466       }
2467
2468       // Transform the arguments stored in physical registers into virtual ones.
2469       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2470       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2471                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2472
2473       if (ValVT == MVT::i1)
2474         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2475
2476       InVals.push_back(ArgValue);
2477     } else {
2478       // Argument stored in memory.
2479       assert(VA.isMemLoc());
2480
2481       unsigned ArgSize = VA.getLocVT().getStoreSize();
2482       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2483                                       isImmutable);
2484
2485       // Create load nodes to retrieve arguments from the stack.
2486       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2487       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2488                                    MachinePointerInfo(),
2489                                    false, false, false, 0));
2490     }
2491   }
2492
2493   // Assign locations to all of the incoming aggregate by value arguments.
2494   // Aggregates passed by value are stored in the local variable space of the
2495   // caller's stack frame, right above the parameter list area.
2496   SmallVector<CCValAssign, 16> ByValArgLocs;
2497   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2498                       ByValArgLocs, *DAG.getContext());
2499
2500   // Reserve stack space for the allocations in CCInfo.
2501   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2502
2503   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2504
2505   // Area that is at least reserved in the caller of this function.
2506   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2507   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2508
2509   // Set the size that is at least reserved in caller of this function.  Tail
2510   // call optimized function's reserved stack space needs to be aligned so that
2511   // taking the difference between two stack areas will result in an aligned
2512   // stack.
2513   MinReservedArea =
2514       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2515   FuncInfo->setMinReservedArea(MinReservedArea);
2516
2517   SmallVector<SDValue, 8> MemOps;
2518
2519   // If the function takes variable number of arguments, make a frame index for
2520   // the start of the first vararg value... for expansion of llvm.va_start.
2521   if (isVarArg) {
2522     static const MCPhysReg GPArgRegs[] = {
2523       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2524       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2525     };
2526     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2527
2528     static const MCPhysReg FPArgRegs[] = {
2529       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2530       PPC::F8
2531     };
2532     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2533     if (DisablePPCFloatInVariadic)
2534       NumFPArgRegs = 0;
2535
2536     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2537                                                           NumGPArgRegs));
2538     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2539                                                           NumFPArgRegs));
2540
2541     // Make room for NumGPArgRegs and NumFPArgRegs.
2542     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2543                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2544
2545     FuncInfo->setVarArgsStackOffset(
2546       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2547                              CCInfo.getNextStackOffset(), true));
2548
2549     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2550     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2551
2552     // The fixed integer arguments of a variadic function are stored to the
2553     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2554     // the result of va_next.
2555     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2556       // Get an existing live-in vreg, or add a new one.
2557       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2558       if (!VReg)
2559         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2560
2561       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2562       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2563                                    MachinePointerInfo(), false, false, 0);
2564       MemOps.push_back(Store);
2565       // Increment the address by four for the next argument to store
2566       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2567       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2568     }
2569
2570     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2571     // is set.
2572     // The double arguments are stored to the VarArgsFrameIndex
2573     // on the stack.
2574     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2575       // Get an existing live-in vreg, or add a new one.
2576       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2577       if (!VReg)
2578         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2579
2580       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2581       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2582                                    MachinePointerInfo(), false, false, 0);
2583       MemOps.push_back(Store);
2584       // Increment the address by eight for the next argument to store
2585       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2586                                          PtrVT);
2587       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2588     }
2589   }
2590
2591   if (!MemOps.empty())
2592     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2593
2594   return Chain;
2595 }
2596
2597 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2598 // value to MVT::i64 and then truncate to the correct register size.
2599 SDValue
2600 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2601                                      SelectionDAG &DAG, SDValue ArgVal,
2602                                      SDLoc dl) const {
2603   if (Flags.isSExt())
2604     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2605                          DAG.getValueType(ObjectVT));
2606   else if (Flags.isZExt())
2607     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2608                          DAG.getValueType(ObjectVT));
2609
2610   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2611 }
2612
2613 SDValue
2614 PPCTargetLowering::LowerFormalArguments_64SVR4(
2615                                       SDValue Chain,
2616                                       CallingConv::ID CallConv, bool isVarArg,
2617                                       const SmallVectorImpl<ISD::InputArg>
2618                                         &Ins,
2619                                       SDLoc dl, SelectionDAG &DAG,
2620                                       SmallVectorImpl<SDValue> &InVals) const {
2621   // TODO: add description of PPC stack frame format, or at least some docs.
2622   //
2623   bool isELFv2ABI = Subtarget.isELFv2ABI();
2624   bool isLittleEndian = Subtarget.isLittleEndian();
2625   MachineFunction &MF = DAG.getMachineFunction();
2626   MachineFrameInfo *MFI = MF.getFrameInfo();
2627   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2628
2629   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2630          "fastcc not supported on varargs functions");
2631
2632   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2633   // Potential tail calls could cause overwriting of argument stack slots.
2634   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2635                        (CallConv == CallingConv::Fast));
2636   unsigned PtrByteSize = 8;
2637
2638   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2639                                                           isELFv2ABI);
2640
2641   static const MCPhysReg GPR[] = {
2642     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2643     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2644   };
2645
2646   static const MCPhysReg *FPR = GetFPR();
2647
2648   static const MCPhysReg VR[] = {
2649     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2650     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2651   };
2652   static const MCPhysReg VSRH[] = {
2653     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2654     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2655   };
2656
2657   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2658   const unsigned Num_FPR_Regs = 13;
2659   const unsigned Num_VR_Regs  = array_lengthof(VR);
2660
2661   // Do a first pass over the arguments to determine whether the ABI
2662   // guarantees that our caller has allocated the parameter save area
2663   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2664   // in the ELFv2 ABI, it is true if this is a vararg function or if
2665   // any parameter is located in a stack slot.
2666
2667   bool HasParameterArea = !isELFv2ABI || isVarArg;
2668   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2669   unsigned NumBytes = LinkageSize;
2670   unsigned AvailableFPRs = Num_FPR_Regs;
2671   unsigned AvailableVRs = Num_VR_Regs;
2672   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2673     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2674                                PtrByteSize, LinkageSize, ParamAreaSize,
2675                                NumBytes, AvailableFPRs, AvailableVRs))
2676       HasParameterArea = true;
2677
2678   // Add DAG nodes to load the arguments or copy them out of registers.  On
2679   // entry to a function on PPC, the arguments start after the linkage area,
2680   // although the first ones are often in registers.
2681
2682   unsigned ArgOffset = LinkageSize;
2683   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2684   SmallVector<SDValue, 8> MemOps;
2685   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2686   unsigned CurArgIdx = 0;
2687   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2688     SDValue ArgVal;
2689     bool needsLoad = false;
2690     EVT ObjectVT = Ins[ArgNo].VT;
2691     EVT OrigVT = Ins[ArgNo].ArgVT;
2692     unsigned ObjSize = ObjectVT.getStoreSize();
2693     unsigned ArgSize = ObjSize;
2694     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2695     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2696     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2697
2698     // We re-align the argument offset for each argument, except when using the
2699     // fast calling convention, when we need to make sure we do that only when
2700     // we'll actually use a stack slot.
2701     unsigned CurArgOffset, Align;
2702     auto ComputeArgOffset = [&]() {
2703       /* Respect alignment of argument on the stack.  */
2704       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2705       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2706       CurArgOffset = ArgOffset;
2707     };
2708
2709     if (CallConv != CallingConv::Fast) {
2710       ComputeArgOffset();
2711
2712       /* Compute GPR index associated with argument offset.  */
2713       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2714       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2715     }
2716
2717     // FIXME the codegen can be much improved in some cases.
2718     // We do not have to keep everything in memory.
2719     if (Flags.isByVal()) {
2720       if (CallConv == CallingConv::Fast)
2721         ComputeArgOffset();
2722
2723       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2724       ObjSize = Flags.getByValSize();
2725       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2726       // Empty aggregate parameters do not take up registers.  Examples:
2727       //   struct { } a;
2728       //   union  { } b;
2729       //   int c[0];
2730       // etc.  However, we have to provide a place-holder in InVals, so
2731       // pretend we have an 8-byte item at the current address for that
2732       // purpose.
2733       if (!ObjSize) {
2734         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2735         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2736         InVals.push_back(FIN);
2737         continue;
2738       }
2739
2740       // Create a stack object covering all stack doublewords occupied
2741       // by the argument.  If the argument is (fully or partially) on
2742       // the stack, or if the argument is fully in registers but the
2743       // caller has allocated the parameter save anyway, we can refer
2744       // directly to the caller's stack frame.  Otherwise, create a
2745       // local copy in our own frame.
2746       int FI;
2747       if (HasParameterArea ||
2748           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2749         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2750       else
2751         FI = MFI->CreateStackObject(ArgSize, Align, false);
2752       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2753
2754       // Handle aggregates smaller than 8 bytes.
2755       if (ObjSize < PtrByteSize) {
2756         // The value of the object is its address, which differs from the
2757         // address of the enclosing doubleword on big-endian systems.
2758         SDValue Arg = FIN;
2759         if (!isLittleEndian) {
2760           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2761           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2762         }
2763         InVals.push_back(Arg);
2764
2765         if (GPR_idx != Num_GPR_Regs) {
2766           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2767           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2768           SDValue Store;
2769
2770           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2771             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2772                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2773             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2774                                       MachinePointerInfo(FuncArg),
2775                                       ObjType, false, false, 0);
2776           } else {
2777             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2778             // store the whole register as-is to the parameter save area
2779             // slot.
2780             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2781                                  MachinePointerInfo(FuncArg),
2782                                  false, false, 0);
2783           }
2784
2785           MemOps.push_back(Store);
2786         }
2787         // Whether we copied from a register or not, advance the offset
2788         // into the parameter save area by a full doubleword.
2789         ArgOffset += PtrByteSize;
2790         continue;
2791       }
2792
2793       // The value of the object is its address, which is the address of
2794       // its first stack doubleword.
2795       InVals.push_back(FIN);
2796
2797       // Store whatever pieces of the object are in registers to memory.
2798       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2799         if (GPR_idx == Num_GPR_Regs)
2800           break;
2801
2802         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2803         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2804         SDValue Addr = FIN;
2805         if (j) {
2806           SDValue Off = DAG.getConstant(j, PtrVT);
2807           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2808         }
2809         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2810                                      MachinePointerInfo(FuncArg, j),
2811                                      false, false, 0);
2812         MemOps.push_back(Store);
2813         ++GPR_idx;
2814       }
2815       ArgOffset += ArgSize;
2816       continue;
2817     }
2818
2819     switch (ObjectVT.getSimpleVT().SimpleTy) {
2820     default: llvm_unreachable("Unhandled argument type!");
2821     case MVT::i1:
2822     case MVT::i32:
2823     case MVT::i64:
2824       // These can be scalar arguments or elements of an integer array type
2825       // passed directly.  Clang may use those instead of "byval" aggregate
2826       // types to avoid forcing arguments to memory unnecessarily.
2827       if (GPR_idx != Num_GPR_Regs) {
2828         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2829         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2830
2831         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2832           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2833           // value to MVT::i64 and then truncate to the correct register size.
2834           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2835       } else {
2836         if (CallConv == CallingConv::Fast)
2837           ComputeArgOffset();
2838
2839         needsLoad = true;
2840         ArgSize = PtrByteSize;
2841       }
2842       if (CallConv != CallingConv::Fast || needsLoad)
2843         ArgOffset += 8;
2844       break;
2845
2846     case MVT::f32:
2847     case MVT::f64:
2848       // These can be scalar arguments or elements of a float array type
2849       // passed directly.  The latter are used to implement ELFv2 homogenous
2850       // float aggregates.
2851       if (FPR_idx != Num_FPR_Regs) {
2852         unsigned VReg;
2853
2854         if (ObjectVT == MVT::f32)
2855           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2856         else
2857           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
2858                                                 ? &PPC::VSFRCRegClass
2859                                                 : &PPC::F8RCRegClass);
2860
2861         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2862         ++FPR_idx;
2863       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
2864         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
2865         // once we support fp <-> gpr moves.
2866
2867         // This can only ever happen in the presence of f32 array types,
2868         // since otherwise we never run out of FPRs before running out
2869         // of GPRs.
2870         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2871         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2872
2873         if (ObjectVT == MVT::f32) {
2874           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2875             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2876                                  DAG.getConstant(32, MVT::i32));
2877           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2878         }
2879
2880         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2881       } else {
2882         if (CallConv == CallingConv::Fast)
2883           ComputeArgOffset();
2884
2885         needsLoad = true;
2886       }
2887
2888       // When passing an array of floats, the array occupies consecutive
2889       // space in the argument area; only round up to the next doubleword
2890       // at the end of the array.  Otherwise, each float takes 8 bytes.
2891       if (CallConv != CallingConv::Fast || needsLoad) {
2892         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2893         ArgOffset += ArgSize;
2894         if (Flags.isInConsecutiveRegsLast())
2895           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2896       }
2897       break;
2898     case MVT::v4f32:
2899     case MVT::v4i32:
2900     case MVT::v8i16:
2901     case MVT::v16i8:
2902     case MVT::v2f64:
2903     case MVT::v2i64:
2904       // These can be scalar arguments or elements of a vector array type
2905       // passed directly.  The latter are used to implement ELFv2 homogenous
2906       // vector aggregates.
2907       if (VR_idx != Num_VR_Regs) {
2908         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2909                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2910                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2911         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2912         ++VR_idx;
2913       } else {
2914         if (CallConv == CallingConv::Fast)
2915           ComputeArgOffset();
2916
2917         needsLoad = true;
2918       }
2919       if (CallConv != CallingConv::Fast || needsLoad)
2920         ArgOffset += 16;
2921       break;
2922     }
2923
2924     // We need to load the argument to a virtual register if we determined
2925     // above that we ran out of physical registers of the appropriate type.
2926     if (needsLoad) {
2927       if (ObjSize < ArgSize && !isLittleEndian)
2928         CurArgOffset += ArgSize - ObjSize;
2929       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2930       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2931       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2932                            false, false, false, 0);
2933     }
2934
2935     InVals.push_back(ArgVal);
2936   }
2937
2938   // Area that is at least reserved in the caller of this function.
2939   unsigned MinReservedArea;
2940   if (HasParameterArea)
2941     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2942   else
2943     MinReservedArea = LinkageSize;
2944
2945   // Set the size that is at least reserved in caller of this function.  Tail
2946   // call optimized functions' reserved stack space needs to be aligned so that
2947   // taking the difference between two stack areas will result in an aligned
2948   // stack.
2949   MinReservedArea =
2950       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2951   FuncInfo->setMinReservedArea(MinReservedArea);
2952
2953   // If the function takes variable number of arguments, make a frame index for
2954   // the start of the first vararg value... for expansion of llvm.va_start.
2955   if (isVarArg) {
2956     int Depth = ArgOffset;
2957
2958     FuncInfo->setVarArgsFrameIndex(
2959       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2960     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2961
2962     // If this function is vararg, store any remaining integer argument regs
2963     // to their spots on the stack so that they may be loaded by deferencing the
2964     // result of va_next.
2965     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2966          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2967       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2968       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2969       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2970                                    MachinePointerInfo(), false, false, 0);
2971       MemOps.push_back(Store);
2972       // Increment the address by four for the next argument to store
2973       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2974       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2975     }
2976   }
2977
2978   if (!MemOps.empty())
2979     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2980
2981   return Chain;
2982 }
2983
2984 SDValue
2985 PPCTargetLowering::LowerFormalArguments_Darwin(
2986                                       SDValue Chain,
2987                                       CallingConv::ID CallConv, bool isVarArg,
2988                                       const SmallVectorImpl<ISD::InputArg>
2989                                         &Ins,
2990                                       SDLoc dl, SelectionDAG &DAG,
2991                                       SmallVectorImpl<SDValue> &InVals) const {
2992   // TODO: add description of PPC stack frame format, or at least some docs.
2993   //
2994   MachineFunction &MF = DAG.getMachineFunction();
2995   MachineFrameInfo *MFI = MF.getFrameInfo();
2996   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2997
2998   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2999   bool isPPC64 = PtrVT == MVT::i64;
3000   // Potential tail calls could cause overwriting of argument stack slots.
3001   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3002                        (CallConv == CallingConv::Fast));
3003   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3004
3005   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
3006                                                           false);
3007   unsigned ArgOffset = LinkageSize;
3008   // Area that is at least reserved in caller of this function.
3009   unsigned MinReservedArea = ArgOffset;
3010
3011   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3012     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3013     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3014   };
3015   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3016     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3017     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3018   };
3019
3020   static const MCPhysReg *FPR = GetFPR();
3021
3022   static const MCPhysReg VR[] = {
3023     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3024     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3025   };
3026
3027   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3028   const unsigned Num_FPR_Regs = 13;
3029   const unsigned Num_VR_Regs  = array_lengthof( VR);
3030
3031   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3032
3033   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3034
3035   // In 32-bit non-varargs functions, the stack space for vectors is after the
3036   // stack space for non-vectors.  We do not use this space unless we have
3037   // too many vectors to fit in registers, something that only occurs in
3038   // constructed examples:), but we have to walk the arglist to figure
3039   // that out...for the pathological case, compute VecArgOffset as the
3040   // start of the vector parameter area.  Computing VecArgOffset is the
3041   // entire point of the following loop.
3042   unsigned VecArgOffset = ArgOffset;
3043   if (!isVarArg && !isPPC64) {
3044     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3045          ++ArgNo) {
3046       EVT ObjectVT = Ins[ArgNo].VT;
3047       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3048
3049       if (Flags.isByVal()) {
3050         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3051         unsigned ObjSize = Flags.getByValSize();
3052         unsigned ArgSize =
3053                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3054         VecArgOffset += ArgSize;
3055         continue;
3056       }
3057
3058       switch(ObjectVT.getSimpleVT().SimpleTy) {
3059       default: llvm_unreachable("Unhandled argument type!");
3060       case MVT::i1:
3061       case MVT::i32:
3062       case MVT::f32:
3063         VecArgOffset += 4;
3064         break;
3065       case MVT::i64:  // PPC64
3066       case MVT::f64:
3067         // FIXME: We are guaranteed to be !isPPC64 at this point.
3068         // Does MVT::i64 apply?
3069         VecArgOffset += 8;
3070         break;
3071       case MVT::v4f32:
3072       case MVT::v4i32:
3073       case MVT::v8i16:
3074       case MVT::v16i8:
3075         // Nothing to do, we're only looking at Nonvector args here.
3076         break;
3077       }
3078     }
3079   }
3080   // We've found where the vector parameter area in memory is.  Skip the
3081   // first 12 parameters; these don't use that memory.
3082   VecArgOffset = ((VecArgOffset+15)/16)*16;
3083   VecArgOffset += 12*16;
3084
3085   // Add DAG nodes to load the arguments or copy them out of registers.  On
3086   // entry to a function on PPC, the arguments start after the linkage area,
3087   // although the first ones are often in registers.
3088
3089   SmallVector<SDValue, 8> MemOps;
3090   unsigned nAltivecParamsAtEnd = 0;
3091   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3092   unsigned CurArgIdx = 0;
3093   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3094     SDValue ArgVal;
3095     bool needsLoad = false;
3096     EVT ObjectVT = Ins[ArgNo].VT;
3097     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3098     unsigned ArgSize = ObjSize;
3099     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3100     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3101     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3102
3103     unsigned CurArgOffset = ArgOffset;
3104
3105     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3106     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3107         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3108       if (isVarArg || isPPC64) {
3109         MinReservedArea = ((MinReservedArea+15)/16)*16;
3110         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3111                                                   Flags,
3112                                                   PtrByteSize);
3113       } else  nAltivecParamsAtEnd++;
3114     } else
3115       // Calculate min reserved area.
3116       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3117                                                 Flags,
3118                                                 PtrByteSize);
3119
3120     // FIXME the codegen can be much improved in some cases.
3121     // We do not have to keep everything in memory.
3122     if (Flags.isByVal()) {
3123       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3124       ObjSize = Flags.getByValSize();
3125       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3126       // Objects of size 1 and 2 are right justified, everything else is
3127       // left justified.  This means the memory address is adjusted forwards.
3128       if (ObjSize==1 || ObjSize==2) {
3129         CurArgOffset = CurArgOffset + (4 - ObjSize);
3130       }
3131       // The value of the object is its address.
3132       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3133       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3134       InVals.push_back(FIN);
3135       if (ObjSize==1 || ObjSize==2) {
3136         if (GPR_idx != Num_GPR_Regs) {
3137           unsigned VReg;
3138           if (isPPC64)
3139             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3140           else
3141             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3142           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3143           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3144           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3145                                             MachinePointerInfo(FuncArg),
3146                                             ObjType, false, false, 0);
3147           MemOps.push_back(Store);
3148           ++GPR_idx;
3149         }
3150
3151         ArgOffset += PtrByteSize;
3152
3153         continue;
3154       }
3155       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3156         // Store whatever pieces of the object are in registers
3157         // to memory.  ArgOffset will be the address of the beginning
3158         // of the object.
3159         if (GPR_idx != Num_GPR_Regs) {
3160           unsigned VReg;
3161           if (isPPC64)
3162             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3163           else
3164             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3165           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3166           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3167           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3168           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3169                                        MachinePointerInfo(FuncArg, j),
3170                                        false, false, 0);
3171           MemOps.push_back(Store);
3172           ++GPR_idx;
3173           ArgOffset += PtrByteSize;
3174         } else {
3175           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3176           break;
3177         }
3178       }
3179       continue;
3180     }
3181
3182     switch (ObjectVT.getSimpleVT().SimpleTy) {
3183     default: llvm_unreachable("Unhandled argument type!");
3184     case MVT::i1:
3185     case MVT::i32:
3186       if (!isPPC64) {
3187         if (GPR_idx != Num_GPR_Regs) {
3188           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3189           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3190
3191           if (ObjectVT == MVT::i1)
3192             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3193
3194           ++GPR_idx;
3195         } else {
3196           needsLoad = true;
3197           ArgSize = PtrByteSize;
3198         }
3199         // All int arguments reserve stack space in the Darwin ABI.
3200         ArgOffset += PtrByteSize;
3201         break;
3202       }
3203       // FALLTHROUGH
3204     case MVT::i64:  // PPC64
3205       if (GPR_idx != Num_GPR_Regs) {
3206         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3207         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3208
3209         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3210           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3211           // value to MVT::i64 and then truncate to the correct register size.
3212           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3213
3214         ++GPR_idx;
3215       } else {
3216         needsLoad = true;
3217         ArgSize = PtrByteSize;
3218       }
3219       // All int arguments reserve stack space in the Darwin ABI.
3220       ArgOffset += 8;
3221       break;
3222
3223     case MVT::f32:
3224     case MVT::f64:
3225       // Every 4 bytes of argument space consumes one of the GPRs available for
3226       // argument passing.
3227       if (GPR_idx != Num_GPR_Regs) {
3228         ++GPR_idx;
3229         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3230           ++GPR_idx;
3231       }
3232       if (FPR_idx != Num_FPR_Regs) {
3233         unsigned VReg;
3234
3235         if (ObjectVT == MVT::f32)
3236           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3237         else
3238           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3239
3240         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3241         ++FPR_idx;
3242       } else {
3243         needsLoad = true;
3244       }
3245
3246       // All FP arguments reserve stack space in the Darwin ABI.
3247       ArgOffset += isPPC64 ? 8 : ObjSize;
3248       break;
3249     case MVT::v4f32:
3250     case MVT::v4i32:
3251     case MVT::v8i16:
3252     case MVT::v16i8:
3253       // Note that vector arguments in registers don't reserve stack space,
3254       // except in varargs functions.
3255       if (VR_idx != Num_VR_Regs) {
3256         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3257         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3258         if (isVarArg) {
3259           while ((ArgOffset % 16) != 0) {
3260             ArgOffset += PtrByteSize;
3261             if (GPR_idx != Num_GPR_Regs)
3262               GPR_idx++;
3263           }
3264           ArgOffset += 16;
3265           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3266         }
3267         ++VR_idx;
3268       } else {
3269         if (!isVarArg && !isPPC64) {
3270           // Vectors go after all the nonvectors.
3271           CurArgOffset = VecArgOffset;
3272           VecArgOffset += 16;
3273         } else {
3274           // Vectors are aligned.
3275           ArgOffset = ((ArgOffset+15)/16)*16;
3276           CurArgOffset = ArgOffset;
3277           ArgOffset += 16;
3278         }
3279         needsLoad = true;
3280       }
3281       break;
3282     }
3283
3284     // We need to load the argument to a virtual register if we determined above
3285     // that we ran out of physical registers of the appropriate type.
3286     if (needsLoad) {
3287       int FI = MFI->CreateFixedObject(ObjSize,
3288                                       CurArgOffset + (ArgSize - ObjSize),
3289                                       isImmutable);
3290       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3291       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3292                            false, false, false, 0);
3293     }
3294
3295     InVals.push_back(ArgVal);
3296   }
3297
3298   // Allow for Altivec parameters at the end, if needed.
3299   if (nAltivecParamsAtEnd) {
3300     MinReservedArea = ((MinReservedArea+15)/16)*16;
3301     MinReservedArea += 16*nAltivecParamsAtEnd;
3302   }
3303
3304   // Area that is at least reserved in the caller of this function.
3305   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3306
3307   // Set the size that is at least reserved in caller of this function.  Tail
3308   // call optimized functions' reserved stack space needs to be aligned so that
3309   // taking the difference between two stack areas will result in an aligned
3310   // stack.
3311   MinReservedArea =
3312       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3313   FuncInfo->setMinReservedArea(MinReservedArea);
3314
3315   // If the function takes variable number of arguments, make a frame index for
3316   // the start of the first vararg value... for expansion of llvm.va_start.
3317   if (isVarArg) {
3318     int Depth = ArgOffset;
3319
3320     FuncInfo->setVarArgsFrameIndex(
3321       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3322                              Depth, true));
3323     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3324
3325     // If this function is vararg, store any remaining integer argument regs
3326     // to their spots on the stack so that they may be loaded by deferencing the
3327     // result of va_next.
3328     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3329       unsigned VReg;
3330
3331       if (isPPC64)
3332         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3333       else
3334         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3335
3336       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3337       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3338                                    MachinePointerInfo(), false, false, 0);
3339       MemOps.push_back(Store);
3340       // Increment the address by four for the next argument to store
3341       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3342       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3343     }
3344   }
3345
3346   if (!MemOps.empty())
3347     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3348
3349   return Chain;
3350 }
3351
3352 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3353 /// adjusted to accommodate the arguments for the tailcall.
3354 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3355                                    unsigned ParamSize) {
3356
3357   if (!isTailCall) return 0;
3358
3359   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3360   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3361   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3362   // Remember only if the new adjustement is bigger.
3363   if (SPDiff < FI->getTailCallSPDelta())
3364     FI->setTailCallSPDelta(SPDiff);
3365
3366   return SPDiff;
3367 }
3368
3369 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3370 /// for tail call optimization. Targets which want to do tail call
3371 /// optimization should implement this function.
3372 bool
3373 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3374                                                      CallingConv::ID CalleeCC,
3375                                                      bool isVarArg,
3376                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3377                                                      SelectionDAG& DAG) const {
3378   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3379     return false;
3380
3381   // Variable argument functions are not supported.
3382   if (isVarArg)
3383     return false;
3384
3385   MachineFunction &MF = DAG.getMachineFunction();
3386   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3387   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3388     // Functions containing by val parameters are not supported.
3389     for (unsigned i = 0; i != Ins.size(); i++) {
3390        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3391        if (Flags.isByVal()) return false;
3392     }
3393
3394     // Non-PIC/GOT tail calls are supported.
3395     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3396       return true;
3397
3398     // At the moment we can only do local tail calls (in same module, hidden
3399     // or protected) if we are generating PIC.
3400     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3401       return G->getGlobal()->hasHiddenVisibility()
3402           || G->getGlobal()->hasProtectedVisibility();
3403   }
3404
3405   return false;
3406 }
3407
3408 /// isCallCompatibleAddress - Return the immediate to use if the specified
3409 /// 32-bit value is representable in the immediate field of a BxA instruction.
3410 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3411   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3412   if (!C) return nullptr;
3413
3414   int Addr = C->getZExtValue();
3415   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3416       SignExtend32<26>(Addr) != Addr)
3417     return nullptr;  // Top 6 bits have to be sext of immediate.
3418
3419   return DAG.getConstant((int)C->getZExtValue() >> 2,
3420                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3421 }
3422
3423 namespace {
3424
3425 struct TailCallArgumentInfo {
3426   SDValue Arg;
3427   SDValue FrameIdxOp;
3428   int       FrameIdx;
3429
3430   TailCallArgumentInfo() : FrameIdx(0) {}
3431 };
3432
3433 }
3434
3435 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3436 static void
3437 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3438                                            SDValue Chain,
3439                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3440                    SmallVectorImpl<SDValue> &MemOpChains,
3441                    SDLoc dl) {
3442   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3443     SDValue Arg = TailCallArgs[i].Arg;
3444     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3445     int FI = TailCallArgs[i].FrameIdx;
3446     // Store relative to framepointer.
3447     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3448                                        MachinePointerInfo::getFixedStack(FI),
3449                                        false, false, 0));
3450   }
3451 }
3452
3453 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3454 /// the appropriate stack slot for the tail call optimized function call.
3455 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3456                                                MachineFunction &MF,
3457                                                SDValue Chain,
3458                                                SDValue OldRetAddr,
3459                                                SDValue OldFP,
3460                                                int SPDiff,
3461                                                bool isPPC64,
3462                                                bool isDarwinABI,
3463                                                SDLoc dl) {
3464   if (SPDiff) {
3465     // Calculate the new stack slot for the return address.
3466     int SlotSize = isPPC64 ? 8 : 4;
3467     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3468                                                                    isDarwinABI);
3469     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3470                                                           NewRetAddrLoc, true);
3471     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3472     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3473     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3474                          MachinePointerInfo::getFixedStack(NewRetAddr),
3475                          false, false, 0);
3476
3477     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3478     // slot as the FP is never overwritten.
3479     if (isDarwinABI) {
3480       int NewFPLoc =
3481         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3482       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3483                                                           true);
3484       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3485       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3486                            MachinePointerInfo::getFixedStack(NewFPIdx),
3487                            false, false, 0);
3488     }
3489   }
3490   return Chain;
3491 }
3492
3493 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3494 /// the position of the argument.
3495 static void
3496 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3497                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3498                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3499   int Offset = ArgOffset + SPDiff;
3500   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3501   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3502   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3503   SDValue FIN = DAG.getFrameIndex(FI, VT);
3504   TailCallArgumentInfo Info;
3505   Info.Arg = Arg;
3506   Info.FrameIdxOp = FIN;
3507   Info.FrameIdx = FI;
3508   TailCallArguments.push_back(Info);
3509 }
3510
3511 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3512 /// stack slot. Returns the chain as result and the loaded frame pointers in
3513 /// LROpOut/FPOpout. Used when tail calling.
3514 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3515                                                         int SPDiff,
3516                                                         SDValue Chain,
3517                                                         SDValue &LROpOut,
3518                                                         SDValue &FPOpOut,
3519                                                         bool isDarwinABI,
3520                                                         SDLoc dl) const {
3521   if (SPDiff) {
3522     // Load the LR and FP stack slot for later adjusting.
3523     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3524     LROpOut = getReturnAddrFrameIndex(DAG);
3525     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3526                           false, false, false, 0);
3527     Chain = SDValue(LROpOut.getNode(), 1);
3528
3529     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3530     // slot as the FP is never overwritten.
3531     if (isDarwinABI) {
3532       FPOpOut = getFramePointerFrameIndex(DAG);
3533       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3534                             false, false, false, 0);
3535       Chain = SDValue(FPOpOut.getNode(), 1);
3536     }
3537   }
3538   return Chain;
3539 }
3540
3541 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3542 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3543 /// specified by the specific parameter attribute. The copy will be passed as
3544 /// a byval function parameter.
3545 /// Sometimes what we are copying is the end of a larger object, the part that
3546 /// does not fit in registers.
3547 static SDValue
3548 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3549                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3550                           SDLoc dl) {
3551   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3552   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3553                        false, false, MachinePointerInfo(),
3554                        MachinePointerInfo());
3555 }
3556
3557 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3558 /// tail calls.
3559 static void
3560 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3561                  SDValue Arg, SDValue PtrOff, int SPDiff,
3562                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3563                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3564                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3565                  SDLoc dl) {
3566   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3567   if (!isTailCall) {
3568     if (isVector) {
3569       SDValue StackPtr;
3570       if (isPPC64)
3571         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3572       else
3573         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3574       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3575                            DAG.getConstant(ArgOffset, PtrVT));
3576     }
3577     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3578                                        MachinePointerInfo(), false, false, 0));
3579   // Calculate and remember argument location.
3580   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3581                                   TailCallArguments);
3582 }
3583
3584 static
3585 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3586                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3587                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3588                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3589   MachineFunction &MF = DAG.getMachineFunction();
3590
3591   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3592   // might overwrite each other in case of tail call optimization.
3593   SmallVector<SDValue, 8> MemOpChains2;
3594   // Do not flag preceding copytoreg stuff together with the following stuff.
3595   InFlag = SDValue();
3596   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3597                                     MemOpChains2, dl);
3598   if (!MemOpChains2.empty())
3599     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3600
3601   // Store the return address to the appropriate stack slot.
3602   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3603                                         isPPC64, isDarwinABI, dl);
3604
3605   // Emit callseq_end just before tailcall node.
3606   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3607                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3608   InFlag = Chain.getValue(1);
3609 }
3610
3611 // Is this global address that of a function that can be called by name? (as
3612 // opposed to something that must hold a descriptor for an indirect call).
3613 static bool isFunctionGlobalAddress(SDValue Callee) {
3614   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3615     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3616         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3617       return false;
3618
3619     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3620   }
3621
3622   return false;
3623 }
3624
3625 static
3626 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3627                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3628                      bool isTailCall, bool IsPatchPoint,
3629                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3630                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3631                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3632
3633   bool isPPC64 = Subtarget.isPPC64();
3634   bool isSVR4ABI = Subtarget.isSVR4ABI();
3635   bool isELFv2ABI = Subtarget.isELFv2ABI();
3636
3637   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3638   NodeTys.push_back(MVT::Other);   // Returns a chain
3639   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3640
3641   unsigned CallOpc = PPCISD::CALL;
3642
3643   bool needIndirectCall = true;
3644   if (!isSVR4ABI || !isPPC64)
3645     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3646       // If this is an absolute destination address, use the munged value.
3647       Callee = SDValue(Dest, 0);
3648       needIndirectCall = false;
3649     }
3650
3651   if (isFunctionGlobalAddress(Callee)) {
3652     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3653     // A call to a TLS address is actually an indirect call to a
3654     // thread-specific pointer.
3655     unsigned OpFlags = 0;
3656     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3657          (Subtarget.getTargetTriple().isMacOSX() &&
3658           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3659          (G->getGlobal()->isDeclaration() ||
3660           G->getGlobal()->isWeakForLinker())) ||
3661         (Subtarget.isTargetELF() && !isPPC64 &&
3662          !G->getGlobal()->hasLocalLinkage() &&
3663          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3664       // PC-relative references to external symbols should go through $stub,
3665       // unless we're building with the leopard linker or later, which
3666       // automatically synthesizes these stubs.
3667       OpFlags = PPCII::MO_PLT_OR_STUB;
3668     }
3669
3670     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3671     // every direct call is) turn it into a TargetGlobalAddress /
3672     // TargetExternalSymbol node so that legalize doesn't hack it.
3673     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3674                                         Callee.getValueType(), 0, OpFlags);
3675     needIndirectCall = false;
3676   }
3677
3678   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3679     unsigned char OpFlags = 0;
3680
3681     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3682          (Subtarget.getTargetTriple().isMacOSX() &&
3683           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3684         (Subtarget.isTargetELF() && !isPPC64 &&
3685          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3686       // PC-relative references to external symbols should go through $stub,
3687       // unless we're building with the leopard linker or later, which
3688       // automatically synthesizes these stubs.
3689       OpFlags = PPCII::MO_PLT_OR_STUB;
3690     }
3691
3692     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3693                                          OpFlags);
3694     needIndirectCall = false;
3695   }
3696
3697   if (IsPatchPoint) {
3698     // We'll form an invalid direct call when lowering a patchpoint; the full
3699     // sequence for an indirect call is complicated, and many of the
3700     // instructions introduced might have side effects (and, thus, can't be
3701     // removed later). The call itself will be removed as soon as the
3702     // argument/return lowering is complete, so the fact that it has the wrong
3703     // kind of operands should not really matter.
3704     needIndirectCall = false;
3705   }
3706
3707   if (needIndirectCall) {
3708     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3709     // to do the call, we can't use PPCISD::CALL.
3710     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3711
3712     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3713       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3714       // entry point, but to the function descriptor (the function entry point
3715       // address is part of the function descriptor though).
3716       // The function descriptor is a three doubleword structure with the
3717       // following fields: function entry point, TOC base address and
3718       // environment pointer.
3719       // Thus for a call through a function pointer, the following actions need
3720       // to be performed:
3721       //   1. Save the TOC of the caller in the TOC save area of its stack
3722       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3723       //   2. Load the address of the function entry point from the function
3724       //      descriptor.
3725       //   3. Load the TOC of the callee from the function descriptor into r2.
3726       //   4. Load the environment pointer from the function descriptor into
3727       //      r11.
3728       //   5. Branch to the function entry point address.
3729       //   6. On return of the callee, the TOC of the caller needs to be
3730       //      restored (this is done in FinishCall()).
3731       //
3732       // The loads are scheduled at the beginning of the call sequence, and the
3733       // register copies are flagged together to ensure that no other
3734       // operations can be scheduled in between. E.g. without flagging the
3735       // copies together, a TOC access in the caller could be scheduled between
3736       // the assignment of the callee TOC and the branch to the callee, which
3737       // results in the TOC access going through the TOC of the callee instead
3738       // of going through the TOC of the caller, which leads to incorrect code.
3739
3740       // Load the address of the function entry point from the function
3741       // descriptor.
3742       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
3743       if (LDChain.getValueType() == MVT::Glue)
3744         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
3745
3746       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
3747
3748       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
3749       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
3750                                         false, false, LoadsInv, 8);
3751
3752       // Load environment pointer into r11.
3753       SDValue PtrOff = DAG.getIntPtrConstant(16);
3754       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3755       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
3756                                        MPI.getWithOffset(16), false, false,
3757                                        LoadsInv, 8);
3758
3759       SDValue TOCOff = DAG.getIntPtrConstant(8);
3760       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3761       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
3762                                    MPI.getWithOffset(8), false, false,
3763                                    LoadsInv, 8);
3764
3765       setUsesTOCBasePtr(DAG);
3766       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
3767                                         InFlag);
3768       Chain = TOCVal.getValue(0);
3769       InFlag = TOCVal.getValue(1);
3770
3771       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3772                                         InFlag);
3773
3774       Chain = EnvVal.getValue(0);
3775       InFlag = EnvVal.getValue(1);
3776
3777       MTCTROps[0] = Chain;
3778       MTCTROps[1] = LoadFuncPtr;
3779       MTCTROps[2] = InFlag;
3780     }
3781
3782     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3783                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3784     InFlag = Chain.getValue(1);
3785
3786     NodeTys.clear();
3787     NodeTys.push_back(MVT::Other);
3788     NodeTys.push_back(MVT::Glue);
3789     Ops.push_back(Chain);
3790     CallOpc = PPCISD::BCTRL;
3791     Callee.setNode(nullptr);
3792     // Add use of X11 (holding environment pointer)
3793     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3794       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3795     // Add CTR register as callee so a bctr can be emitted later.
3796     if (isTailCall)
3797       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3798   }
3799
3800   // If this is a direct call, pass the chain and the callee.
3801   if (Callee.getNode()) {
3802     Ops.push_back(Chain);
3803     Ops.push_back(Callee);
3804   }
3805   // If this is a tail call add stack pointer delta.
3806   if (isTailCall)
3807     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3808
3809   // Add argument registers to the end of the list so that they are known live
3810   // into the call.
3811   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3812     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3813                                   RegsToPass[i].second.getValueType()));
3814
3815   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
3816   // into the call.
3817   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
3818     setUsesTOCBasePtr(DAG);
3819     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3820   }
3821
3822   return CallOpc;
3823 }
3824
3825 static
3826 bool isLocalCall(const SDValue &Callee)
3827 {
3828   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3829     return !G->getGlobal()->isDeclaration() &&
3830            !G->getGlobal()->isWeakForLinker();
3831   return false;
3832 }
3833
3834 SDValue
3835 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3836                                    CallingConv::ID CallConv, bool isVarArg,
3837                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3838                                    SDLoc dl, SelectionDAG &DAG,
3839                                    SmallVectorImpl<SDValue> &InVals) const {
3840
3841   SmallVector<CCValAssign, 16> RVLocs;
3842   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3843                     *DAG.getContext());
3844   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3845
3846   // Copy all of the result registers out of their specified physreg.
3847   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3848     CCValAssign &VA = RVLocs[i];
3849     assert(VA.isRegLoc() && "Can only return in registers!");
3850
3851     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3852                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3853     Chain = Val.getValue(1);
3854     InFlag = Val.getValue(2);
3855
3856     switch (VA.getLocInfo()) {
3857     default: llvm_unreachable("Unknown loc info!");
3858     case CCValAssign::Full: break;
3859     case CCValAssign::AExt:
3860       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3861       break;
3862     case CCValAssign::ZExt:
3863       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3864                         DAG.getValueType(VA.getValVT()));
3865       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3866       break;
3867     case CCValAssign::SExt:
3868       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3869                         DAG.getValueType(VA.getValVT()));
3870       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3871       break;
3872     }
3873
3874     InVals.push_back(Val);
3875   }
3876
3877   return Chain;
3878 }
3879
3880 SDValue
3881 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3882                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
3883                               SelectionDAG &DAG,
3884                               SmallVector<std::pair<unsigned, SDValue>, 8>
3885                                 &RegsToPass,
3886                               SDValue InFlag, SDValue Chain,
3887                               SDValue CallSeqStart, SDValue &Callee,
3888                               int SPDiff, unsigned NumBytes,
3889                               const SmallVectorImpl<ISD::InputArg> &Ins,
3890                               SmallVectorImpl<SDValue> &InVals,
3891                               ImmutableCallSite *CS) const {
3892
3893   bool isELFv2ABI = Subtarget.isELFv2ABI();
3894   std::vector<EVT> NodeTys;
3895   SmallVector<SDValue, 8> Ops;
3896   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
3897                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
3898                                  Ops, NodeTys, CS, Subtarget);
3899
3900   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3901   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3902     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3903
3904   // When performing tail call optimization the callee pops its arguments off
3905   // the stack. Account for this here so these bytes can be pushed back on in
3906   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3907   int BytesCalleePops =
3908     (CallConv == CallingConv::Fast &&
3909      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3910
3911   // Add a register mask operand representing the call-preserved registers.
3912   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3913   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3914   assert(Mask && "Missing call preserved mask for calling convention");
3915   Ops.push_back(DAG.getRegisterMask(Mask));
3916
3917   if (InFlag.getNode())
3918     Ops.push_back(InFlag);
3919
3920   // Emit tail call.
3921   if (isTailCall) {
3922     assert(((Callee.getOpcode() == ISD::Register &&
3923              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3924             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3925             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3926             isa<ConstantSDNode>(Callee)) &&
3927     "Expecting an global address, external symbol, absolute value or register");
3928
3929     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3930   }
3931
3932   // Add a NOP immediately after the branch instruction when using the 64-bit
3933   // SVR4 ABI. At link time, if caller and callee are in a different module and
3934   // thus have a different TOC, the call will be replaced with a call to a stub
3935   // function which saves the current TOC, loads the TOC of the callee and
3936   // branches to the callee. The NOP will be replaced with a load instruction
3937   // which restores the TOC of the caller from the TOC save slot of the current
3938   // stack frame. If caller and callee belong to the same module (and have the
3939   // same TOC), the NOP will remain unchanged.
3940
3941   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
3942       !IsPatchPoint) {
3943     if (CallOpc == PPCISD::BCTRL) {
3944       // This is a call through a function pointer.
3945       // Restore the caller TOC from the save area into R2.
3946       // See PrepareCall() for more information about calls through function
3947       // pointers in the 64-bit SVR4 ABI.
3948       // We are using a target-specific load with r2 hard coded, because the
3949       // result of a target-independent load would never go directly into r2,
3950       // since r2 is a reserved register (which prevents the register allocator
3951       // from allocating it), resulting in an additional register being
3952       // allocated and an unnecessary move instruction being generated.
3953       CallOpc = PPCISD::BCTRL_LOAD_TOC;
3954
3955       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3956       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3957       unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3958       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3959       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3960
3961       // The address needs to go after the chain input but before the flag (or
3962       // any other variadic arguments).
3963       Ops.insert(std::next(Ops.begin()), AddTOC);
3964     } else if ((CallOpc == PPCISD::CALL) &&
3965                (!isLocalCall(Callee) ||
3966                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
3967       // Otherwise insert NOP for non-local calls.
3968       CallOpc = PPCISD::CALL_NOP;
3969   }
3970
3971   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3972   InFlag = Chain.getValue(1);
3973
3974   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3975                              DAG.getIntPtrConstant(BytesCalleePops, true),
3976                              InFlag, dl);
3977   if (!Ins.empty())
3978     InFlag = Chain.getValue(1);
3979
3980   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3981                          Ins, dl, DAG, InVals);
3982 }
3983
3984 SDValue
3985 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3986                              SmallVectorImpl<SDValue> &InVals) const {
3987   SelectionDAG &DAG                     = CLI.DAG;
3988   SDLoc &dl                             = CLI.DL;
3989   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3990   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3991   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3992   SDValue Chain                         = CLI.Chain;
3993   SDValue Callee                        = CLI.Callee;
3994   bool &isTailCall                      = CLI.IsTailCall;
3995   CallingConv::ID CallConv              = CLI.CallConv;
3996   bool isVarArg                         = CLI.IsVarArg;
3997   bool IsPatchPoint                     = CLI.IsPatchPoint;
3998   ImmutableCallSite *CS                 = CLI.CS;
3999
4000   if (isTailCall)
4001     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4002                                                    Ins, DAG);
4003
4004   if (!isTailCall && CS && CS->isMustTailCall())
4005     report_fatal_error("failed to perform tail call elimination on a call "
4006                        "site marked musttail");
4007
4008   if (Subtarget.isSVR4ABI()) {
4009     if (Subtarget.isPPC64())
4010       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4011                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4012                               dl, DAG, InVals, CS);
4013     else
4014       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4015                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4016                               dl, DAG, InVals, CS);
4017   }
4018
4019   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4020                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4021                           dl, DAG, InVals, CS);
4022 }
4023
4024 SDValue
4025 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4026                                     CallingConv::ID CallConv, bool isVarArg,
4027                                     bool isTailCall, bool IsPatchPoint,
4028                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4029                                     const SmallVectorImpl<SDValue> &OutVals,
4030                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4031                                     SDLoc dl, SelectionDAG &DAG,
4032                                     SmallVectorImpl<SDValue> &InVals,
4033                                     ImmutableCallSite *CS) const {
4034   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4035   // of the 32-bit SVR4 ABI stack frame layout.
4036
4037   assert((CallConv == CallingConv::C ||
4038           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4039
4040   unsigned PtrByteSize = 4;
4041
4042   MachineFunction &MF = DAG.getMachineFunction();
4043
4044   // Mark this function as potentially containing a function that contains a
4045   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4046   // and restoring the callers stack pointer in this functions epilog. This is
4047   // done because by tail calling the called function might overwrite the value
4048   // in this function's (MF) stack pointer stack slot 0(SP).
4049   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4050       CallConv == CallingConv::Fast)
4051     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4052
4053   // Count how many bytes are to be pushed on the stack, including the linkage
4054   // area, parameter list area and the part of the local variable space which
4055   // contains copies of aggregates which are passed by value.
4056
4057   // Assign locations to all of the outgoing arguments.
4058   SmallVector<CCValAssign, 16> ArgLocs;
4059   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4060                  *DAG.getContext());
4061
4062   // Reserve space for the linkage area on the stack.
4063   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4064                        PtrByteSize);
4065
4066   if (isVarArg) {
4067     // Handle fixed and variable vector arguments differently.
4068     // Fixed vector arguments go into registers as long as registers are
4069     // available. Variable vector arguments always go into memory.
4070     unsigned NumArgs = Outs.size();
4071
4072     for (unsigned i = 0; i != NumArgs; ++i) {
4073       MVT ArgVT = Outs[i].VT;
4074       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4075       bool Result;
4076
4077       if (Outs[i].IsFixed) {
4078         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4079                                CCInfo);
4080       } else {
4081         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4082                                       ArgFlags, CCInfo);
4083       }
4084
4085       if (Result) {
4086 #ifndef NDEBUG
4087         errs() << "Call operand #" << i << " has unhandled type "
4088              << EVT(ArgVT).getEVTString() << "\n";
4089 #endif
4090         llvm_unreachable(nullptr);
4091       }
4092     }
4093   } else {
4094     // All arguments are treated the same.
4095     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4096   }
4097
4098   // Assign locations to all of the outgoing aggregate by value arguments.
4099   SmallVector<CCValAssign, 16> ByValArgLocs;
4100   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4101                       ByValArgLocs, *DAG.getContext());
4102
4103   // Reserve stack space for the allocations in CCInfo.
4104   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4105
4106   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4107
4108   // Size of the linkage area, parameter list area and the part of the local
4109   // space variable where copies of aggregates which are passed by value are
4110   // stored.
4111   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4112
4113   // Calculate by how many bytes the stack has to be adjusted in case of tail
4114   // call optimization.
4115   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4116
4117   // Adjust the stack pointer for the new arguments...
4118   // These operations are automatically eliminated by the prolog/epilog pass
4119   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4120                                dl);
4121   SDValue CallSeqStart = Chain;
4122
4123   // Load the return address and frame pointer so it can be moved somewhere else
4124   // later.
4125   SDValue LROp, FPOp;
4126   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4127                                        dl);
4128
4129   // Set up a copy of the stack pointer for use loading and storing any
4130   // arguments that may not fit in the registers available for argument
4131   // passing.
4132   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4133
4134   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4135   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4136   SmallVector<SDValue, 8> MemOpChains;
4137
4138   bool seenFloatArg = false;
4139   // Walk the register/memloc assignments, inserting copies/loads.
4140   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4141        i != e;
4142        ++i) {
4143     CCValAssign &VA = ArgLocs[i];
4144     SDValue Arg = OutVals[i];
4145     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4146
4147     if (Flags.isByVal()) {
4148       // Argument is an aggregate which is passed by value, thus we need to
4149       // create a copy of it in the local variable space of the current stack
4150       // frame (which is the stack frame of the caller) and pass the address of
4151       // this copy to the callee.
4152       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4153       CCValAssign &ByValVA = ByValArgLocs[j++];
4154       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4155
4156       // Memory reserved in the local variable space of the callers stack frame.
4157       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4158
4159       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4160       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4161
4162       // Create a copy of the argument in the local area of the current
4163       // stack frame.
4164       SDValue MemcpyCall =
4165         CreateCopyOfByValArgument(Arg, PtrOff,
4166                                   CallSeqStart.getNode()->getOperand(0),
4167                                   Flags, DAG, dl);
4168
4169       // This must go outside the CALLSEQ_START..END.
4170       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4171                            CallSeqStart.getNode()->getOperand(1),
4172                            SDLoc(MemcpyCall));
4173       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4174                              NewCallSeqStart.getNode());
4175       Chain = CallSeqStart = NewCallSeqStart;
4176
4177       // Pass the address of the aggregate copy on the stack either in a
4178       // physical register or in the parameter list area of the current stack
4179       // frame to the callee.
4180       Arg = PtrOff;
4181     }
4182
4183     if (VA.isRegLoc()) {
4184       if (Arg.getValueType() == MVT::i1)
4185         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4186
4187       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4188       // Put argument in a physical register.
4189       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4190     } else {
4191       // Put argument in the parameter list area of the current stack frame.
4192       assert(VA.isMemLoc());
4193       unsigned LocMemOffset = VA.getLocMemOffset();
4194
4195       if (!isTailCall) {
4196         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4197         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4198
4199         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4200                                            MachinePointerInfo(),
4201                                            false, false, 0));
4202       } else {
4203         // Calculate and remember argument location.
4204         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4205                                  TailCallArguments);
4206       }
4207     }
4208   }
4209
4210   if (!MemOpChains.empty())
4211     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4212
4213   // Build a sequence of copy-to-reg nodes chained together with token chain
4214   // and flag operands which copy the outgoing args into the appropriate regs.
4215   SDValue InFlag;
4216   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4217     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4218                              RegsToPass[i].second, InFlag);
4219     InFlag = Chain.getValue(1);
4220   }
4221
4222   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4223   // registers.
4224   if (isVarArg) {
4225     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4226     SDValue Ops[] = { Chain, InFlag };
4227
4228     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4229                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4230
4231     InFlag = Chain.getValue(1);
4232   }
4233
4234   if (isTailCall)
4235     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4236                     false, TailCallArguments);
4237
4238   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4239                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4240                     NumBytes, Ins, InVals, CS);
4241 }
4242
4243 // Copy an argument into memory, being careful to do this outside the
4244 // call sequence for the call to which the argument belongs.
4245 SDValue
4246 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4247                                               SDValue CallSeqStart,
4248                                               ISD::ArgFlagsTy Flags,
4249                                               SelectionDAG &DAG,
4250                                               SDLoc dl) const {
4251   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4252                         CallSeqStart.getNode()->getOperand(0),
4253                         Flags, DAG, dl);
4254   // The MEMCPY must go outside the CALLSEQ_START..END.
4255   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4256                              CallSeqStart.getNode()->getOperand(1),
4257                              SDLoc(MemcpyCall));
4258   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4259                          NewCallSeqStart.getNode());
4260   return NewCallSeqStart;
4261 }
4262
4263 SDValue
4264 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4265                                     CallingConv::ID CallConv, bool isVarArg,
4266                                     bool isTailCall, bool IsPatchPoint,
4267                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4268                                     const SmallVectorImpl<SDValue> &OutVals,
4269                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4270                                     SDLoc dl, SelectionDAG &DAG,
4271                                     SmallVectorImpl<SDValue> &InVals,
4272                                     ImmutableCallSite *CS) const {
4273
4274   bool isELFv2ABI = Subtarget.isELFv2ABI();
4275   bool isLittleEndian = Subtarget.isLittleEndian();
4276   unsigned NumOps = Outs.size();
4277
4278   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4279   unsigned PtrByteSize = 8;
4280
4281   MachineFunction &MF = DAG.getMachineFunction();
4282
4283   // Mark this function as potentially containing a function that contains a
4284   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4285   // and restoring the callers stack pointer in this functions epilog. This is
4286   // done because by tail calling the called function might overwrite the value
4287   // in this function's (MF) stack pointer stack slot 0(SP).
4288   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4289       CallConv == CallingConv::Fast)
4290     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4291
4292   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4293          "fastcc not supported on varargs functions");
4294
4295   // Count how many bytes are to be pushed on the stack, including the linkage
4296   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4297   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4298   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4299   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4300                                                           isELFv2ABI);
4301   unsigned NumBytes = LinkageSize;
4302   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4303
4304   static const MCPhysReg GPR[] = {
4305     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4306     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4307   };
4308   static const MCPhysReg *FPR = GetFPR();
4309
4310   static const MCPhysReg VR[] = {
4311     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4312     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4313   };
4314   static const MCPhysReg VSRH[] = {
4315     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4316     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4317   };
4318
4319   const unsigned NumGPRs = array_lengthof(GPR);
4320   const unsigned NumFPRs = 13;
4321   const unsigned NumVRs  = array_lengthof(VR);
4322
4323   // When using the fast calling convention, we don't provide backing for
4324   // arguments that will be in registers.
4325   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4326
4327   // Add up all the space actually used.
4328   for (unsigned i = 0; i != NumOps; ++i) {
4329     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4330     EVT ArgVT = Outs[i].VT;
4331     EVT OrigVT = Outs[i].ArgVT;
4332
4333     if (CallConv == CallingConv::Fast) {
4334       if (Flags.isByVal())
4335         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4336       else
4337         switch (ArgVT.getSimpleVT().SimpleTy) {
4338         default: llvm_unreachable("Unexpected ValueType for argument!");
4339         case MVT::i1:
4340         case MVT::i32:
4341         case MVT::i64:
4342           if (++NumGPRsUsed <= NumGPRs)
4343             continue;
4344           break;
4345         case MVT::f32:
4346         case MVT::f64:
4347           if (++NumFPRsUsed <= NumFPRs)
4348             continue;
4349           break;
4350         case MVT::v4f32:
4351         case MVT::v4i32:
4352         case MVT::v8i16:
4353         case MVT::v16i8:
4354         case MVT::v2f64:
4355         case MVT::v2i64:
4356           if (++NumVRsUsed <= NumVRs)
4357             continue;
4358           break;
4359         }
4360     }
4361
4362     /* Respect alignment of argument on the stack.  */
4363     unsigned Align =
4364       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4365     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4366
4367     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4368     if (Flags.isInConsecutiveRegsLast())
4369       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4370   }
4371
4372   unsigned NumBytesActuallyUsed = NumBytes;
4373
4374   // The prolog code of the callee may store up to 8 GPR argument registers to
4375   // the stack, allowing va_start to index over them in memory if its varargs.
4376   // Because we cannot tell if this is needed on the caller side, we have to
4377   // conservatively assume that it is needed.  As such, make sure we have at
4378   // least enough stack space for the caller to store the 8 GPRs.
4379   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4380   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4381
4382   // Tail call needs the stack to be aligned.
4383   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4384       CallConv == CallingConv::Fast)
4385     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4386
4387   // Calculate by how many bytes the stack has to be adjusted in case of tail
4388   // call optimization.
4389   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4390
4391   // To protect arguments on the stack from being clobbered in a tail call,
4392   // force all the loads to happen before doing any other lowering.
4393   if (isTailCall)
4394     Chain = DAG.getStackArgumentTokenFactor(Chain);
4395
4396   // Adjust the stack pointer for the new arguments...
4397   // These operations are automatically eliminated by the prolog/epilog pass
4398   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4399                                dl);
4400   SDValue CallSeqStart = Chain;
4401
4402   // Load the return address and frame pointer so it can be move somewhere else
4403   // later.
4404   SDValue LROp, FPOp;
4405   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4406                                        dl);
4407
4408   // Set up a copy of the stack pointer for use loading and storing any
4409   // arguments that may not fit in the registers available for argument
4410   // passing.
4411   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4412
4413   // Figure out which arguments are going to go in registers, and which in
4414   // memory.  Also, if this is a vararg function, floating point operations
4415   // must be stored to our stack, and loaded into integer regs as well, if
4416   // any integer regs are available for argument passing.
4417   unsigned ArgOffset = LinkageSize;
4418
4419   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4420   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4421
4422   SmallVector<SDValue, 8> MemOpChains;
4423   for (unsigned i = 0; i != NumOps; ++i) {
4424     SDValue Arg = OutVals[i];
4425     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4426     EVT ArgVT = Outs[i].VT;
4427     EVT OrigVT = Outs[i].ArgVT;
4428
4429     // PtrOff will be used to store the current argument to the stack if a
4430     // register cannot be found for it.
4431     SDValue PtrOff;
4432
4433     // We re-align the argument offset for each argument, except when using the
4434     // fast calling convention, when we need to make sure we do that only when
4435     // we'll actually use a stack slot.
4436     auto ComputePtrOff = [&]() {
4437       /* Respect alignment of argument on the stack.  */
4438       unsigned Align =
4439         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4440       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4441
4442       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4443
4444       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4445     };
4446
4447     if (CallConv != CallingConv::Fast) {
4448       ComputePtrOff();
4449
4450       /* Compute GPR index associated with argument offset.  */
4451       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4452       GPR_idx = std::min(GPR_idx, NumGPRs);
4453     }
4454
4455     // Promote integers to 64-bit values.
4456     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4457       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4458       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4459       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4460     }
4461
4462     // FIXME memcpy is used way more than necessary.  Correctness first.
4463     // Note: "by value" is code for passing a structure by value, not
4464     // basic types.
4465     if (Flags.isByVal()) {
4466       // Note: Size includes alignment padding, so
4467       //   struct x { short a; char b; }
4468       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4469       // These are the proper values we need for right-justifying the
4470       // aggregate in a parameter register.
4471       unsigned Size = Flags.getByValSize();
4472
4473       // An empty aggregate parameter takes up no storage and no
4474       // registers.
4475       if (Size == 0)
4476         continue;
4477
4478       if (CallConv == CallingConv::Fast)
4479         ComputePtrOff();
4480
4481       // All aggregates smaller than 8 bytes must be passed right-justified.
4482       if (Size==1 || Size==2 || Size==4) {
4483         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4484         if (GPR_idx != NumGPRs) {
4485           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4486                                         MachinePointerInfo(), VT,
4487                                         false, false, false, 0);
4488           MemOpChains.push_back(Load.getValue(1));
4489           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4490
4491           ArgOffset += PtrByteSize;
4492           continue;
4493         }
4494       }
4495
4496       if (GPR_idx == NumGPRs && Size < 8) {
4497         SDValue AddPtr = PtrOff;
4498         if (!isLittleEndian) {
4499           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4500                                           PtrOff.getValueType());
4501           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4502         }
4503         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4504                                                           CallSeqStart,
4505                                                           Flags, DAG, dl);
4506         ArgOffset += PtrByteSize;
4507         continue;
4508       }
4509       // Copy entire object into memory.  There are cases where gcc-generated
4510       // code assumes it is there, even if it could be put entirely into
4511       // registers.  (This is not what the doc says.)
4512
4513       // FIXME: The above statement is likely due to a misunderstanding of the
4514       // documents.  All arguments must be copied into the parameter area BY
4515       // THE CALLEE in the event that the callee takes the address of any
4516       // formal argument.  That has not yet been implemented.  However, it is
4517       // reasonable to use the stack area as a staging area for the register
4518       // load.
4519
4520       // Skip this for small aggregates, as we will use the same slot for a
4521       // right-justified copy, below.
4522       if (Size >= 8)
4523         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4524                                                           CallSeqStart,
4525                                                           Flags, DAG, dl);
4526
4527       // When a register is available, pass a small aggregate right-justified.
4528       if (Size < 8 && GPR_idx != NumGPRs) {
4529         // The easiest way to get this right-justified in a register
4530         // is to copy the structure into the rightmost portion of a
4531         // local variable slot, then load the whole slot into the
4532         // register.
4533         // FIXME: The memcpy seems to produce pretty awful code for
4534         // small aggregates, particularly for packed ones.
4535         // FIXME: It would be preferable to use the slot in the
4536         // parameter save area instead of a new local variable.
4537         SDValue AddPtr = PtrOff;
4538         if (!isLittleEndian) {
4539           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4540           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4541         }
4542         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4543                                                           CallSeqStart,
4544                                                           Flags, DAG, dl);
4545
4546         // Load the slot into the register.
4547         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4548                                    MachinePointerInfo(),
4549                                    false, false, false, 0);
4550         MemOpChains.push_back(Load.getValue(1));
4551         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4552
4553         // Done with this argument.
4554         ArgOffset += PtrByteSize;
4555         continue;
4556       }
4557
4558       // For aggregates larger than PtrByteSize, copy the pieces of the
4559       // object that fit into registers from the parameter save area.
4560       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4561         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4562         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4563         if (GPR_idx != NumGPRs) {
4564           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4565                                      MachinePointerInfo(),
4566                                      false, false, false, 0);
4567           MemOpChains.push_back(Load.getValue(1));
4568           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4569           ArgOffset += PtrByteSize;
4570         } else {
4571           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4572           break;
4573         }
4574       }
4575       continue;
4576     }
4577
4578     switch (Arg.getSimpleValueType().SimpleTy) {
4579     default: llvm_unreachable("Unexpected ValueType for argument!");
4580     case MVT::i1:
4581     case MVT::i32:
4582     case MVT::i64:
4583       // These can be scalar arguments or elements of an integer array type
4584       // passed directly.  Clang may use those instead of "byval" aggregate
4585       // types to avoid forcing arguments to memory unnecessarily.
4586       if (GPR_idx != NumGPRs) {
4587         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4588       } else {
4589         if (CallConv == CallingConv::Fast)
4590           ComputePtrOff();
4591
4592         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4593                          true, isTailCall, false, MemOpChains,
4594                          TailCallArguments, dl);
4595         if (CallConv == CallingConv::Fast)
4596           ArgOffset += PtrByteSize;
4597       }
4598       if (CallConv != CallingConv::Fast)
4599         ArgOffset += PtrByteSize;
4600       break;
4601     case MVT::f32:
4602     case MVT::f64: {
4603       // These can be scalar arguments or elements of a float array type
4604       // passed directly.  The latter are used to implement ELFv2 homogenous
4605       // float aggregates.
4606
4607       // Named arguments go into FPRs first, and once they overflow, the
4608       // remaining arguments go into GPRs and then the parameter save area.
4609       // Unnamed arguments for vararg functions always go to GPRs and
4610       // then the parameter save area.  For now, put all arguments to vararg
4611       // routines always in both locations (FPR *and* GPR or stack slot).
4612       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4613       bool NeededLoad = false;
4614
4615       // First load the argument into the next available FPR.
4616       if (FPR_idx != NumFPRs)
4617         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4618
4619       // Next, load the argument into GPR or stack slot if needed.
4620       if (!NeedGPROrStack)
4621         ;
4622       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4623         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4624         // once we support fp <-> gpr moves.
4625
4626         // In the non-vararg case, this can only ever happen in the
4627         // presence of f32 array types, since otherwise we never run
4628         // out of FPRs before running out of GPRs.
4629         SDValue ArgVal;
4630
4631         // Double values are always passed in a single GPR.
4632         if (Arg.getValueType() != MVT::f32) {
4633           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4634
4635         // Non-array float values are extended and passed in a GPR.
4636         } else if (!Flags.isInConsecutiveRegs()) {
4637           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4638           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4639
4640         // If we have an array of floats, we collect every odd element
4641         // together with its predecessor into one GPR.
4642         } else if (ArgOffset % PtrByteSize != 0) {
4643           SDValue Lo, Hi;
4644           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4645           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4646           if (!isLittleEndian)
4647             std::swap(Lo, Hi);
4648           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4649
4650         // The final element, if even, goes into the first half of a GPR.
4651         } else if (Flags.isInConsecutiveRegsLast()) {
4652           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4653           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4654           if (!isLittleEndian)
4655             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4656                                  DAG.getConstant(32, MVT::i32));
4657
4658         // Non-final even elements are skipped; they will be handled
4659         // together the with subsequent argument on the next go-around.
4660         } else
4661           ArgVal = SDValue();
4662
4663         if (ArgVal.getNode())
4664           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4665       } else {
4666         if (CallConv == CallingConv::Fast)
4667           ComputePtrOff();
4668
4669         // Single-precision floating-point values are mapped to the
4670         // second (rightmost) word of the stack doubleword.
4671         if (Arg.getValueType() == MVT::f32 &&
4672             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4673           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4674           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4675         }
4676
4677         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4678                          true, isTailCall, false, MemOpChains,
4679                          TailCallArguments, dl);
4680
4681         NeededLoad = true;
4682       }
4683       // When passing an array of floats, the array occupies consecutive
4684       // space in the argument area; only round up to the next doubleword
4685       // at the end of the array.  Otherwise, each float takes 8 bytes.
4686       if (CallConv != CallingConv::Fast || NeededLoad) {
4687         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4688                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4689         if (Flags.isInConsecutiveRegsLast())
4690           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4691       }
4692       break;
4693     }
4694     case MVT::v4f32:
4695     case MVT::v4i32:
4696     case MVT::v8i16:
4697     case MVT::v16i8:
4698     case MVT::v2f64:
4699     case MVT::v2i64:
4700       // These can be scalar arguments or elements of a vector array type
4701       // passed directly.  The latter are used to implement ELFv2 homogenous
4702       // vector aggregates.
4703
4704       // For a varargs call, named arguments go into VRs or on the stack as
4705       // usual; unnamed arguments always go to the stack or the corresponding
4706       // GPRs when within range.  For now, we always put the value in both
4707       // locations (or even all three).
4708       if (isVarArg) {
4709         // We could elide this store in the case where the object fits
4710         // entirely in R registers.  Maybe later.
4711         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4712                                      MachinePointerInfo(), false, false, 0);
4713         MemOpChains.push_back(Store);
4714         if (VR_idx != NumVRs) {
4715           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4716                                      MachinePointerInfo(),
4717                                      false, false, false, 0);
4718           MemOpChains.push_back(Load.getValue(1));
4719
4720           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4721                            Arg.getSimpleValueType() == MVT::v2i64) ?
4722                           VSRH[VR_idx] : VR[VR_idx];
4723           ++VR_idx;
4724
4725           RegsToPass.push_back(std::make_pair(VReg, Load));
4726         }
4727         ArgOffset += 16;
4728         for (unsigned i=0; i<16; i+=PtrByteSize) {
4729           if (GPR_idx == NumGPRs)
4730             break;
4731           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4732                                   DAG.getConstant(i, PtrVT));
4733           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4734                                      false, false, false, 0);
4735           MemOpChains.push_back(Load.getValue(1));
4736           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4737         }
4738         break;
4739       }
4740
4741       // Non-varargs Altivec params go into VRs or on the stack.
4742       if (VR_idx != NumVRs) {
4743         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4744                          Arg.getSimpleValueType() == MVT::v2i64) ?
4745                         VSRH[VR_idx] : VR[VR_idx];
4746         ++VR_idx;
4747
4748         RegsToPass.push_back(std::make_pair(VReg, Arg));
4749       } else {
4750         if (CallConv == CallingConv::Fast)
4751           ComputePtrOff();
4752
4753         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4754                          true, isTailCall, true, MemOpChains,
4755                          TailCallArguments, dl);
4756         if (CallConv == CallingConv::Fast)
4757           ArgOffset += 16;
4758       }
4759
4760       if (CallConv != CallingConv::Fast)
4761         ArgOffset += 16;
4762       break;
4763     }
4764   }
4765
4766   assert(NumBytesActuallyUsed == ArgOffset);
4767   (void)NumBytesActuallyUsed;
4768
4769   if (!MemOpChains.empty())
4770     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4771
4772   // Check if this is an indirect call (MTCTR/BCTRL).
4773   // See PrepareCall() for more information about calls through function
4774   // pointers in the 64-bit SVR4 ABI.
4775   if (!isTailCall && !IsPatchPoint &&
4776       !isFunctionGlobalAddress(Callee) &&
4777       !isa<ExternalSymbolSDNode>(Callee)) {
4778     // Load r2 into a virtual register and store it to the TOC save area.
4779     setUsesTOCBasePtr(DAG);
4780     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4781     // TOC save area offset.
4782     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4783     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4784     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4785     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
4786                          MachinePointerInfo::getStack(TOCSaveOffset),
4787                          false, false, 0);
4788     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4789     // This does not mean the MTCTR instruction must use R12; it's easier
4790     // to model this as an extra parameter, so do that.
4791     if (isELFv2ABI && !IsPatchPoint)
4792       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4793   }
4794
4795   // Build a sequence of copy-to-reg nodes chained together with token chain
4796   // and flag operands which copy the outgoing args into the appropriate regs.
4797   SDValue InFlag;
4798   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4799     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4800                              RegsToPass[i].second, InFlag);
4801     InFlag = Chain.getValue(1);
4802   }
4803
4804   if (isTailCall)
4805     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4806                     FPOp, true, TailCallArguments);
4807
4808   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4809                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4810                     NumBytes, Ins, InVals, CS);
4811 }
4812
4813 SDValue
4814 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4815                                     CallingConv::ID CallConv, bool isVarArg,
4816                                     bool isTailCall, bool IsPatchPoint,
4817                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4818                                     const SmallVectorImpl<SDValue> &OutVals,
4819                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4820                                     SDLoc dl, SelectionDAG &DAG,
4821                                     SmallVectorImpl<SDValue> &InVals,
4822                                     ImmutableCallSite *CS) const {
4823
4824   unsigned NumOps = Outs.size();
4825
4826   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4827   bool isPPC64 = PtrVT == MVT::i64;
4828   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4829
4830   MachineFunction &MF = DAG.getMachineFunction();
4831
4832   // Mark this function as potentially containing a function that contains a
4833   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4834   // and restoring the callers stack pointer in this functions epilog. This is
4835   // done because by tail calling the called function might overwrite the value
4836   // in this function's (MF) stack pointer stack slot 0(SP).
4837   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4838       CallConv == CallingConv::Fast)
4839     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4840
4841   // Count how many bytes are to be pushed on the stack, including the linkage
4842   // area, and parameter passing area.  We start with 24/48 bytes, which is
4843   // prereserved space for [SP][CR][LR][3 x unused].
4844   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4845                                                           false);
4846   unsigned NumBytes = LinkageSize;
4847
4848   // Add up all the space actually used.
4849   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4850   // they all go in registers, but we must reserve stack space for them for
4851   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4852   // assigned stack space in order, with padding so Altivec parameters are
4853   // 16-byte aligned.
4854   unsigned nAltivecParamsAtEnd = 0;
4855   for (unsigned i = 0; i != NumOps; ++i) {
4856     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4857     EVT ArgVT = Outs[i].VT;
4858     // Varargs Altivec parameters are padded to a 16 byte boundary.
4859     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4860         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4861         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4862       if (!isVarArg && !isPPC64) {
4863         // Non-varargs Altivec parameters go after all the non-Altivec
4864         // parameters; handle those later so we know how much padding we need.
4865         nAltivecParamsAtEnd++;
4866         continue;
4867       }
4868       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4869       NumBytes = ((NumBytes+15)/16)*16;
4870     }
4871     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4872   }
4873
4874   // Allow for Altivec parameters at the end, if needed.
4875   if (nAltivecParamsAtEnd) {
4876     NumBytes = ((NumBytes+15)/16)*16;
4877     NumBytes += 16*nAltivecParamsAtEnd;
4878   }
4879
4880   // The prolog code of the callee may store up to 8 GPR argument registers to
4881   // the stack, allowing va_start to index over them in memory if its varargs.
4882   // Because we cannot tell if this is needed on the caller side, we have to
4883   // conservatively assume that it is needed.  As such, make sure we have at
4884   // least enough stack space for the caller to store the 8 GPRs.
4885   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4886
4887   // Tail call needs the stack to be aligned.
4888   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4889       CallConv == CallingConv::Fast)
4890     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4891
4892   // Calculate by how many bytes the stack has to be adjusted in case of tail
4893   // call optimization.
4894   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4895
4896   // To protect arguments on the stack from being clobbered in a tail call,
4897   // force all the loads to happen before doing any other lowering.
4898   if (isTailCall)
4899     Chain = DAG.getStackArgumentTokenFactor(Chain);
4900
4901   // Adjust the stack pointer for the new arguments...
4902   // These operations are automatically eliminated by the prolog/epilog pass
4903   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4904                                dl);
4905   SDValue CallSeqStart = Chain;
4906
4907   // Load the return address and frame pointer so it can be move somewhere else
4908   // later.
4909   SDValue LROp, FPOp;
4910   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4911                                        dl);
4912
4913   // Set up a copy of the stack pointer for use loading and storing any
4914   // arguments that may not fit in the registers available for argument
4915   // passing.
4916   SDValue StackPtr;
4917   if (isPPC64)
4918     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4919   else
4920     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4921
4922   // Figure out which arguments are going to go in registers, and which in
4923   // memory.  Also, if this is a vararg function, floating point operations
4924   // must be stored to our stack, and loaded into integer regs as well, if
4925   // any integer regs are available for argument passing.
4926   unsigned ArgOffset = LinkageSize;
4927   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4928
4929   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4930     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4931     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4932   };
4933   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4934     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4935     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4936   };
4937   static const MCPhysReg *FPR = GetFPR();
4938
4939   static const MCPhysReg VR[] = {
4940     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4941     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4942   };
4943   const unsigned NumGPRs = array_lengthof(GPR_32);
4944   const unsigned NumFPRs = 13;
4945   const unsigned NumVRs  = array_lengthof(VR);
4946
4947   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4948
4949   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4950   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4951
4952   SmallVector<SDValue, 8> MemOpChains;
4953   for (unsigned i = 0; i != NumOps; ++i) {
4954     SDValue Arg = OutVals[i];
4955     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4956
4957     // PtrOff will be used to store the current argument to the stack if a
4958     // register cannot be found for it.
4959     SDValue PtrOff;
4960
4961     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4962
4963     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4964
4965     // On PPC64, promote integers to 64-bit values.
4966     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4967       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4968       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4969       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4970     }
4971
4972     // FIXME memcpy is used way more than necessary.  Correctness first.
4973     // Note: "by value" is code for passing a structure by value, not
4974     // basic types.
4975     if (Flags.isByVal()) {
4976       unsigned Size = Flags.getByValSize();
4977       // Very small objects are passed right-justified.  Everything else is
4978       // passed left-justified.
4979       if (Size==1 || Size==2) {
4980         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4981         if (GPR_idx != NumGPRs) {
4982           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4983                                         MachinePointerInfo(), VT,
4984                                         false, false, false, 0);
4985           MemOpChains.push_back(Load.getValue(1));
4986           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4987
4988           ArgOffset += PtrByteSize;
4989         } else {
4990           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4991                                           PtrOff.getValueType());
4992           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4993           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4994                                                             CallSeqStart,
4995                                                             Flags, DAG, dl);
4996           ArgOffset += PtrByteSize;
4997         }
4998         continue;
4999       }
5000       // Copy entire object into memory.  There are cases where gcc-generated
5001       // code assumes it is there, even if it could be put entirely into
5002       // registers.  (This is not what the doc says.)
5003       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5004                                                         CallSeqStart,
5005                                                         Flags, DAG, dl);
5006
5007       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5008       // copy the pieces of the object that fit into registers from the
5009       // parameter save area.
5010       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5011         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5012         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5013         if (GPR_idx != NumGPRs) {
5014           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5015                                      MachinePointerInfo(),
5016                                      false, false, false, 0);
5017           MemOpChains.push_back(Load.getValue(1));
5018           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5019           ArgOffset += PtrByteSize;
5020         } else {
5021           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5022           break;
5023         }
5024       }
5025       continue;
5026     }
5027
5028     switch (Arg.getSimpleValueType().SimpleTy) {
5029     default: llvm_unreachable("Unexpected ValueType for argument!");
5030     case MVT::i1:
5031     case MVT::i32:
5032     case MVT::i64:
5033       if (GPR_idx != NumGPRs) {
5034         if (Arg.getValueType() == MVT::i1)
5035           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5036
5037         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5038       } else {
5039         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5040                          isPPC64, isTailCall, false, MemOpChains,
5041                          TailCallArguments, dl);
5042       }
5043       ArgOffset += PtrByteSize;
5044       break;
5045     case MVT::f32:
5046     case MVT::f64:
5047       if (FPR_idx != NumFPRs) {
5048         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5049
5050         if (isVarArg) {
5051           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5052                                        MachinePointerInfo(), false, false, 0);
5053           MemOpChains.push_back(Store);
5054
5055           // Float varargs are always shadowed in available integer registers
5056           if (GPR_idx != NumGPRs) {
5057             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5058                                        MachinePointerInfo(), false, false,
5059                                        false, 0);
5060             MemOpChains.push_back(Load.getValue(1));
5061             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5062           }
5063           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5064             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5065             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5066             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5067                                        MachinePointerInfo(),
5068                                        false, false, false, 0);
5069             MemOpChains.push_back(Load.getValue(1));
5070             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5071           }
5072         } else {
5073           // If we have any FPRs remaining, we may also have GPRs remaining.
5074           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5075           // GPRs.
5076           if (GPR_idx != NumGPRs)
5077             ++GPR_idx;
5078           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5079               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5080             ++GPR_idx;
5081         }
5082       } else
5083         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5084                          isPPC64, isTailCall, false, MemOpChains,
5085                          TailCallArguments, dl);
5086       if (isPPC64)
5087         ArgOffset += 8;
5088       else
5089         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5090       break;
5091     case MVT::v4f32:
5092     case MVT::v4i32:
5093     case MVT::v8i16:
5094     case MVT::v16i8:
5095       if (isVarArg) {
5096         // These go aligned on the stack, or in the corresponding R registers
5097         // when within range.  The Darwin PPC ABI doc claims they also go in
5098         // V registers; in fact gcc does this only for arguments that are
5099         // prototyped, not for those that match the ...  We do it for all
5100         // arguments, seems to work.
5101         while (ArgOffset % 16 !=0) {
5102           ArgOffset += PtrByteSize;
5103           if (GPR_idx != NumGPRs)
5104             GPR_idx++;
5105         }
5106         // We could elide this store in the case where the object fits
5107         // entirely in R registers.  Maybe later.
5108         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5109                             DAG.getConstant(ArgOffset, PtrVT));
5110         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5111                                      MachinePointerInfo(), false, false, 0);
5112         MemOpChains.push_back(Store);
5113         if (VR_idx != NumVRs) {
5114           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5115                                      MachinePointerInfo(),
5116                                      false, false, false, 0);
5117           MemOpChains.push_back(Load.getValue(1));
5118           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5119         }
5120         ArgOffset += 16;
5121         for (unsigned i=0; i<16; i+=PtrByteSize) {
5122           if (GPR_idx == NumGPRs)
5123             break;
5124           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5125                                   DAG.getConstant(i, PtrVT));
5126           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5127                                      false, false, false, 0);
5128           MemOpChains.push_back(Load.getValue(1));
5129           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5130         }
5131         break;
5132       }
5133
5134       // Non-varargs Altivec params generally go in registers, but have
5135       // stack space allocated at the end.
5136       if (VR_idx != NumVRs) {
5137         // Doesn't have GPR space allocated.
5138         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5139       } else if (nAltivecParamsAtEnd==0) {
5140         // We are emitting Altivec params in order.
5141         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5142                          isPPC64, isTailCall, true, MemOpChains,
5143                          TailCallArguments, dl);
5144         ArgOffset += 16;
5145       }
5146       break;
5147     }
5148   }
5149   // If all Altivec parameters fit in registers, as they usually do,
5150   // they get stack space following the non-Altivec parameters.  We
5151   // don't track this here because nobody below needs it.
5152   // If there are more Altivec parameters than fit in registers emit
5153   // the stores here.
5154   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5155     unsigned j = 0;
5156     // Offset is aligned; skip 1st 12 params which go in V registers.
5157     ArgOffset = ((ArgOffset+15)/16)*16;
5158     ArgOffset += 12*16;
5159     for (unsigned i = 0; i != NumOps; ++i) {
5160       SDValue Arg = OutVals[i];
5161       EVT ArgType = Outs[i].VT;
5162       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5163           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5164         if (++j > NumVRs) {
5165           SDValue PtrOff;
5166           // We are emitting Altivec params in order.
5167           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5168                            isPPC64, isTailCall, true, MemOpChains,
5169                            TailCallArguments, dl);
5170           ArgOffset += 16;
5171         }
5172       }
5173     }
5174   }
5175
5176   if (!MemOpChains.empty())
5177     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5178
5179   // On Darwin, R12 must contain the address of an indirect callee.  This does
5180   // not mean the MTCTR instruction must use R12; it's easier to model this as
5181   // an extra parameter, so do that.
5182   if (!isTailCall &&
5183       !isFunctionGlobalAddress(Callee) &&
5184       !isa<ExternalSymbolSDNode>(Callee) &&
5185       !isBLACompatibleAddress(Callee, DAG))
5186     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5187                                                    PPC::R12), Callee));
5188
5189   // Build a sequence of copy-to-reg nodes chained together with token chain
5190   // and flag operands which copy the outgoing args into the appropriate regs.
5191   SDValue InFlag;
5192   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5193     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5194                              RegsToPass[i].second, InFlag);
5195     InFlag = Chain.getValue(1);
5196   }
5197
5198   if (isTailCall)
5199     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5200                     FPOp, true, TailCallArguments);
5201
5202   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5203                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5204                     NumBytes, Ins, InVals, CS);
5205 }
5206
5207 bool
5208 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5209                                   MachineFunction &MF, bool isVarArg,
5210                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5211                                   LLVMContext &Context) const {
5212   SmallVector<CCValAssign, 16> RVLocs;
5213   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5214   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5215 }
5216
5217 SDValue
5218 PPCTargetLowering::LowerReturn(SDValue Chain,
5219                                CallingConv::ID CallConv, bool isVarArg,
5220                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5221                                const SmallVectorImpl<SDValue> &OutVals,
5222                                SDLoc dl, SelectionDAG &DAG) const {
5223
5224   SmallVector<CCValAssign, 16> RVLocs;
5225   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5226                  *DAG.getContext());
5227   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5228
5229   SDValue Flag;
5230   SmallVector<SDValue, 4> RetOps(1, Chain);
5231
5232   // Copy the result values into the output registers.
5233   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5234     CCValAssign &VA = RVLocs[i];
5235     assert(VA.isRegLoc() && "Can only return in registers!");
5236
5237     SDValue Arg = OutVals[i];
5238
5239     switch (VA.getLocInfo()) {
5240     default: llvm_unreachable("Unknown loc info!");
5241     case CCValAssign::Full: break;
5242     case CCValAssign::AExt:
5243       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5244       break;
5245     case CCValAssign::ZExt:
5246       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5247       break;
5248     case CCValAssign::SExt:
5249       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5250       break;
5251     }
5252
5253     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5254     Flag = Chain.getValue(1);
5255     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5256   }
5257
5258   RetOps[0] = Chain;  // Update chain.
5259
5260   // Add the flag if we have it.
5261   if (Flag.getNode())
5262     RetOps.push_back(Flag);
5263
5264   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5265 }
5266
5267 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5268                                    const PPCSubtarget &Subtarget) const {
5269   // When we pop the dynamic allocation we need to restore the SP link.
5270   SDLoc dl(Op);
5271
5272   // Get the corect type for pointers.
5273   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5274
5275   // Construct the stack pointer operand.
5276   bool isPPC64 = Subtarget.isPPC64();
5277   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5278   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5279
5280   // Get the operands for the STACKRESTORE.
5281   SDValue Chain = Op.getOperand(0);
5282   SDValue SaveSP = Op.getOperand(1);
5283
5284   // Load the old link SP.
5285   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5286                                    MachinePointerInfo(),
5287                                    false, false, false, 0);
5288
5289   // Restore the stack pointer.
5290   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5291
5292   // Store the old link SP.
5293   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5294                       false, false, 0);
5295 }
5296
5297
5298
5299 SDValue
5300 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5301   MachineFunction &MF = DAG.getMachineFunction();
5302   bool isPPC64 = Subtarget.isPPC64();
5303   bool isDarwinABI = Subtarget.isDarwinABI();
5304   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5305
5306   // Get current frame pointer save index.  The users of this index will be
5307   // primarily DYNALLOC instructions.
5308   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5309   int RASI = FI->getReturnAddrSaveIndex();
5310
5311   // If the frame pointer save index hasn't been defined yet.
5312   if (!RASI) {
5313     // Find out what the fix offset of the frame pointer save area.
5314     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5315     // Allocate the frame index for frame pointer save area.
5316     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5317     // Save the result.
5318     FI->setReturnAddrSaveIndex(RASI);
5319   }
5320   return DAG.getFrameIndex(RASI, PtrVT);
5321 }
5322
5323 SDValue
5324 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5325   MachineFunction &MF = DAG.getMachineFunction();
5326   bool isPPC64 = Subtarget.isPPC64();
5327   bool isDarwinABI = Subtarget.isDarwinABI();
5328   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5329
5330   // Get current frame pointer save index.  The users of this index will be
5331   // primarily DYNALLOC instructions.
5332   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5333   int FPSI = FI->getFramePointerSaveIndex();
5334
5335   // If the frame pointer save index hasn't been defined yet.
5336   if (!FPSI) {
5337     // Find out what the fix offset of the frame pointer save area.
5338     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5339                                                            isDarwinABI);
5340
5341     // Allocate the frame index for frame pointer save area.
5342     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5343     // Save the result.
5344     FI->setFramePointerSaveIndex(FPSI);
5345   }
5346   return DAG.getFrameIndex(FPSI, PtrVT);
5347 }
5348
5349 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5350                                          SelectionDAG &DAG,
5351                                          const PPCSubtarget &Subtarget) const {
5352   // Get the inputs.
5353   SDValue Chain = Op.getOperand(0);
5354   SDValue Size  = Op.getOperand(1);
5355   SDLoc dl(Op);
5356
5357   // Get the corect type for pointers.
5358   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5359   // Negate the size.
5360   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5361                                   DAG.getConstant(0, PtrVT), Size);
5362   // Construct a node for the frame pointer save index.
5363   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5364   // Build a DYNALLOC node.
5365   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5366   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5367   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5368 }
5369
5370 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5371                                                SelectionDAG &DAG) const {
5372   SDLoc DL(Op);
5373   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5374                      DAG.getVTList(MVT::i32, MVT::Other),
5375                      Op.getOperand(0), Op.getOperand(1));
5376 }
5377
5378 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5379                                                 SelectionDAG &DAG) const {
5380   SDLoc DL(Op);
5381   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5382                      Op.getOperand(0), Op.getOperand(1));
5383 }
5384
5385 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5386   assert(Op.getValueType() == MVT::i1 &&
5387          "Custom lowering only for i1 loads");
5388
5389   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5390
5391   SDLoc dl(Op);
5392   LoadSDNode *LD = cast<LoadSDNode>(Op);
5393
5394   SDValue Chain = LD->getChain();
5395   SDValue BasePtr = LD->getBasePtr();
5396   MachineMemOperand *MMO = LD->getMemOperand();
5397
5398   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5399                                  BasePtr, MVT::i8, MMO);
5400   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5401
5402   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5403   return DAG.getMergeValues(Ops, dl);
5404 }
5405
5406 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5407   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5408          "Custom lowering only for i1 stores");
5409
5410   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5411
5412   SDLoc dl(Op);
5413   StoreSDNode *ST = cast<StoreSDNode>(Op);
5414
5415   SDValue Chain = ST->getChain();
5416   SDValue BasePtr = ST->getBasePtr();
5417   SDValue Value = ST->getValue();
5418   MachineMemOperand *MMO = ST->getMemOperand();
5419
5420   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5421   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5422 }
5423
5424 // FIXME: Remove this once the ANDI glue bug is fixed:
5425 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5426   assert(Op.getValueType() == MVT::i1 &&
5427          "Custom lowering only for i1 results");
5428
5429   SDLoc DL(Op);
5430   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5431                      Op.getOperand(0));
5432 }
5433
5434 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5435 /// possible.
5436 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5437   // Not FP? Not a fsel.
5438   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5439       !Op.getOperand(2).getValueType().isFloatingPoint())
5440     return Op;
5441
5442   // We might be able to do better than this under some circumstances, but in
5443   // general, fsel-based lowering of select is a finite-math-only optimization.
5444   // For more information, see section F.3 of the 2.06 ISA specification.
5445   if (!DAG.getTarget().Options.NoInfsFPMath ||
5446       !DAG.getTarget().Options.NoNaNsFPMath)
5447     return Op;
5448
5449   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5450
5451   EVT ResVT = Op.getValueType();
5452   EVT CmpVT = Op.getOperand(0).getValueType();
5453   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5454   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5455   SDLoc dl(Op);
5456
5457   // If the RHS of the comparison is a 0.0, we don't need to do the
5458   // subtraction at all.
5459   SDValue Sel1;
5460   if (isFloatingPointZero(RHS))
5461     switch (CC) {
5462     default: break;       // SETUO etc aren't handled by fsel.
5463     case ISD::SETNE:
5464       std::swap(TV, FV);
5465     case ISD::SETEQ:
5466       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5467         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5468       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5469       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5470         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5471       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5472                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5473     case ISD::SETULT:
5474     case ISD::SETLT:
5475       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5476     case ISD::SETOGE:
5477     case ISD::SETGE:
5478       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5479         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5480       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5481     case ISD::SETUGT:
5482     case ISD::SETGT:
5483       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5484     case ISD::SETOLE:
5485     case ISD::SETLE:
5486       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5487         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5488       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5489                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5490     }
5491
5492   SDValue Cmp;
5493   switch (CC) {
5494   default: break;       // SETUO etc aren't handled by fsel.
5495   case ISD::SETNE:
5496     std::swap(TV, FV);
5497   case ISD::SETEQ:
5498     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5499     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5500       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5501     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5502     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5503       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5504     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5505                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5506   case ISD::SETULT:
5507   case ISD::SETLT:
5508     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5509     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5510       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5511     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5512   case ISD::SETOGE:
5513   case ISD::SETGE:
5514     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5515     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5516       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5517     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5518   case ISD::SETUGT:
5519   case ISD::SETGT:
5520     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5521     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5522       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5523     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5524   case ISD::SETOLE:
5525   case ISD::SETLE:
5526     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5527     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5528       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5529     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5530   }
5531   return Op;
5532 }
5533
5534 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5535                                                SelectionDAG &DAG,
5536                                                SDLoc dl) const {
5537   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5538   SDValue Src = Op.getOperand(0);
5539   if (Src.getValueType() == MVT::f32)
5540     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5541
5542   SDValue Tmp;
5543   switch (Op.getSimpleValueType().SimpleTy) {
5544   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5545   case MVT::i32:
5546     Tmp = DAG.getNode(
5547         Op.getOpcode() == ISD::FP_TO_SINT
5548             ? PPCISD::FCTIWZ
5549             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5550         dl, MVT::f64, Src);
5551     break;
5552   case MVT::i64:
5553     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5554            "i64 FP_TO_UINT is supported only with FPCVT");
5555     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5556                                                         PPCISD::FCTIDUZ,
5557                       dl, MVT::f64, Src);
5558     break;
5559   }
5560
5561   // Convert the FP value to an int value through memory.
5562   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5563     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5564   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5565   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5566   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5567
5568   // Emit a store to the stack slot.
5569   SDValue Chain;
5570   if (i32Stack) {
5571     MachineFunction &MF = DAG.getMachineFunction();
5572     MachineMemOperand *MMO =
5573       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5574     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5575     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5576               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5577   } else
5578     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5579                          MPI, false, false, 0);
5580
5581   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5582   // add in a bias.
5583   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5584     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5585                         DAG.getConstant(4, FIPtr.getValueType()));
5586     MPI = MPI.getWithOffset(4);
5587   }
5588
5589   RLI.Chain = Chain;
5590   RLI.Ptr = FIPtr;
5591   RLI.MPI = MPI;
5592 }
5593
5594 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5595                                           SDLoc dl) const {
5596   ReuseLoadInfo RLI;
5597   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5598
5599   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5600                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5601                      RLI.Ranges);
5602 }
5603
5604 // We're trying to insert a regular store, S, and then a load, L. If the
5605 // incoming value, O, is a load, we might just be able to have our load use the
5606 // address used by O. However, we don't know if anything else will store to
5607 // that address before we can load from it. To prevent this situation, we need
5608 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5609 // the same chain operand as O, we create a token factor from the chain results
5610 // of O and L, and we replace all uses of O's chain result with that token
5611 // factor (see spliceIntoChain below for this last part).
5612 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5613                                             ReuseLoadInfo &RLI,
5614                                             SelectionDAG &DAG,
5615                                             ISD::LoadExtType ET) const {
5616   SDLoc dl(Op);
5617   if (ET == ISD::NON_EXTLOAD &&
5618       (Op.getOpcode() == ISD::FP_TO_UINT ||
5619        Op.getOpcode() == ISD::FP_TO_SINT) &&
5620       isOperationLegalOrCustom(Op.getOpcode(),
5621                                Op.getOperand(0).getValueType())) {
5622
5623     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5624     return true;
5625   }
5626
5627   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5628   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5629       LD->isNonTemporal())
5630     return false;
5631   if (LD->getMemoryVT() != MemVT)
5632     return false;
5633
5634   RLI.Ptr = LD->getBasePtr();
5635   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5636     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5637            "Non-pre-inc AM on PPC?");
5638     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5639                           LD->getOffset());
5640   }
5641
5642   RLI.Chain = LD->getChain();
5643   RLI.MPI = LD->getPointerInfo();
5644   RLI.IsInvariant = LD->isInvariant();
5645   RLI.Alignment = LD->getAlignment();
5646   RLI.AAInfo = LD->getAAInfo();
5647   RLI.Ranges = LD->getRanges();
5648
5649   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5650   return true;
5651 }
5652
5653 // Given the head of the old chain, ResChain, insert a token factor containing
5654 // it and NewResChain, and make users of ResChain now be users of that token
5655 // factor.
5656 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5657                                         SDValue NewResChain,
5658                                         SelectionDAG &DAG) const {
5659   if (!ResChain)
5660     return;
5661
5662   SDLoc dl(NewResChain);
5663
5664   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5665                            NewResChain, DAG.getUNDEF(MVT::Other));
5666   assert(TF.getNode() != NewResChain.getNode() &&
5667          "A new TF really is required here");
5668
5669   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5670   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5671 }
5672
5673 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5674                                           SelectionDAG &DAG) const {
5675   SDLoc dl(Op);
5676   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5677   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5678     return SDValue();
5679
5680   if (Op.getOperand(0).getValueType() == MVT::i1)
5681     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5682                        DAG.getConstantFP(1.0, Op.getValueType()),
5683                        DAG.getConstantFP(0.0, Op.getValueType()));
5684
5685   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5686          "UINT_TO_FP is supported only with FPCVT");
5687
5688   // If we have FCFIDS, then use it when converting to single-precision.
5689   // Otherwise, convert to double-precision and then round.
5690   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5691                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
5692                                                             : PPCISD::FCFIDS)
5693                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
5694                                                             : PPCISD::FCFID);
5695   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5696                   ? MVT::f32
5697                   : MVT::f64;
5698
5699   if (Op.getOperand(0).getValueType() == MVT::i64) {
5700     SDValue SINT = Op.getOperand(0);
5701     // When converting to single-precision, we actually need to convert
5702     // to double-precision first and then round to single-precision.
5703     // To avoid double-rounding effects during that operation, we have
5704     // to prepare the input operand.  Bits that might be truncated when
5705     // converting to double-precision are replaced by a bit that won't
5706     // be lost at this stage, but is below the single-precision rounding
5707     // position.
5708     //
5709     // However, if -enable-unsafe-fp-math is in effect, accept double
5710     // rounding to avoid the extra overhead.
5711     if (Op.getValueType() == MVT::f32 &&
5712         !Subtarget.hasFPCVT() &&
5713         !DAG.getTarget().Options.UnsafeFPMath) {
5714
5715       // Twiddle input to make sure the low 11 bits are zero.  (If this
5716       // is the case, we are guaranteed the value will fit into the 53 bit
5717       // mantissa of an IEEE double-precision value without rounding.)
5718       // If any of those low 11 bits were not zero originally, make sure
5719       // bit 12 (value 2048) is set instead, so that the final rounding
5720       // to single-precision gets the correct result.
5721       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5722                                   SINT, DAG.getConstant(2047, MVT::i64));
5723       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5724                           Round, DAG.getConstant(2047, MVT::i64));
5725       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5726       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5727                           Round, DAG.getConstant(-2048, MVT::i64));
5728
5729       // However, we cannot use that value unconditionally: if the magnitude
5730       // of the input value is small, the bit-twiddling we did above might
5731       // end up visibly changing the output.  Fortunately, in that case, we
5732       // don't need to twiddle bits since the original input will convert
5733       // exactly to double-precision floating-point already.  Therefore,
5734       // construct a conditional to use the original value if the top 11
5735       // bits are all sign-bit copies, and use the rounded value computed
5736       // above otherwise.
5737       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5738                                  SINT, DAG.getConstant(53, MVT::i32));
5739       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5740                          Cond, DAG.getConstant(1, MVT::i64));
5741       Cond = DAG.getSetCC(dl, MVT::i32,
5742                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5743
5744       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5745     }
5746
5747     ReuseLoadInfo RLI;
5748     SDValue Bits;
5749
5750     MachineFunction &MF = DAG.getMachineFunction();
5751     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5752       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5753                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5754                          RLI.Ranges);
5755       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5756     } else if (Subtarget.hasLFIWAX() &&
5757                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5758       MachineMemOperand *MMO =
5759         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5760                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5761       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5762       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5763                                      DAG.getVTList(MVT::f64, MVT::Other),
5764                                      Ops, MVT::i32, MMO);
5765       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5766     } else if (Subtarget.hasFPCVT() &&
5767                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5768       MachineMemOperand *MMO =
5769         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5770                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5771       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5772       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5773                                      DAG.getVTList(MVT::f64, MVT::Other),
5774                                      Ops, MVT::i32, MMO);
5775       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5776     } else if (((Subtarget.hasLFIWAX() &&
5777                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5778                 (Subtarget.hasFPCVT() &&
5779                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5780                SINT.getOperand(0).getValueType() == MVT::i32) {
5781       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5782       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5783
5784       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5785       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5786
5787       SDValue Store =
5788         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5789                      MachinePointerInfo::getFixedStack(FrameIdx),
5790                      false, false, 0);
5791
5792       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5793              "Expected an i32 store");
5794
5795       RLI.Ptr = FIdx;
5796       RLI.Chain = Store;
5797       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5798       RLI.Alignment = 4;
5799
5800       MachineMemOperand *MMO =
5801         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5802                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5803       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5804       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5805                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
5806                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
5807                                      Ops, MVT::i32, MMO);
5808     } else
5809       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5810
5811     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5812
5813     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5814       FP = DAG.getNode(ISD::FP_ROUND, dl,
5815                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5816     return FP;
5817   }
5818
5819   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5820          "Unhandled INT_TO_FP type in custom expander!");
5821   // Since we only generate this in 64-bit mode, we can take advantage of
5822   // 64-bit registers.  In particular, sign extend the input value into the
5823   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5824   // then lfd it and fcfid it.
5825   MachineFunction &MF = DAG.getMachineFunction();
5826   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5827   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5828
5829   SDValue Ld;
5830   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5831     ReuseLoadInfo RLI;
5832     bool ReusingLoad;
5833     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5834                                             DAG))) {
5835       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5836       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5837
5838       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5839                                    MachinePointerInfo::getFixedStack(FrameIdx),
5840                                    false, false, 0);
5841
5842       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5843              "Expected an i32 store");
5844
5845       RLI.Ptr = FIdx;
5846       RLI.Chain = Store;
5847       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5848       RLI.Alignment = 4;
5849     }
5850
5851     MachineMemOperand *MMO =
5852       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5853                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5854     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5855     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5856                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5857                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5858                                  Ops, MVT::i32, MMO);
5859     if (ReusingLoad)
5860       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5861   } else {
5862     assert(Subtarget.isPPC64() &&
5863            "i32->FP without LFIWAX supported only on PPC64");
5864
5865     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5866     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5867
5868     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5869                                 Op.getOperand(0));
5870
5871     // STD the extended value into the stack slot.
5872     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5873                                  MachinePointerInfo::getFixedStack(FrameIdx),
5874                                  false, false, 0);
5875
5876     // Load the value as a double.
5877     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5878                      MachinePointerInfo::getFixedStack(FrameIdx),
5879                      false, false, false, 0);
5880   }
5881
5882   // FCFID it and return it.
5883   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5884   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5885     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5886   return FP;
5887 }
5888
5889 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5890                                             SelectionDAG &DAG) const {
5891   SDLoc dl(Op);
5892   /*
5893    The rounding mode is in bits 30:31 of FPSR, and has the following
5894    settings:
5895      00 Round to nearest
5896      01 Round to 0
5897      10 Round to +inf
5898      11 Round to -inf
5899
5900   FLT_ROUNDS, on the other hand, expects the following:
5901     -1 Undefined
5902      0 Round to 0
5903      1 Round to nearest
5904      2 Round to +inf
5905      3 Round to -inf
5906
5907   To perform the conversion, we do:
5908     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5909   */
5910
5911   MachineFunction &MF = DAG.getMachineFunction();
5912   EVT VT = Op.getValueType();
5913   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5914
5915   // Save FP Control Word to register
5916   EVT NodeTys[] = {
5917     MVT::f64,    // return register
5918     MVT::Glue    // unused in this context
5919   };
5920   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5921
5922   // Save FP register to stack slot
5923   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5924   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5925   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5926                                StackSlot, MachinePointerInfo(), false, false,0);
5927
5928   // Load FP Control Word from low 32 bits of stack slot.
5929   SDValue Four = DAG.getConstant(4, PtrVT);
5930   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5931   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5932                             false, false, false, 0);
5933
5934   // Transform as necessary
5935   SDValue CWD1 =
5936     DAG.getNode(ISD::AND, dl, MVT::i32,
5937                 CWD, DAG.getConstant(3, MVT::i32));
5938   SDValue CWD2 =
5939     DAG.getNode(ISD::SRL, dl, MVT::i32,
5940                 DAG.getNode(ISD::AND, dl, MVT::i32,
5941                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5942                                         CWD, DAG.getConstant(3, MVT::i32)),
5943                             DAG.getConstant(3, MVT::i32)),
5944                 DAG.getConstant(1, MVT::i32));
5945
5946   SDValue RetVal =
5947     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5948
5949   return DAG.getNode((VT.getSizeInBits() < 16 ?
5950                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5951 }
5952
5953 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5954   EVT VT = Op.getValueType();
5955   unsigned BitWidth = VT.getSizeInBits();
5956   SDLoc dl(Op);
5957   assert(Op.getNumOperands() == 3 &&
5958          VT == Op.getOperand(1).getValueType() &&
5959          "Unexpected SHL!");
5960
5961   // Expand into a bunch of logical ops.  Note that these ops
5962   // depend on the PPC behavior for oversized shift amounts.
5963   SDValue Lo = Op.getOperand(0);
5964   SDValue Hi = Op.getOperand(1);
5965   SDValue Amt = Op.getOperand(2);
5966   EVT AmtVT = Amt.getValueType();
5967
5968   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5969                              DAG.getConstant(BitWidth, AmtVT), Amt);
5970   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5971   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5972   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5973   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5974                              DAG.getConstant(-BitWidth, AmtVT));
5975   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5976   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5977   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5978   SDValue OutOps[] = { OutLo, OutHi };
5979   return DAG.getMergeValues(OutOps, dl);
5980 }
5981
5982 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5983   EVT VT = Op.getValueType();
5984   SDLoc dl(Op);
5985   unsigned BitWidth = VT.getSizeInBits();
5986   assert(Op.getNumOperands() == 3 &&
5987          VT == Op.getOperand(1).getValueType() &&
5988          "Unexpected SRL!");
5989
5990   // Expand into a bunch of logical ops.  Note that these ops
5991   // depend on the PPC behavior for oversized shift amounts.
5992   SDValue Lo = Op.getOperand(0);
5993   SDValue Hi = Op.getOperand(1);
5994   SDValue Amt = Op.getOperand(2);
5995   EVT AmtVT = Amt.getValueType();
5996
5997   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5998                              DAG.getConstant(BitWidth, AmtVT), Amt);
5999   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6000   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6001   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6002   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6003                              DAG.getConstant(-BitWidth, AmtVT));
6004   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6005   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6006   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6007   SDValue OutOps[] = { OutLo, OutHi };
6008   return DAG.getMergeValues(OutOps, dl);
6009 }
6010
6011 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6012   SDLoc dl(Op);
6013   EVT VT = Op.getValueType();
6014   unsigned BitWidth = VT.getSizeInBits();
6015   assert(Op.getNumOperands() == 3 &&
6016          VT == Op.getOperand(1).getValueType() &&
6017          "Unexpected SRA!");
6018
6019   // Expand into a bunch of logical ops, followed by a select_cc.
6020   SDValue Lo = Op.getOperand(0);
6021   SDValue Hi = Op.getOperand(1);
6022   SDValue Amt = Op.getOperand(2);
6023   EVT AmtVT = Amt.getValueType();
6024
6025   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6026                              DAG.getConstant(BitWidth, AmtVT), Amt);
6027   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6028   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6029   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6030   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6031                              DAG.getConstant(-BitWidth, AmtVT));
6032   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6033   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6034   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6035                                   Tmp4, Tmp6, ISD::SETLE);
6036   SDValue OutOps[] = { OutLo, OutHi };
6037   return DAG.getMergeValues(OutOps, dl);
6038 }
6039
6040 //===----------------------------------------------------------------------===//
6041 // Vector related lowering.
6042 //
6043
6044 /// BuildSplatI - Build a canonical splati of Val with an element size of
6045 /// SplatSize.  Cast the result to VT.
6046 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6047                              SelectionDAG &DAG, SDLoc dl) {
6048   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6049
6050   static const EVT VTys[] = { // canonical VT to use for each size.
6051     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6052   };
6053
6054   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6055
6056   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6057   if (Val == -1)
6058     SplatSize = 1;
6059
6060   EVT CanonicalVT = VTys[SplatSize-1];
6061
6062   // Build a canonical splat for this value.
6063   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6064   SmallVector<SDValue, 8> Ops;
6065   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6066   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6067   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6068 }
6069
6070 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6071 /// specified intrinsic ID.
6072 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6073                                 SelectionDAG &DAG, SDLoc dl,
6074                                 EVT DestVT = MVT::Other) {
6075   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6076   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6077                      DAG.getConstant(IID, MVT::i32), Op);
6078 }
6079
6080 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6081 /// specified intrinsic ID.
6082 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6083                                 SelectionDAG &DAG, SDLoc dl,
6084                                 EVT DestVT = MVT::Other) {
6085   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6086   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6087                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6088 }
6089
6090 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6091 /// specified intrinsic ID.
6092 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6093                                 SDValue Op2, SelectionDAG &DAG,
6094                                 SDLoc dl, EVT DestVT = MVT::Other) {
6095   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6096   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6097                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6098 }
6099
6100
6101 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6102 /// amount.  The result has the specified value type.
6103 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6104                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6105   // Force LHS/RHS to be the right type.
6106   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6107   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6108
6109   int Ops[16];
6110   for (unsigned i = 0; i != 16; ++i)
6111     Ops[i] = i + Amt;
6112   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6113   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6114 }
6115
6116 // If this is a case we can't handle, return null and let the default
6117 // expansion code take care of it.  If we CAN select this case, and if it
6118 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6119 // this case more efficiently than a constant pool load, lower it to the
6120 // sequence of ops that should be used.
6121 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6122                                              SelectionDAG &DAG) const {
6123   SDLoc dl(Op);
6124   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6125   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6126
6127   // Check if this is a splat of a constant value.
6128   APInt APSplatBits, APSplatUndef;
6129   unsigned SplatBitSize;
6130   bool HasAnyUndefs;
6131   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6132                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6133     return SDValue();
6134
6135   unsigned SplatBits = APSplatBits.getZExtValue();
6136   unsigned SplatUndef = APSplatUndef.getZExtValue();
6137   unsigned SplatSize = SplatBitSize / 8;
6138
6139   // First, handle single instruction cases.
6140
6141   // All zeros?
6142   if (SplatBits == 0) {
6143     // Canonicalize all zero vectors to be v4i32.
6144     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6145       SDValue Z = DAG.getConstant(0, MVT::i32);
6146       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6147       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6148     }
6149     return Op;
6150   }
6151
6152   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6153   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6154                     (32-SplatBitSize));
6155   if (SextVal >= -16 && SextVal <= 15)
6156     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6157
6158
6159   // Two instruction sequences.
6160
6161   // If this value is in the range [-32,30] and is even, use:
6162   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6163   // If this value is in the range [17,31] and is odd, use:
6164   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6165   // If this value is in the range [-31,-17] and is odd, use:
6166   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6167   // Note the last two are three-instruction sequences.
6168   if (SextVal >= -32 && SextVal <= 31) {
6169     // To avoid having these optimizations undone by constant folding,
6170     // we convert to a pseudo that will be expanded later into one of
6171     // the above forms.
6172     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6173     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6174               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6175     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6176     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6177     if (VT == Op.getValueType())
6178       return RetVal;
6179     else
6180       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6181   }
6182
6183   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6184   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6185   // for fneg/fabs.
6186   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6187     // Make -1 and vspltisw -1:
6188     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6189
6190     // Make the VSLW intrinsic, computing 0x8000_0000.
6191     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6192                                    OnesV, DAG, dl);
6193
6194     // xor by OnesV to invert it.
6195     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6196     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6197   }
6198
6199   // The remaining cases assume either big endian element order or
6200   // a splat-size that equates to the element size of the vector
6201   // to be built.  An example that doesn't work for little endian is
6202   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6203   // and a vector element size of 16 bits.  The code below will
6204   // produce the vector in big endian element order, which for little
6205   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6206
6207   // For now, just avoid these optimizations in that case.
6208   // FIXME: Develop correct optimizations for LE with mismatched
6209   // splat and element sizes.
6210
6211   if (Subtarget.isLittleEndian() &&
6212       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6213     return SDValue();
6214
6215   // Check to see if this is a wide variety of vsplti*, binop self cases.
6216   static const signed char SplatCsts[] = {
6217     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6218     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6219   };
6220
6221   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6222     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6223     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6224     int i = SplatCsts[idx];
6225
6226     // Figure out what shift amount will be used by altivec if shifted by i in
6227     // this splat size.
6228     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6229
6230     // vsplti + shl self.
6231     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6232       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6233       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6234         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6235         Intrinsic::ppc_altivec_vslw
6236       };
6237       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6238       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6239     }
6240
6241     // vsplti + srl self.
6242     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6243       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6244       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6245         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6246         Intrinsic::ppc_altivec_vsrw
6247       };
6248       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6249       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6250     }
6251
6252     // vsplti + sra self.
6253     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6254       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6255       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6256         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6257         Intrinsic::ppc_altivec_vsraw
6258       };
6259       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6260       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6261     }
6262
6263     // vsplti + rol self.
6264     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6265                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6266       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6267       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6268         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6269         Intrinsic::ppc_altivec_vrlw
6270       };
6271       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6272       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6273     }
6274
6275     // t = vsplti c, result = vsldoi t, t, 1
6276     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6277       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6278       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6279     }
6280     // t = vsplti c, result = vsldoi t, t, 2
6281     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6282       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6283       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6284     }
6285     // t = vsplti c, result = vsldoi t, t, 3
6286     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6287       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6288       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6289     }
6290   }
6291
6292   return SDValue();
6293 }
6294
6295 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6296 /// the specified operations to build the shuffle.
6297 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6298                                       SDValue RHS, SelectionDAG &DAG,
6299                                       SDLoc dl) {
6300   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6301   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6302   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6303
6304   enum {
6305     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6306     OP_VMRGHW,
6307     OP_VMRGLW,
6308     OP_VSPLTISW0,
6309     OP_VSPLTISW1,
6310     OP_VSPLTISW2,
6311     OP_VSPLTISW3,
6312     OP_VSLDOI4,
6313     OP_VSLDOI8,
6314     OP_VSLDOI12
6315   };
6316
6317   if (OpNum == OP_COPY) {
6318     if (LHSID == (1*9+2)*9+3) return LHS;
6319     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6320     return RHS;
6321   }
6322
6323   SDValue OpLHS, OpRHS;
6324   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6325   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6326
6327   int ShufIdxs[16];
6328   switch (OpNum) {
6329   default: llvm_unreachable("Unknown i32 permute!");
6330   case OP_VMRGHW:
6331     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6332     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6333     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6334     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6335     break;
6336   case OP_VMRGLW:
6337     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6338     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6339     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6340     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6341     break;
6342   case OP_VSPLTISW0:
6343     for (unsigned i = 0; i != 16; ++i)
6344       ShufIdxs[i] = (i&3)+0;
6345     break;
6346   case OP_VSPLTISW1:
6347     for (unsigned i = 0; i != 16; ++i)
6348       ShufIdxs[i] = (i&3)+4;
6349     break;
6350   case OP_VSPLTISW2:
6351     for (unsigned i = 0; i != 16; ++i)
6352       ShufIdxs[i] = (i&3)+8;
6353     break;
6354   case OP_VSPLTISW3:
6355     for (unsigned i = 0; i != 16; ++i)
6356       ShufIdxs[i] = (i&3)+12;
6357     break;
6358   case OP_VSLDOI4:
6359     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6360   case OP_VSLDOI8:
6361     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6362   case OP_VSLDOI12:
6363     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6364   }
6365   EVT VT = OpLHS.getValueType();
6366   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6367   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6368   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6369   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6370 }
6371
6372 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6373 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6374 /// return the code it can be lowered into.  Worst case, it can always be
6375 /// lowered into a vperm.
6376 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6377                                                SelectionDAG &DAG) const {
6378   SDLoc dl(Op);
6379   SDValue V1 = Op.getOperand(0);
6380   SDValue V2 = Op.getOperand(1);
6381   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6382   EVT VT = Op.getValueType();
6383   bool isLittleEndian = Subtarget.isLittleEndian();
6384
6385   // Cases that are handled by instructions that take permute immediates
6386   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6387   // selected by the instruction selector.
6388   if (V2.getOpcode() == ISD::UNDEF) {
6389     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6390         PPC::isSplatShuffleMask(SVOp, 2) ||
6391         PPC::isSplatShuffleMask(SVOp, 4) ||
6392         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6393         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6394         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6395         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6396         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6397         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6398         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6399         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6400         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6401       return Op;
6402     }
6403   }
6404
6405   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6406   // and produce a fixed permutation.  If any of these match, do not lower to
6407   // VPERM.
6408   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6409   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6410       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6411       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6412       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6413       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6414       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6415       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6416       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6417       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6418     return Op;
6419
6420   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6421   // perfect shuffle table to emit an optimal matching sequence.
6422   ArrayRef<int> PermMask = SVOp->getMask();
6423
6424   unsigned PFIndexes[4];
6425   bool isFourElementShuffle = true;
6426   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6427     unsigned EltNo = 8;   // Start out undef.
6428     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6429       if (PermMask[i*4+j] < 0)
6430         continue;   // Undef, ignore it.
6431
6432       unsigned ByteSource = PermMask[i*4+j];
6433       if ((ByteSource & 3) != j) {
6434         isFourElementShuffle = false;
6435         break;
6436       }
6437
6438       if (EltNo == 8) {
6439         EltNo = ByteSource/4;
6440       } else if (EltNo != ByteSource/4) {
6441         isFourElementShuffle = false;
6442         break;
6443       }
6444     }
6445     PFIndexes[i] = EltNo;
6446   }
6447
6448   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6449   // perfect shuffle vector to determine if it is cost effective to do this as
6450   // discrete instructions, or whether we should use a vperm.
6451   // For now, we skip this for little endian until such time as we have a
6452   // little-endian perfect shuffle table.
6453   if (isFourElementShuffle && !isLittleEndian) {
6454     // Compute the index in the perfect shuffle table.
6455     unsigned PFTableIndex =
6456       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6457
6458     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6459     unsigned Cost  = (PFEntry >> 30);
6460
6461     // Determining when to avoid vperm is tricky.  Many things affect the cost
6462     // of vperm, particularly how many times the perm mask needs to be computed.
6463     // For example, if the perm mask can be hoisted out of a loop or is already
6464     // used (perhaps because there are multiple permutes with the same shuffle
6465     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6466     // the loop requires an extra register.
6467     //
6468     // As a compromise, we only emit discrete instructions if the shuffle can be
6469     // generated in 3 or fewer operations.  When we have loop information
6470     // available, if this block is within a loop, we should avoid using vperm
6471     // for 3-operation perms and use a constant pool load instead.
6472     if (Cost < 3)
6473       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6474   }
6475
6476   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6477   // vector that will get spilled to the constant pool.
6478   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6479
6480   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6481   // that it is in input element units, not in bytes.  Convert now.
6482
6483   // For little endian, the order of the input vectors is reversed, and
6484   // the permutation mask is complemented with respect to 31.  This is
6485   // necessary to produce proper semantics with the big-endian-biased vperm
6486   // instruction.
6487   EVT EltVT = V1.getValueType().getVectorElementType();
6488   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6489
6490   SmallVector<SDValue, 16> ResultMask;
6491   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6492     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6493
6494     for (unsigned j = 0; j != BytesPerElement; ++j)
6495       if (isLittleEndian)
6496         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6497                                              MVT::i32));
6498       else
6499         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6500                                              MVT::i32));
6501   }
6502
6503   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6504                                   ResultMask);
6505   if (isLittleEndian)
6506     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6507                        V2, V1, VPermMask);
6508   else
6509     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6510                        V1, V2, VPermMask);
6511 }
6512
6513 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6514 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6515 /// information about the intrinsic.
6516 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6517                                   bool &isDot) {
6518   unsigned IntrinsicID =
6519     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6520   CompareOpc = -1;
6521   isDot = false;
6522   switch (IntrinsicID) {
6523   default: return false;
6524     // Comparison predicates.
6525   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6526   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6527   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6528   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6529   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6530   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6531   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6532   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6533   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6534   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6535   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6536   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6537   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6538
6539     // Normal Comparisons.
6540   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6541   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6542   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6543   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6544   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6545   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6546   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6547   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6548   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6549   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6550   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6551   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6552   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6553   }
6554   return true;
6555 }
6556
6557 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6558 /// lower, do it, otherwise return null.
6559 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6560                                                    SelectionDAG &DAG) const {
6561   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6562   // opcode number of the comparison.
6563   SDLoc dl(Op);
6564   int CompareOpc;
6565   bool isDot;
6566   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6567     return SDValue();    // Don't custom lower most intrinsics.
6568
6569   // If this is a non-dot comparison, make the VCMP node and we are done.
6570   if (!isDot) {
6571     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6572                               Op.getOperand(1), Op.getOperand(2),
6573                               DAG.getConstant(CompareOpc, MVT::i32));
6574     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6575   }
6576
6577   // Create the PPCISD altivec 'dot' comparison node.
6578   SDValue Ops[] = {
6579     Op.getOperand(2),  // LHS
6580     Op.getOperand(3),  // RHS
6581     DAG.getConstant(CompareOpc, MVT::i32)
6582   };
6583   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6584   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6585
6586   // Now that we have the comparison, emit a copy from the CR to a GPR.
6587   // This is flagged to the above dot comparison.
6588   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6589                                 DAG.getRegister(PPC::CR6, MVT::i32),
6590                                 CompNode.getValue(1));
6591
6592   // Unpack the result based on how the target uses it.
6593   unsigned BitNo;   // Bit # of CR6.
6594   bool InvertBit;   // Invert result?
6595   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6596   default:  // Can't happen, don't crash on invalid number though.
6597   case 0:   // Return the value of the EQ bit of CR6.
6598     BitNo = 0; InvertBit = false;
6599     break;
6600   case 1:   // Return the inverted value of the EQ bit of CR6.
6601     BitNo = 0; InvertBit = true;
6602     break;
6603   case 2:   // Return the value of the LT bit of CR6.
6604     BitNo = 2; InvertBit = false;
6605     break;
6606   case 3:   // Return the inverted value of the LT bit of CR6.
6607     BitNo = 2; InvertBit = true;
6608     break;
6609   }
6610
6611   // Shift the bit into the low position.
6612   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6613                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6614   // Isolate the bit.
6615   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6616                       DAG.getConstant(1, MVT::i32));
6617
6618   // If we are supposed to, toggle the bit.
6619   if (InvertBit)
6620     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6621                         DAG.getConstant(1, MVT::i32));
6622   return Flags;
6623 }
6624
6625 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6626                                                   SelectionDAG &DAG) const {
6627   SDLoc dl(Op);
6628   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6629   // instructions), but for smaller types, we need to first extend up to v2i32
6630   // before doing going farther.
6631   if (Op.getValueType() == MVT::v2i64) {
6632     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6633     if (ExtVT != MVT::v2i32) {
6634       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6635       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6636                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6637                                         ExtVT.getVectorElementType(), 4)));
6638       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6639       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6640                        DAG.getValueType(MVT::v2i32));
6641     }
6642
6643     return Op;
6644   }
6645
6646   return SDValue();
6647 }
6648
6649 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6650                                                    SelectionDAG &DAG) const {
6651   SDLoc dl(Op);
6652   // Create a stack slot that is 16-byte aligned.
6653   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6654   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6655   EVT PtrVT = getPointerTy();
6656   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6657
6658   // Store the input value into Value#0 of the stack slot.
6659   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6660                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6661                                false, false, 0);
6662   // Load it out.
6663   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6664                      false, false, false, 0);
6665 }
6666
6667 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6668   SDLoc dl(Op);
6669   if (Op.getValueType() == MVT::v4i32) {
6670     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6671
6672     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6673     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6674
6675     SDValue RHSSwap =   // = vrlw RHS, 16
6676       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6677
6678     // Shrinkify inputs to v8i16.
6679     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6680     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6681     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6682
6683     // Low parts multiplied together, generating 32-bit results (we ignore the
6684     // top parts).
6685     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6686                                         LHS, RHS, DAG, dl, MVT::v4i32);
6687
6688     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6689                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6690     // Shift the high parts up 16 bits.
6691     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6692                               Neg16, DAG, dl);
6693     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6694   } else if (Op.getValueType() == MVT::v8i16) {
6695     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6696
6697     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6698
6699     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6700                             LHS, RHS, Zero, DAG, dl);
6701   } else if (Op.getValueType() == MVT::v16i8) {
6702     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6703     bool isLittleEndian = Subtarget.isLittleEndian();
6704
6705     // Multiply the even 8-bit parts, producing 16-bit sums.
6706     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6707                                            LHS, RHS, DAG, dl, MVT::v8i16);
6708     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6709
6710     // Multiply the odd 8-bit parts, producing 16-bit sums.
6711     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6712                                           LHS, RHS, DAG, dl, MVT::v8i16);
6713     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6714
6715     // Merge the results together.  Because vmuleub and vmuloub are
6716     // instructions with a big-endian bias, we must reverse the
6717     // element numbering and reverse the meaning of "odd" and "even"
6718     // when generating little endian code.
6719     int Ops[16];
6720     for (unsigned i = 0; i != 8; ++i) {
6721       if (isLittleEndian) {
6722         Ops[i*2  ] = 2*i;
6723         Ops[i*2+1] = 2*i+16;
6724       } else {
6725         Ops[i*2  ] = 2*i+1;
6726         Ops[i*2+1] = 2*i+1+16;
6727       }
6728     }
6729     if (isLittleEndian)
6730       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6731     else
6732       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6733   } else {
6734     llvm_unreachable("Unknown mul to lower!");
6735   }
6736 }
6737
6738 /// LowerOperation - Provide custom lowering hooks for some operations.
6739 ///
6740 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6741   switch (Op.getOpcode()) {
6742   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6743   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6744   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6745   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6746   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6747   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6748   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6749   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6750   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6751   case ISD::VASTART:
6752     return LowerVASTART(Op, DAG, Subtarget);
6753
6754   case ISD::VAARG:
6755     return LowerVAARG(Op, DAG, Subtarget);
6756
6757   case ISD::VACOPY:
6758     return LowerVACOPY(Op, DAG, Subtarget);
6759
6760   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6761   case ISD::DYNAMIC_STACKALLOC:
6762     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6763
6764   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6765   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6766
6767   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6768   case ISD::STORE:              return LowerSTORE(Op, DAG);
6769   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6770   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6771   case ISD::FP_TO_UINT:
6772   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6773                                                       SDLoc(Op));
6774   case ISD::UINT_TO_FP:
6775   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6776   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6777
6778   // Lower 64-bit shifts.
6779   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6780   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6781   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6782
6783   // Vector-related lowering.
6784   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6785   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6786   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6787   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6788   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6789   case ISD::MUL:                return LowerMUL(Op, DAG);
6790
6791   // For counter-based loop handling.
6792   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6793
6794   // Frame & Return address.
6795   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6796   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6797   }
6798 }
6799
6800 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6801                                            SmallVectorImpl<SDValue>&Results,
6802                                            SelectionDAG &DAG) const {
6803   SDLoc dl(N);
6804   switch (N->getOpcode()) {
6805   default:
6806     llvm_unreachable("Do not know how to custom type legalize this operation!");
6807   case ISD::READCYCLECOUNTER: {
6808     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6809     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6810
6811     Results.push_back(RTB);
6812     Results.push_back(RTB.getValue(1));
6813     Results.push_back(RTB.getValue(2));
6814     break;
6815   }
6816   case ISD::INTRINSIC_W_CHAIN: {
6817     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6818         Intrinsic::ppc_is_decremented_ctr_nonzero)
6819       break;
6820
6821     assert(N->getValueType(0) == MVT::i1 &&
6822            "Unexpected result type for CTR decrement intrinsic");
6823     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6824     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6825     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6826                                  N->getOperand(1)); 
6827
6828     Results.push_back(NewInt);
6829     Results.push_back(NewInt.getValue(1));
6830     break;
6831   }
6832   case ISD::VAARG: {
6833     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
6834       return;
6835
6836     EVT VT = N->getValueType(0);
6837
6838     if (VT == MVT::i64) {
6839       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6840
6841       Results.push_back(NewNode);
6842       Results.push_back(NewNode.getValue(1));
6843     }
6844     return;
6845   }
6846   case ISD::FP_ROUND_INREG: {
6847     assert(N->getValueType(0) == MVT::ppcf128);
6848     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6849     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6850                              MVT::f64, N->getOperand(0),
6851                              DAG.getIntPtrConstant(0));
6852     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6853                              MVT::f64, N->getOperand(0),
6854                              DAG.getIntPtrConstant(1));
6855
6856     // Add the two halves of the long double in round-to-zero mode.
6857     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6858
6859     // We know the low half is about to be thrown away, so just use something
6860     // convenient.
6861     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6862                                 FPreg, FPreg));
6863     return;
6864   }
6865   case ISD::FP_TO_SINT:
6866     // LowerFP_TO_INT() can only handle f32 and f64.
6867     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6868       return;
6869     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6870     return;
6871   }
6872 }
6873
6874
6875 //===----------------------------------------------------------------------===//
6876 //  Other Lowering Code
6877 //===----------------------------------------------------------------------===//
6878
6879 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6880   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6881   Function *Func = Intrinsic::getDeclaration(M, Id);
6882   return Builder.CreateCall(Func);
6883 }
6884
6885 // The mappings for emitLeading/TrailingFence is taken from
6886 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6887 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6888                                          AtomicOrdering Ord, bool IsStore,
6889                                          bool IsLoad) const {
6890   if (Ord == SequentiallyConsistent)
6891     return callIntrinsic(Builder, Intrinsic::ppc_sync);
6892   else if (isAtLeastRelease(Ord))
6893     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6894   else
6895     return nullptr;
6896 }
6897
6898 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6899                                           AtomicOrdering Ord, bool IsStore,
6900                                           bool IsLoad) const {
6901   if (IsLoad && isAtLeastAcquire(Ord))
6902     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6903   // FIXME: this is too conservative, a dependent branch + isync is enough.
6904   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6905   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6906   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6907   else
6908     return nullptr;
6909 }
6910
6911 MachineBasicBlock *
6912 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6913                                     bool is64bit, unsigned BinOpcode) const {
6914   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6915   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6916
6917   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6918   MachineFunction *F = BB->getParent();
6919   MachineFunction::iterator It = BB;
6920   ++It;
6921
6922   unsigned dest = MI->getOperand(0).getReg();
6923   unsigned ptrA = MI->getOperand(1).getReg();
6924   unsigned ptrB = MI->getOperand(2).getReg();
6925   unsigned incr = MI->getOperand(3).getReg();
6926   DebugLoc dl = MI->getDebugLoc();
6927
6928   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6929   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6930   F->insert(It, loopMBB);
6931   F->insert(It, exitMBB);
6932   exitMBB->splice(exitMBB->begin(), BB,
6933                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6934   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6935
6936   MachineRegisterInfo &RegInfo = F->getRegInfo();
6937   unsigned TmpReg = (!BinOpcode) ? incr :
6938     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6939                                            : &PPC::GPRCRegClass);
6940
6941   //  thisMBB:
6942   //   ...
6943   //   fallthrough --> loopMBB
6944   BB->addSuccessor(loopMBB);
6945
6946   //  loopMBB:
6947   //   l[wd]arx dest, ptr
6948   //   add r0, dest, incr
6949   //   st[wd]cx. r0, ptr
6950   //   bne- loopMBB
6951   //   fallthrough --> exitMBB
6952   BB = loopMBB;
6953   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6954     .addReg(ptrA).addReg(ptrB);
6955   if (BinOpcode)
6956     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6957   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6958     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6959   BuildMI(BB, dl, TII->get(PPC::BCC))
6960     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6961   BB->addSuccessor(loopMBB);
6962   BB->addSuccessor(exitMBB);
6963
6964   //  exitMBB:
6965   //   ...
6966   BB = exitMBB;
6967   return BB;
6968 }
6969
6970 MachineBasicBlock *
6971 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6972                                             MachineBasicBlock *BB,
6973                                             bool is8bit,    // operation
6974                                             unsigned BinOpcode) const {
6975   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6976   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6977   // In 64 bit mode we have to use 64 bits for addresses, even though the
6978   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6979   // registers without caring whether they're 32 or 64, but here we're
6980   // doing actual arithmetic on the addresses.
6981   bool is64bit = Subtarget.isPPC64();
6982   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6983
6984   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6985   MachineFunction *F = BB->getParent();
6986   MachineFunction::iterator It = BB;
6987   ++It;
6988
6989   unsigned dest = MI->getOperand(0).getReg();
6990   unsigned ptrA = MI->getOperand(1).getReg();
6991   unsigned ptrB = MI->getOperand(2).getReg();
6992   unsigned incr = MI->getOperand(3).getReg();
6993   DebugLoc dl = MI->getDebugLoc();
6994
6995   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6996   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6997   F->insert(It, loopMBB);
6998   F->insert(It, exitMBB);
6999   exitMBB->splice(exitMBB->begin(), BB,
7000                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7001   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7002
7003   MachineRegisterInfo &RegInfo = F->getRegInfo();
7004   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7005                                           : &PPC::GPRCRegClass;
7006   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7007   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7008   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7009   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7010   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7011   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7012   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7013   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7014   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7015   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7016   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7017   unsigned Ptr1Reg;
7018   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7019
7020   //  thisMBB:
7021   //   ...
7022   //   fallthrough --> loopMBB
7023   BB->addSuccessor(loopMBB);
7024
7025   // The 4-byte load must be aligned, while a char or short may be
7026   // anywhere in the word.  Hence all this nasty bookkeeping code.
7027   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7028   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7029   //   xori shift, shift1, 24 [16]
7030   //   rlwinm ptr, ptr1, 0, 0, 29
7031   //   slw incr2, incr, shift
7032   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7033   //   slw mask, mask2, shift
7034   //  loopMBB:
7035   //   lwarx tmpDest, ptr
7036   //   add tmp, tmpDest, incr2
7037   //   andc tmp2, tmpDest, mask
7038   //   and tmp3, tmp, mask
7039   //   or tmp4, tmp3, tmp2
7040   //   stwcx. tmp4, ptr
7041   //   bne- loopMBB
7042   //   fallthrough --> exitMBB
7043   //   srw dest, tmpDest, shift
7044   if (ptrA != ZeroReg) {
7045     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7046     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7047       .addReg(ptrA).addReg(ptrB);
7048   } else {
7049     Ptr1Reg = ptrB;
7050   }
7051   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7052       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7053   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7054       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7055   if (is64bit)
7056     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7057       .addReg(Ptr1Reg).addImm(0).addImm(61);
7058   else
7059     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7060       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7061   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7062       .addReg(incr).addReg(ShiftReg);
7063   if (is8bit)
7064     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7065   else {
7066     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7067     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7068   }
7069   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7070       .addReg(Mask2Reg).addReg(ShiftReg);
7071
7072   BB = loopMBB;
7073   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7074     .addReg(ZeroReg).addReg(PtrReg);
7075   if (BinOpcode)
7076     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7077       .addReg(Incr2Reg).addReg(TmpDestReg);
7078   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7079     .addReg(TmpDestReg).addReg(MaskReg);
7080   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7081     .addReg(TmpReg).addReg(MaskReg);
7082   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7083     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7084   BuildMI(BB, dl, TII->get(PPC::STWCX))
7085     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7086   BuildMI(BB, dl, TII->get(PPC::BCC))
7087     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7088   BB->addSuccessor(loopMBB);
7089   BB->addSuccessor(exitMBB);
7090
7091   //  exitMBB:
7092   //   ...
7093   BB = exitMBB;
7094   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7095     .addReg(ShiftReg);
7096   return BB;
7097 }
7098
7099 llvm::MachineBasicBlock*
7100 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7101                                     MachineBasicBlock *MBB) const {
7102   DebugLoc DL = MI->getDebugLoc();
7103   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7104
7105   MachineFunction *MF = MBB->getParent();
7106   MachineRegisterInfo &MRI = MF->getRegInfo();
7107
7108   const BasicBlock *BB = MBB->getBasicBlock();
7109   MachineFunction::iterator I = MBB;
7110   ++I;
7111
7112   // Memory Reference
7113   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7114   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7115
7116   unsigned DstReg = MI->getOperand(0).getReg();
7117   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7118   assert(RC->hasType(MVT::i32) && "Invalid destination!");
7119   unsigned mainDstReg = MRI.createVirtualRegister(RC);
7120   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7121
7122   MVT PVT = getPointerTy();
7123   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7124          "Invalid Pointer Size!");
7125   // For v = setjmp(buf), we generate
7126   //
7127   // thisMBB:
7128   //  SjLjSetup mainMBB
7129   //  bl mainMBB
7130   //  v_restore = 1
7131   //  b sinkMBB
7132   //
7133   // mainMBB:
7134   //  buf[LabelOffset] = LR
7135   //  v_main = 0
7136   //
7137   // sinkMBB:
7138   //  v = phi(main, restore)
7139   //
7140
7141   MachineBasicBlock *thisMBB = MBB;
7142   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7143   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7144   MF->insert(I, mainMBB);
7145   MF->insert(I, sinkMBB);
7146
7147   MachineInstrBuilder MIB;
7148
7149   // Transfer the remainder of BB and its successor edges to sinkMBB.
7150   sinkMBB->splice(sinkMBB->begin(), MBB,
7151                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7152   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7153
7154   // Note that the structure of the jmp_buf used here is not compatible
7155   // with that used by libc, and is not designed to be. Specifically, it
7156   // stores only those 'reserved' registers that LLVM does not otherwise
7157   // understand how to spill. Also, by convention, by the time this
7158   // intrinsic is called, Clang has already stored the frame address in the
7159   // first slot of the buffer and stack address in the third. Following the
7160   // X86 target code, we'll store the jump address in the second slot. We also
7161   // need to save the TOC pointer (R2) to handle jumps between shared
7162   // libraries, and that will be stored in the fourth slot. The thread
7163   // identifier (R13) is not affected.
7164
7165   // thisMBB:
7166   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7167   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7168   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7169
7170   // Prepare IP either in reg.
7171   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7172   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7173   unsigned BufReg = MI->getOperand(1).getReg();
7174
7175   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7176     setUsesTOCBasePtr(*MBB->getParent());
7177     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7178             .addReg(PPC::X2)
7179             .addImm(TOCOffset)
7180             .addReg(BufReg);
7181     MIB.setMemRefs(MMOBegin, MMOEnd);
7182   }
7183
7184   // Naked functions never have a base pointer, and so we use r1. For all
7185   // other functions, this decision must be delayed until during PEI.
7186   unsigned BaseReg;
7187   if (MF->getFunction()->getAttributes().hasAttribute(
7188           AttributeSet::FunctionIndex, Attribute::Naked))
7189     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7190   else
7191     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7192
7193   MIB = BuildMI(*thisMBB, MI, DL,
7194                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7195             .addReg(BaseReg)
7196             .addImm(BPOffset)
7197             .addReg(BufReg);
7198   MIB.setMemRefs(MMOBegin, MMOEnd);
7199
7200   // Setup
7201   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7202   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7203   MIB.addRegMask(TRI->getNoPreservedMask());
7204
7205   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7206
7207   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7208           .addMBB(mainMBB);
7209   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7210
7211   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7212   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7213
7214   // mainMBB:
7215   //  mainDstReg = 0
7216   MIB =
7217       BuildMI(mainMBB, DL,
7218               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7219
7220   // Store IP
7221   if (Subtarget.isPPC64()) {
7222     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7223             .addReg(LabelReg)
7224             .addImm(LabelOffset)
7225             .addReg(BufReg);
7226   } else {
7227     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7228             .addReg(LabelReg)
7229             .addImm(LabelOffset)
7230             .addReg(BufReg);
7231   }
7232
7233   MIB.setMemRefs(MMOBegin, MMOEnd);
7234
7235   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7236   mainMBB->addSuccessor(sinkMBB);
7237
7238   // sinkMBB:
7239   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7240           TII->get(PPC::PHI), DstReg)
7241     .addReg(mainDstReg).addMBB(mainMBB)
7242     .addReg(restoreDstReg).addMBB(thisMBB);
7243
7244   MI->eraseFromParent();
7245   return sinkMBB;
7246 }
7247
7248 MachineBasicBlock *
7249 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7250                                      MachineBasicBlock *MBB) const {
7251   DebugLoc DL = MI->getDebugLoc();
7252   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7253
7254   MachineFunction *MF = MBB->getParent();
7255   MachineRegisterInfo &MRI = MF->getRegInfo();
7256
7257   // Memory Reference
7258   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7259   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7260
7261   MVT PVT = getPointerTy();
7262   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7263          "Invalid Pointer Size!");
7264
7265   const TargetRegisterClass *RC =
7266     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7267   unsigned Tmp = MRI.createVirtualRegister(RC);
7268   // Since FP is only updated here but NOT referenced, it's treated as GPR.
7269   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7270   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7271   unsigned BP =
7272       (PVT == MVT::i64)
7273           ? PPC::X30
7274           : (Subtarget.isSVR4ABI() &&
7275                      MF->getTarget().getRelocationModel() == Reloc::PIC_
7276                  ? PPC::R29
7277                  : PPC::R30);
7278
7279   MachineInstrBuilder MIB;
7280
7281   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7282   const int64_t SPOffset    = 2 * PVT.getStoreSize();
7283   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7284   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7285
7286   unsigned BufReg = MI->getOperand(0).getReg();
7287
7288   // Reload FP (the jumped-to function may not have had a
7289   // frame pointer, and if so, then its r31 will be restored
7290   // as necessary).
7291   if (PVT == MVT::i64) {
7292     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7293             .addImm(0)
7294             .addReg(BufReg);
7295   } else {
7296     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7297             .addImm(0)
7298             .addReg(BufReg);
7299   }
7300   MIB.setMemRefs(MMOBegin, MMOEnd);
7301
7302   // Reload IP
7303   if (PVT == MVT::i64) {
7304     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7305             .addImm(LabelOffset)
7306             .addReg(BufReg);
7307   } else {
7308     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7309             .addImm(LabelOffset)
7310             .addReg(BufReg);
7311   }
7312   MIB.setMemRefs(MMOBegin, MMOEnd);
7313
7314   // Reload SP
7315   if (PVT == MVT::i64) {
7316     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7317             .addImm(SPOffset)
7318             .addReg(BufReg);
7319   } else {
7320     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7321             .addImm(SPOffset)
7322             .addReg(BufReg);
7323   }
7324   MIB.setMemRefs(MMOBegin, MMOEnd);
7325
7326   // Reload BP
7327   if (PVT == MVT::i64) {
7328     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7329             .addImm(BPOffset)
7330             .addReg(BufReg);
7331   } else {
7332     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7333             .addImm(BPOffset)
7334             .addReg(BufReg);
7335   }
7336   MIB.setMemRefs(MMOBegin, MMOEnd);
7337
7338   // Reload TOC
7339   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7340     setUsesTOCBasePtr(*MBB->getParent());
7341     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7342             .addImm(TOCOffset)
7343             .addReg(BufReg);
7344
7345     MIB.setMemRefs(MMOBegin, MMOEnd);
7346   }
7347
7348   // Jump
7349   BuildMI(*MBB, MI, DL,
7350           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7351   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7352
7353   MI->eraseFromParent();
7354   return MBB;
7355 }
7356
7357 MachineBasicBlock *
7358 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7359                                                MachineBasicBlock *BB) const {
7360   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
7361       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7362     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
7363         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7364       // Call lowering should have added an r2 operand to indicate a dependence
7365       // on the TOC base pointer value. It can't however, because there is no
7366       // way to mark the dependence as implicit there, and so the stackmap code
7367       // will confuse it with a regular operand. Instead, add the dependence
7368       // here.
7369       setUsesTOCBasePtr(*BB->getParent());
7370       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
7371     }
7372
7373     return emitPatchPoint(MI, BB);
7374   }
7375
7376   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7377       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7378     return emitEHSjLjSetJmp(MI, BB);
7379   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7380              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7381     return emitEHSjLjLongJmp(MI, BB);
7382   }
7383
7384   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7385
7386   // To "insert" these instructions we actually have to insert their
7387   // control-flow patterns.
7388   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7389   MachineFunction::iterator It = BB;
7390   ++It;
7391
7392   MachineFunction *F = BB->getParent();
7393
7394   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7395                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
7396                               MI->getOpcode() == PPC::SELECT_I4 ||
7397                               MI->getOpcode() == PPC::SELECT_I8)) {
7398     SmallVector<MachineOperand, 2> Cond;
7399     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7400         MI->getOpcode() == PPC::SELECT_CC_I8)
7401       Cond.push_back(MI->getOperand(4));
7402     else
7403       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7404     Cond.push_back(MI->getOperand(1));
7405
7406     DebugLoc dl = MI->getDebugLoc();
7407     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7408                       Cond, MI->getOperand(2).getReg(),
7409                       MI->getOperand(3).getReg());
7410   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7411              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7412              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7413              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7414              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7415              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7416              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7417              MI->getOpcode() == PPC::SELECT_I4 ||
7418              MI->getOpcode() == PPC::SELECT_I8 ||
7419              MI->getOpcode() == PPC::SELECT_F4 ||
7420              MI->getOpcode() == PPC::SELECT_F8 ||
7421              MI->getOpcode() == PPC::SELECT_VRRC ||
7422              MI->getOpcode() == PPC::SELECT_VSFRC ||
7423              MI->getOpcode() == PPC::SELECT_VSRC) {
7424     // The incoming instruction knows the destination vreg to set, the
7425     // condition code register to branch on, the true/false values to
7426     // select between, and a branch opcode to use.
7427
7428     //  thisMBB:
7429     //  ...
7430     //   TrueVal = ...
7431     //   cmpTY ccX, r1, r2
7432     //   bCC copy1MBB
7433     //   fallthrough --> copy0MBB
7434     MachineBasicBlock *thisMBB = BB;
7435     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7436     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7437     DebugLoc dl = MI->getDebugLoc();
7438     F->insert(It, copy0MBB);
7439     F->insert(It, sinkMBB);
7440
7441     // Transfer the remainder of BB and its successor edges to sinkMBB.
7442     sinkMBB->splice(sinkMBB->begin(), BB,
7443                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7444     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7445
7446     // Next, add the true and fallthrough blocks as its successors.
7447     BB->addSuccessor(copy0MBB);
7448     BB->addSuccessor(sinkMBB);
7449
7450     if (MI->getOpcode() == PPC::SELECT_I4 ||
7451         MI->getOpcode() == PPC::SELECT_I8 ||
7452         MI->getOpcode() == PPC::SELECT_F4 ||
7453         MI->getOpcode() == PPC::SELECT_F8 ||
7454         MI->getOpcode() == PPC::SELECT_VRRC ||
7455         MI->getOpcode() == PPC::SELECT_VSFRC ||
7456         MI->getOpcode() == PPC::SELECT_VSRC) {
7457       BuildMI(BB, dl, TII->get(PPC::BC))
7458         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7459     } else {
7460       unsigned SelectPred = MI->getOperand(4).getImm();
7461       BuildMI(BB, dl, TII->get(PPC::BCC))
7462         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7463     }
7464
7465     //  copy0MBB:
7466     //   %FalseValue = ...
7467     //   # fallthrough to sinkMBB
7468     BB = copy0MBB;
7469
7470     // Update machine-CFG edges
7471     BB->addSuccessor(sinkMBB);
7472
7473     //  sinkMBB:
7474     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7475     //  ...
7476     BB = sinkMBB;
7477     BuildMI(*BB, BB->begin(), dl,
7478             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7479       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7480       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7481   } else if (MI->getOpcode() == PPC::ReadTB) {
7482     // To read the 64-bit time-base register on a 32-bit target, we read the
7483     // two halves. Should the counter have wrapped while it was being read, we
7484     // need to try again.
7485     // ...
7486     // readLoop:
7487     // mfspr Rx,TBU # load from TBU
7488     // mfspr Ry,TB  # load from TB
7489     // mfspr Rz,TBU # load from TBU
7490     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
7491     // bne readLoop   # branch if they're not equal
7492     // ...
7493
7494     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7495     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7496     DebugLoc dl = MI->getDebugLoc();
7497     F->insert(It, readMBB);
7498     F->insert(It, sinkMBB);
7499
7500     // Transfer the remainder of BB and its successor edges to sinkMBB.
7501     sinkMBB->splice(sinkMBB->begin(), BB,
7502                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7503     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7504
7505     BB->addSuccessor(readMBB);
7506     BB = readMBB;
7507
7508     MachineRegisterInfo &RegInfo = F->getRegInfo();
7509     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7510     unsigned LoReg = MI->getOperand(0).getReg();
7511     unsigned HiReg = MI->getOperand(1).getReg();
7512
7513     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7514     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7515     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7516
7517     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7518
7519     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7520       .addReg(HiReg).addReg(ReadAgainReg);
7521     BuildMI(BB, dl, TII->get(PPC::BCC))
7522       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7523
7524     BB->addSuccessor(readMBB);
7525     BB->addSuccessor(sinkMBB);
7526   }
7527   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7528     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7529   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7530     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7531   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7532     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7533   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7534     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7535
7536   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7537     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7538   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7539     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7540   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7541     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7542   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7543     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7544
7545   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7546     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7547   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7548     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7549   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7550     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7551   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7552     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7553
7554   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7555     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7556   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7557     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7558   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7559     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7560   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7561     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7562
7563   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7564     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7565   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7566     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7567   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7568     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7569   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7570     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7571
7572   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7573     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7574   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7575     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7576   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7577     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7578   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7579     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7580
7581   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7582     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7583   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7584     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7585   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7586     BB = EmitAtomicBinary(MI, BB, false, 0);
7587   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7588     BB = EmitAtomicBinary(MI, BB, true, 0);
7589
7590   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7591            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7592     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7593
7594     unsigned dest   = MI->getOperand(0).getReg();
7595     unsigned ptrA   = MI->getOperand(1).getReg();
7596     unsigned ptrB   = MI->getOperand(2).getReg();
7597     unsigned oldval = MI->getOperand(3).getReg();
7598     unsigned newval = MI->getOperand(4).getReg();
7599     DebugLoc dl     = MI->getDebugLoc();
7600
7601     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7602     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7603     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7604     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7605     F->insert(It, loop1MBB);
7606     F->insert(It, loop2MBB);
7607     F->insert(It, midMBB);
7608     F->insert(It, exitMBB);
7609     exitMBB->splice(exitMBB->begin(), BB,
7610                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7611     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7612
7613     //  thisMBB:
7614     //   ...
7615     //   fallthrough --> loopMBB
7616     BB->addSuccessor(loop1MBB);
7617
7618     // loop1MBB:
7619     //   l[wd]arx dest, ptr
7620     //   cmp[wd] dest, oldval
7621     //   bne- midMBB
7622     // loop2MBB:
7623     //   st[wd]cx. newval, ptr
7624     //   bne- loopMBB
7625     //   b exitBB
7626     // midMBB:
7627     //   st[wd]cx. dest, ptr
7628     // exitBB:
7629     BB = loop1MBB;
7630     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7631       .addReg(ptrA).addReg(ptrB);
7632     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7633       .addReg(oldval).addReg(dest);
7634     BuildMI(BB, dl, TII->get(PPC::BCC))
7635       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7636     BB->addSuccessor(loop2MBB);
7637     BB->addSuccessor(midMBB);
7638
7639     BB = loop2MBB;
7640     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7641       .addReg(newval).addReg(ptrA).addReg(ptrB);
7642     BuildMI(BB, dl, TII->get(PPC::BCC))
7643       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7644     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7645     BB->addSuccessor(loop1MBB);
7646     BB->addSuccessor(exitMBB);
7647
7648     BB = midMBB;
7649     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7650       .addReg(dest).addReg(ptrA).addReg(ptrB);
7651     BB->addSuccessor(exitMBB);
7652
7653     //  exitMBB:
7654     //   ...
7655     BB = exitMBB;
7656   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7657              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7658     // We must use 64-bit registers for addresses when targeting 64-bit,
7659     // since we're actually doing arithmetic on them.  Other registers
7660     // can be 32-bit.
7661     bool is64bit = Subtarget.isPPC64();
7662     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7663
7664     unsigned dest   = MI->getOperand(0).getReg();
7665     unsigned ptrA   = MI->getOperand(1).getReg();
7666     unsigned ptrB   = MI->getOperand(2).getReg();
7667     unsigned oldval = MI->getOperand(3).getReg();
7668     unsigned newval = MI->getOperand(4).getReg();
7669     DebugLoc dl     = MI->getDebugLoc();
7670
7671     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7672     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7673     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7674     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7675     F->insert(It, loop1MBB);
7676     F->insert(It, loop2MBB);
7677     F->insert(It, midMBB);
7678     F->insert(It, exitMBB);
7679     exitMBB->splice(exitMBB->begin(), BB,
7680                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7681     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7682
7683     MachineRegisterInfo &RegInfo = F->getRegInfo();
7684     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7685                                             : &PPC::GPRCRegClass;
7686     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7687     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7688     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7689     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7690     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7691     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7692     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7693     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7694     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7695     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7696     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7697     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7698     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7699     unsigned Ptr1Reg;
7700     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7701     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7702     //  thisMBB:
7703     //   ...
7704     //   fallthrough --> loopMBB
7705     BB->addSuccessor(loop1MBB);
7706
7707     // The 4-byte load must be aligned, while a char or short may be
7708     // anywhere in the word.  Hence all this nasty bookkeeping code.
7709     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7710     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7711     //   xori shift, shift1, 24 [16]
7712     //   rlwinm ptr, ptr1, 0, 0, 29
7713     //   slw newval2, newval, shift
7714     //   slw oldval2, oldval,shift
7715     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7716     //   slw mask, mask2, shift
7717     //   and newval3, newval2, mask
7718     //   and oldval3, oldval2, mask
7719     // loop1MBB:
7720     //   lwarx tmpDest, ptr
7721     //   and tmp, tmpDest, mask
7722     //   cmpw tmp, oldval3
7723     //   bne- midMBB
7724     // loop2MBB:
7725     //   andc tmp2, tmpDest, mask
7726     //   or tmp4, tmp2, newval3
7727     //   stwcx. tmp4, ptr
7728     //   bne- loop1MBB
7729     //   b exitBB
7730     // midMBB:
7731     //   stwcx. tmpDest, ptr
7732     // exitBB:
7733     //   srw dest, tmpDest, shift
7734     if (ptrA != ZeroReg) {
7735       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7736       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7737         .addReg(ptrA).addReg(ptrB);
7738     } else {
7739       Ptr1Reg = ptrB;
7740     }
7741     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7742         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7743     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7744         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7745     if (is64bit)
7746       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7747         .addReg(Ptr1Reg).addImm(0).addImm(61);
7748     else
7749       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7750         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7751     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7752         .addReg(newval).addReg(ShiftReg);
7753     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7754         .addReg(oldval).addReg(ShiftReg);
7755     if (is8bit)
7756       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7757     else {
7758       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7759       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7760         .addReg(Mask3Reg).addImm(65535);
7761     }
7762     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7763         .addReg(Mask2Reg).addReg(ShiftReg);
7764     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7765         .addReg(NewVal2Reg).addReg(MaskReg);
7766     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7767         .addReg(OldVal2Reg).addReg(MaskReg);
7768
7769     BB = loop1MBB;
7770     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7771         .addReg(ZeroReg).addReg(PtrReg);
7772     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7773         .addReg(TmpDestReg).addReg(MaskReg);
7774     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7775         .addReg(TmpReg).addReg(OldVal3Reg);
7776     BuildMI(BB, dl, TII->get(PPC::BCC))
7777         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7778     BB->addSuccessor(loop2MBB);
7779     BB->addSuccessor(midMBB);
7780
7781     BB = loop2MBB;
7782     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7783         .addReg(TmpDestReg).addReg(MaskReg);
7784     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7785         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7786     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7787         .addReg(ZeroReg).addReg(PtrReg);
7788     BuildMI(BB, dl, TII->get(PPC::BCC))
7789       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7790     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7791     BB->addSuccessor(loop1MBB);
7792     BB->addSuccessor(exitMBB);
7793
7794     BB = midMBB;
7795     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7796       .addReg(ZeroReg).addReg(PtrReg);
7797     BB->addSuccessor(exitMBB);
7798
7799     //  exitMBB:
7800     //   ...
7801     BB = exitMBB;
7802     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7803       .addReg(ShiftReg);
7804   } else if (MI->getOpcode() == PPC::FADDrtz) {
7805     // This pseudo performs an FADD with rounding mode temporarily forced
7806     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7807     // is not modeled at the SelectionDAG level.
7808     unsigned Dest = MI->getOperand(0).getReg();
7809     unsigned Src1 = MI->getOperand(1).getReg();
7810     unsigned Src2 = MI->getOperand(2).getReg();
7811     DebugLoc dl   = MI->getDebugLoc();
7812
7813     MachineRegisterInfo &RegInfo = F->getRegInfo();
7814     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7815
7816     // Save FPSCR value.
7817     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7818
7819     // Set rounding mode to round-to-zero.
7820     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7821     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7822
7823     // Perform addition.
7824     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7825
7826     // Restore FPSCR value.
7827     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
7828   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7829              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7830              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7831              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7832     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7833                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7834                       PPC::ANDIo8 : PPC::ANDIo;
7835     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7836                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7837
7838     MachineRegisterInfo &RegInfo = F->getRegInfo();
7839     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7840                                                   &PPC::GPRCRegClass :
7841                                                   &PPC::G8RCRegClass);
7842
7843     DebugLoc dl   = MI->getDebugLoc();
7844     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7845       .addReg(MI->getOperand(1).getReg()).addImm(1);
7846     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7847             MI->getOperand(0).getReg())
7848       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7849   } else {
7850     llvm_unreachable("Unexpected instr type to insert");
7851   }
7852
7853   MI->eraseFromParent();   // The pseudo instruction is gone now.
7854   return BB;
7855 }
7856
7857 //===----------------------------------------------------------------------===//
7858 // Target Optimization Hooks
7859 //===----------------------------------------------------------------------===//
7860
7861 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7862                                             DAGCombinerInfo &DCI,
7863                                             unsigned &RefinementSteps,
7864                                             bool &UseOneConstNR) const {
7865   EVT VT = Operand.getValueType();
7866   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7867       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7868       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7869       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7870     // Convergence is quadratic, so we essentially double the number of digits
7871     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7872     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7873     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7874     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7875     if (VT.getScalarType() == MVT::f64)
7876       ++RefinementSteps;
7877     UseOneConstNR = true;
7878     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7879   }
7880   return SDValue();
7881 }
7882
7883 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7884                                             DAGCombinerInfo &DCI,
7885                                             unsigned &RefinementSteps) const {
7886   EVT VT = Operand.getValueType();
7887   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7888       (VT == MVT::f64 && Subtarget.hasFRE()) ||
7889       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7890       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7891     // Convergence is quadratic, so we essentially double the number of digits
7892     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7893     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7894     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7895     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7896     if (VT.getScalarType() == MVT::f64)
7897       ++RefinementSteps;
7898     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7899   }
7900   return SDValue();
7901 }
7902
7903 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7904   // Note: This functionality is used only when unsafe-fp-math is enabled, and
7905   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7906   // enabled for division), this functionality is redundant with the default
7907   // combiner logic (once the division -> reciprocal/multiply transformation
7908   // has taken place). As a result, this matters more for older cores than for
7909   // newer ones.
7910
7911   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7912   // reciprocal if there are two or more FDIVs (for embedded cores with only
7913   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7914   switch (Subtarget.getDarwinDirective()) {
7915   default:
7916     return NumUsers > 2;
7917   case PPC::DIR_440:
7918   case PPC::DIR_A2:
7919   case PPC::DIR_E500mc:
7920   case PPC::DIR_E5500:
7921     return NumUsers > 1;
7922   }
7923 }
7924
7925 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7926                             unsigned Bytes, int Dist,
7927                             SelectionDAG &DAG) {
7928   if (VT.getSizeInBits() / 8 != Bytes)
7929     return false;
7930
7931   SDValue BaseLoc = Base->getBasePtr();
7932   if (Loc.getOpcode() == ISD::FrameIndex) {
7933     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7934       return false;
7935     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7936     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7937     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7938     int FS  = MFI->getObjectSize(FI);
7939     int BFS = MFI->getObjectSize(BFI);
7940     if (FS != BFS || FS != (int)Bytes) return false;
7941     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7942   }
7943
7944   // Handle X+C
7945   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7946       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7947     return true;
7948
7949   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7950   const GlobalValue *GV1 = nullptr;
7951   const GlobalValue *GV2 = nullptr;
7952   int64_t Offset1 = 0;
7953   int64_t Offset2 = 0;
7954   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7955   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7956   if (isGA1 && isGA2 && GV1 == GV2)
7957     return Offset1 == (Offset2 + Dist*Bytes);
7958   return false;
7959 }
7960
7961 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7962 // not enforce equality of the chain operands.
7963 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7964                             unsigned Bytes, int Dist,
7965                             SelectionDAG &DAG) {
7966   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7967     EVT VT = LS->getMemoryVT();
7968     SDValue Loc = LS->getBasePtr();
7969     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7970   }
7971
7972   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7973     EVT VT;
7974     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7975     default: return false;
7976     case Intrinsic::ppc_altivec_lvx:
7977     case Intrinsic::ppc_altivec_lvxl:
7978     case Intrinsic::ppc_vsx_lxvw4x:
7979       VT = MVT::v4i32;
7980       break;
7981     case Intrinsic::ppc_vsx_lxvd2x:
7982       VT = MVT::v2f64;
7983       break;
7984     case Intrinsic::ppc_altivec_lvebx:
7985       VT = MVT::i8;
7986       break;
7987     case Intrinsic::ppc_altivec_lvehx:
7988       VT = MVT::i16;
7989       break;
7990     case Intrinsic::ppc_altivec_lvewx:
7991       VT = MVT::i32;
7992       break;
7993     }
7994
7995     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7996   }
7997
7998   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7999     EVT VT;
8000     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8001     default: return false;
8002     case Intrinsic::ppc_altivec_stvx:
8003     case Intrinsic::ppc_altivec_stvxl:
8004     case Intrinsic::ppc_vsx_stxvw4x:
8005       VT = MVT::v4i32;
8006       break;
8007     case Intrinsic::ppc_vsx_stxvd2x:
8008       VT = MVT::v2f64;
8009       break;
8010     case Intrinsic::ppc_altivec_stvebx:
8011       VT = MVT::i8;
8012       break;
8013     case Intrinsic::ppc_altivec_stvehx:
8014       VT = MVT::i16;
8015       break;
8016     case Intrinsic::ppc_altivec_stvewx:
8017       VT = MVT::i32;
8018       break;
8019     }
8020
8021     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8022   }
8023
8024   return false;
8025 }
8026
8027 // Return true is there is a nearyby consecutive load to the one provided
8028 // (regardless of alignment). We search up and down the chain, looking though
8029 // token factors and other loads (but nothing else). As a result, a true result
8030 // indicates that it is safe to create a new consecutive load adjacent to the
8031 // load provided.
8032 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8033   SDValue Chain = LD->getChain();
8034   EVT VT = LD->getMemoryVT();
8035
8036   SmallSet<SDNode *, 16> LoadRoots;
8037   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8038   SmallSet<SDNode *, 16> Visited;
8039
8040   // First, search up the chain, branching to follow all token-factor operands.
8041   // If we find a consecutive load, then we're done, otherwise, record all
8042   // nodes just above the top-level loads and token factors.
8043   while (!Queue.empty()) {
8044     SDNode *ChainNext = Queue.pop_back_val();
8045     if (!Visited.insert(ChainNext).second)
8046       continue;
8047
8048     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8049       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8050         return true;
8051
8052       if (!Visited.count(ChainLD->getChain().getNode()))
8053         Queue.push_back(ChainLD->getChain().getNode());
8054     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8055       for (const SDUse &O : ChainNext->ops())
8056         if (!Visited.count(O.getNode()))
8057           Queue.push_back(O.getNode());
8058     } else
8059       LoadRoots.insert(ChainNext);
8060   }
8061
8062   // Second, search down the chain, starting from the top-level nodes recorded
8063   // in the first phase. These top-level nodes are the nodes just above all
8064   // loads and token factors. Starting with their uses, recursively look though
8065   // all loads (just the chain uses) and token factors to find a consecutive
8066   // load.
8067   Visited.clear();
8068   Queue.clear();
8069
8070   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8071        IE = LoadRoots.end(); I != IE; ++I) {
8072     Queue.push_back(*I);
8073        
8074     while (!Queue.empty()) {
8075       SDNode *LoadRoot = Queue.pop_back_val();
8076       if (!Visited.insert(LoadRoot).second)
8077         continue;
8078
8079       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8080         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8081           return true;
8082
8083       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8084            UE = LoadRoot->use_end(); UI != UE; ++UI)
8085         if (((isa<MemSDNode>(*UI) &&
8086             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8087             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8088           Queue.push_back(*UI);
8089     }
8090   }
8091
8092   return false;
8093 }
8094
8095 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8096                                                   DAGCombinerInfo &DCI) const {
8097   SelectionDAG &DAG = DCI.DAG;
8098   SDLoc dl(N);
8099
8100   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8101   // If we're tracking CR bits, we need to be careful that we don't have:
8102   //   trunc(binary-ops(zext(x), zext(y)))
8103   // or
8104   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8105   // such that we're unnecessarily moving things into GPRs when it would be
8106   // better to keep them in CR bits.
8107
8108   // Note that trunc here can be an actual i1 trunc, or can be the effective
8109   // truncation that comes from a setcc or select_cc.
8110   if (N->getOpcode() == ISD::TRUNCATE &&
8111       N->getValueType(0) != MVT::i1)
8112     return SDValue();
8113
8114   if (N->getOperand(0).getValueType() != MVT::i32 &&
8115       N->getOperand(0).getValueType() != MVT::i64)
8116     return SDValue();
8117
8118   if (N->getOpcode() == ISD::SETCC ||
8119       N->getOpcode() == ISD::SELECT_CC) {
8120     // If we're looking at a comparison, then we need to make sure that the
8121     // high bits (all except for the first) don't matter the result.
8122     ISD::CondCode CC =
8123       cast<CondCodeSDNode>(N->getOperand(
8124         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8125     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8126
8127     if (ISD::isSignedIntSetCC(CC)) {
8128       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
8129           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
8130         return SDValue();
8131     } else if (ISD::isUnsignedIntSetCC(CC)) {
8132       if (!DAG.MaskedValueIsZero(N->getOperand(0),
8133                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
8134           !DAG.MaskedValueIsZero(N->getOperand(1),
8135                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
8136         return SDValue();
8137     } else {
8138       // This is neither a signed nor an unsigned comparison, just make sure
8139       // that the high bits are equal.
8140       APInt Op1Zero, Op1One;
8141       APInt Op2Zero, Op2One;
8142       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8143       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8144
8145       // We don't really care about what is known about the first bit (if
8146       // anything), so clear it in all masks prior to comparing them.
8147       Op1Zero.clearBit(0); Op1One.clearBit(0);
8148       Op2Zero.clearBit(0); Op2One.clearBit(0);
8149
8150       if (Op1Zero != Op2Zero || Op1One != Op2One)
8151         return SDValue();
8152     }
8153   }
8154
8155   // We now know that the higher-order bits are irrelevant, we just need to
8156   // make sure that all of the intermediate operations are bit operations, and
8157   // all inputs are extensions.
8158   if (N->getOperand(0).getOpcode() != ISD::AND &&
8159       N->getOperand(0).getOpcode() != ISD::OR  &&
8160       N->getOperand(0).getOpcode() != ISD::XOR &&
8161       N->getOperand(0).getOpcode() != ISD::SELECT &&
8162       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8163       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8164       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8165       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8166       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8167     return SDValue();
8168
8169   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8170       N->getOperand(1).getOpcode() != ISD::AND &&
8171       N->getOperand(1).getOpcode() != ISD::OR  &&
8172       N->getOperand(1).getOpcode() != ISD::XOR &&
8173       N->getOperand(1).getOpcode() != ISD::SELECT &&
8174       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8175       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8176       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8177       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8178       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8179     return SDValue();
8180
8181   SmallVector<SDValue, 4> Inputs;
8182   SmallVector<SDValue, 8> BinOps, PromOps;
8183   SmallPtrSet<SDNode *, 16> Visited;
8184
8185   for (unsigned i = 0; i < 2; ++i) {
8186     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8187           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8188           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8189           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8190         isa<ConstantSDNode>(N->getOperand(i)))
8191       Inputs.push_back(N->getOperand(i));
8192     else
8193       BinOps.push_back(N->getOperand(i));
8194
8195     if (N->getOpcode() == ISD::TRUNCATE)
8196       break;
8197   }
8198
8199   // Visit all inputs, collect all binary operations (and, or, xor and
8200   // select) that are all fed by extensions. 
8201   while (!BinOps.empty()) {
8202     SDValue BinOp = BinOps.back();
8203     BinOps.pop_back();
8204
8205     if (!Visited.insert(BinOp.getNode()).second)
8206       continue;
8207
8208     PromOps.push_back(BinOp);
8209
8210     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8211       // The condition of the select is not promoted.
8212       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8213         continue;
8214       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8215         continue;
8216
8217       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8218             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8219             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8220            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8221           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8222         Inputs.push_back(BinOp.getOperand(i)); 
8223       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8224                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8225                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8226                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8227                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8228                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8229                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8230                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8231                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8232         BinOps.push_back(BinOp.getOperand(i));
8233       } else {
8234         // We have an input that is not an extension or another binary
8235         // operation; we'll abort this transformation.
8236         return SDValue();
8237       }
8238     }
8239   }
8240
8241   // Make sure that this is a self-contained cluster of operations (which
8242   // is not quite the same thing as saying that everything has only one
8243   // use).
8244   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8245     if (isa<ConstantSDNode>(Inputs[i]))
8246       continue;
8247
8248     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8249                               UE = Inputs[i].getNode()->use_end();
8250          UI != UE; ++UI) {
8251       SDNode *User = *UI;
8252       if (User != N && !Visited.count(User))
8253         return SDValue();
8254
8255       // Make sure that we're not going to promote the non-output-value
8256       // operand(s) or SELECT or SELECT_CC.
8257       // FIXME: Although we could sometimes handle this, and it does occur in
8258       // practice that one of the condition inputs to the select is also one of
8259       // the outputs, we currently can't deal with this.
8260       if (User->getOpcode() == ISD::SELECT) {
8261         if (User->getOperand(0) == Inputs[i])
8262           return SDValue();
8263       } else if (User->getOpcode() == ISD::SELECT_CC) {
8264         if (User->getOperand(0) == Inputs[i] ||
8265             User->getOperand(1) == Inputs[i])
8266           return SDValue();
8267       }
8268     }
8269   }
8270
8271   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8272     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8273                               UE = PromOps[i].getNode()->use_end();
8274          UI != UE; ++UI) {
8275       SDNode *User = *UI;
8276       if (User != N && !Visited.count(User))
8277         return SDValue();
8278
8279       // Make sure that we're not going to promote the non-output-value
8280       // operand(s) or SELECT or SELECT_CC.
8281       // FIXME: Although we could sometimes handle this, and it does occur in
8282       // practice that one of the condition inputs to the select is also one of
8283       // the outputs, we currently can't deal with this.
8284       if (User->getOpcode() == ISD::SELECT) {
8285         if (User->getOperand(0) == PromOps[i])
8286           return SDValue();
8287       } else if (User->getOpcode() == ISD::SELECT_CC) {
8288         if (User->getOperand(0) == PromOps[i] ||
8289             User->getOperand(1) == PromOps[i])
8290           return SDValue();
8291       }
8292     }
8293   }
8294
8295   // Replace all inputs with the extension operand.
8296   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8297     // Constants may have users outside the cluster of to-be-promoted nodes,
8298     // and so we need to replace those as we do the promotions.
8299     if (isa<ConstantSDNode>(Inputs[i]))
8300       continue;
8301     else
8302       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
8303   }
8304
8305   // Replace all operations (these are all the same, but have a different
8306   // (i1) return type). DAG.getNode will validate that the types of
8307   // a binary operator match, so go through the list in reverse so that
8308   // we've likely promoted both operands first. Any intermediate truncations or
8309   // extensions disappear.
8310   while (!PromOps.empty()) {
8311     SDValue PromOp = PromOps.back();
8312     PromOps.pop_back();
8313
8314     if (PromOp.getOpcode() == ISD::TRUNCATE ||
8315         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8316         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8317         PromOp.getOpcode() == ISD::ANY_EXTEND) {
8318       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8319           PromOp.getOperand(0).getValueType() != MVT::i1) {
8320         // The operand is not yet ready (see comment below).
8321         PromOps.insert(PromOps.begin(), PromOp);
8322         continue;
8323       }
8324
8325       SDValue RepValue = PromOp.getOperand(0);
8326       if (isa<ConstantSDNode>(RepValue))
8327         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8328
8329       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8330       continue;
8331     }
8332
8333     unsigned C;
8334     switch (PromOp.getOpcode()) {
8335     default:             C = 0; break;
8336     case ISD::SELECT:    C = 1; break;
8337     case ISD::SELECT_CC: C = 2; break;
8338     }
8339
8340     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8341          PromOp.getOperand(C).getValueType() != MVT::i1) ||
8342         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8343          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8344       // The to-be-promoted operands of this node have not yet been
8345       // promoted (this should be rare because we're going through the
8346       // list backward, but if one of the operands has several users in
8347       // this cluster of to-be-promoted nodes, it is possible).
8348       PromOps.insert(PromOps.begin(), PromOp);
8349       continue;
8350     }
8351
8352     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8353                                 PromOp.getNode()->op_end());
8354
8355     // If there are any constant inputs, make sure they're replaced now.
8356     for (unsigned i = 0; i < 2; ++i)
8357       if (isa<ConstantSDNode>(Ops[C+i]))
8358         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8359
8360     DAG.ReplaceAllUsesOfValueWith(PromOp,
8361       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8362   }
8363
8364   // Now we're left with the initial truncation itself.
8365   if (N->getOpcode() == ISD::TRUNCATE)
8366     return N->getOperand(0);
8367
8368   // Otherwise, this is a comparison. The operands to be compared have just
8369   // changed type (to i1), but everything else is the same.
8370   return SDValue(N, 0);
8371 }
8372
8373 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8374                                                   DAGCombinerInfo &DCI) const {
8375   SelectionDAG &DAG = DCI.DAG;
8376   SDLoc dl(N);
8377
8378   // If we're tracking CR bits, we need to be careful that we don't have:
8379   //   zext(binary-ops(trunc(x), trunc(y)))
8380   // or
8381   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8382   // such that we're unnecessarily moving things into CR bits that can more
8383   // efficiently stay in GPRs. Note that if we're not certain that the high
8384   // bits are set as required by the final extension, we still may need to do
8385   // some masking to get the proper behavior.
8386
8387   // This same functionality is important on PPC64 when dealing with
8388   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8389   // the return values of functions. Because it is so similar, it is handled
8390   // here as well.
8391
8392   if (N->getValueType(0) != MVT::i32 &&
8393       N->getValueType(0) != MVT::i64)
8394     return SDValue();
8395
8396   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
8397         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
8398     return SDValue();
8399
8400   if (N->getOperand(0).getOpcode() != ISD::AND &&
8401       N->getOperand(0).getOpcode() != ISD::OR  &&
8402       N->getOperand(0).getOpcode() != ISD::XOR &&
8403       N->getOperand(0).getOpcode() != ISD::SELECT &&
8404       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8405     return SDValue();
8406
8407   SmallVector<SDValue, 4> Inputs;
8408   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8409   SmallPtrSet<SDNode *, 16> Visited;
8410
8411   // Visit all inputs, collect all binary operations (and, or, xor and
8412   // select) that are all fed by truncations. 
8413   while (!BinOps.empty()) {
8414     SDValue BinOp = BinOps.back();
8415     BinOps.pop_back();
8416
8417     if (!Visited.insert(BinOp.getNode()).second)
8418       continue;
8419
8420     PromOps.push_back(BinOp);
8421
8422     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8423       // The condition of the select is not promoted.
8424       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8425         continue;
8426       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8427         continue;
8428
8429       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8430           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8431         Inputs.push_back(BinOp.getOperand(i)); 
8432       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8433                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8434                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8435                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8436                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8437         BinOps.push_back(BinOp.getOperand(i));
8438       } else {
8439         // We have an input that is not a truncation or another binary
8440         // operation; we'll abort this transformation.
8441         return SDValue();
8442       }
8443     }
8444   }
8445
8446   // The operands of a select that must be truncated when the select is
8447   // promoted because the operand is actually part of the to-be-promoted set.
8448   DenseMap<SDNode *, EVT> SelectTruncOp[2];
8449
8450   // Make sure that this is a self-contained cluster of operations (which
8451   // is not quite the same thing as saying that everything has only one
8452   // use).
8453   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8454     if (isa<ConstantSDNode>(Inputs[i]))
8455       continue;
8456
8457     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8458                               UE = Inputs[i].getNode()->use_end();
8459          UI != UE; ++UI) {
8460       SDNode *User = *UI;
8461       if (User != N && !Visited.count(User))
8462         return SDValue();
8463
8464       // If we're going to promote the non-output-value operand(s) or SELECT or
8465       // SELECT_CC, record them for truncation.
8466       if (User->getOpcode() == ISD::SELECT) {
8467         if (User->getOperand(0) == Inputs[i])
8468           SelectTruncOp[0].insert(std::make_pair(User,
8469                                     User->getOperand(0).getValueType()));
8470       } else if (User->getOpcode() == ISD::SELECT_CC) {
8471         if (User->getOperand(0) == Inputs[i])
8472           SelectTruncOp[0].insert(std::make_pair(User,
8473                                     User->getOperand(0).getValueType()));
8474         if (User->getOperand(1) == Inputs[i])
8475           SelectTruncOp[1].insert(std::make_pair(User,
8476                                     User->getOperand(1).getValueType()));
8477       }
8478     }
8479   }
8480
8481   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8482     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8483                               UE = PromOps[i].getNode()->use_end();
8484          UI != UE; ++UI) {
8485       SDNode *User = *UI;
8486       if (User != N && !Visited.count(User))
8487         return SDValue();
8488
8489       // If we're going to promote the non-output-value operand(s) or SELECT or
8490       // SELECT_CC, record them for truncation.
8491       if (User->getOpcode() == ISD::SELECT) {
8492         if (User->getOperand(0) == PromOps[i])
8493           SelectTruncOp[0].insert(std::make_pair(User,
8494                                     User->getOperand(0).getValueType()));
8495       } else if (User->getOpcode() == ISD::SELECT_CC) {
8496         if (User->getOperand(0) == PromOps[i])
8497           SelectTruncOp[0].insert(std::make_pair(User,
8498                                     User->getOperand(0).getValueType()));
8499         if (User->getOperand(1) == PromOps[i])
8500           SelectTruncOp[1].insert(std::make_pair(User,
8501                                     User->getOperand(1).getValueType()));
8502       }
8503     }
8504   }
8505
8506   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8507   bool ReallyNeedsExt = false;
8508   if (N->getOpcode() != ISD::ANY_EXTEND) {
8509     // If all of the inputs are not already sign/zero extended, then
8510     // we'll still need to do that at the end.
8511     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8512       if (isa<ConstantSDNode>(Inputs[i]))
8513         continue;
8514
8515       unsigned OpBits =
8516         Inputs[i].getOperand(0).getValueSizeInBits();
8517       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8518
8519       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8520            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8521                                   APInt::getHighBitsSet(OpBits,
8522                                                         OpBits-PromBits))) ||
8523           (N->getOpcode() == ISD::SIGN_EXTEND &&
8524            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8525              (OpBits-(PromBits-1)))) {
8526         ReallyNeedsExt = true;
8527         break;
8528       }
8529     }
8530   }
8531
8532   // Replace all inputs, either with the truncation operand, or a
8533   // truncation or extension to the final output type.
8534   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8535     // Constant inputs need to be replaced with the to-be-promoted nodes that
8536     // use them because they might have users outside of the cluster of
8537     // promoted nodes.
8538     if (isa<ConstantSDNode>(Inputs[i]))
8539       continue;
8540
8541     SDValue InSrc = Inputs[i].getOperand(0);
8542     if (Inputs[i].getValueType() == N->getValueType(0))
8543       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8544     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8545       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8546         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8547     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8548       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8549         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8550     else
8551       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8552         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8553   }
8554
8555   // Replace all operations (these are all the same, but have a different
8556   // (promoted) return type). DAG.getNode will validate that the types of
8557   // a binary operator match, so go through the list in reverse so that
8558   // we've likely promoted both operands first.
8559   while (!PromOps.empty()) {
8560     SDValue PromOp = PromOps.back();
8561     PromOps.pop_back();
8562
8563     unsigned C;
8564     switch (PromOp.getOpcode()) {
8565     default:             C = 0; break;
8566     case ISD::SELECT:    C = 1; break;
8567     case ISD::SELECT_CC: C = 2; break;
8568     }
8569
8570     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8571          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8572         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8573          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8574       // The to-be-promoted operands of this node have not yet been
8575       // promoted (this should be rare because we're going through the
8576       // list backward, but if one of the operands has several users in
8577       // this cluster of to-be-promoted nodes, it is possible).
8578       PromOps.insert(PromOps.begin(), PromOp);
8579       continue;
8580     }
8581
8582     // For SELECT and SELECT_CC nodes, we do a similar check for any
8583     // to-be-promoted comparison inputs.
8584     if (PromOp.getOpcode() == ISD::SELECT ||
8585         PromOp.getOpcode() == ISD::SELECT_CC) {
8586       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8587            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8588           (SelectTruncOp[1].count(PromOp.getNode()) &&
8589            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8590         PromOps.insert(PromOps.begin(), PromOp);
8591         continue;
8592       }
8593     }
8594
8595     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8596                                 PromOp.getNode()->op_end());
8597
8598     // If this node has constant inputs, then they'll need to be promoted here.
8599     for (unsigned i = 0; i < 2; ++i) {
8600       if (!isa<ConstantSDNode>(Ops[C+i]))
8601         continue;
8602       if (Ops[C+i].getValueType() == N->getValueType(0))
8603         continue;
8604
8605       if (N->getOpcode() == ISD::SIGN_EXTEND)
8606         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8607       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8608         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8609       else
8610         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8611     }
8612
8613     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8614     // truncate them again to the original value type.
8615     if (PromOp.getOpcode() == ISD::SELECT ||
8616         PromOp.getOpcode() == ISD::SELECT_CC) {
8617       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8618       if (SI0 != SelectTruncOp[0].end())
8619         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8620       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8621       if (SI1 != SelectTruncOp[1].end())
8622         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8623     }
8624
8625     DAG.ReplaceAllUsesOfValueWith(PromOp,
8626       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8627   }
8628
8629   // Now we're left with the initial extension itself.
8630   if (!ReallyNeedsExt)
8631     return N->getOperand(0);
8632
8633   // To zero extend, just mask off everything except for the first bit (in the
8634   // i1 case).
8635   if (N->getOpcode() == ISD::ZERO_EXTEND)
8636     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8637                        DAG.getConstant(APInt::getLowBitsSet(
8638                                          N->getValueSizeInBits(0), PromBits),
8639                                        N->getValueType(0)));
8640
8641   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8642          "Invalid extension type");
8643   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8644   SDValue ShiftCst =
8645     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8646   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8647                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8648                                  N->getOperand(0), ShiftCst), ShiftCst);
8649 }
8650
8651 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8652                                               DAGCombinerInfo &DCI) const {
8653   assert((N->getOpcode() == ISD::SINT_TO_FP ||
8654           N->getOpcode() == ISD::UINT_TO_FP) &&
8655          "Need an int -> FP conversion node here");
8656
8657   if (!Subtarget.has64BitSupport())
8658     return SDValue();
8659
8660   SelectionDAG &DAG = DCI.DAG;
8661   SDLoc dl(N);
8662   SDValue Op(N, 0);
8663
8664   // Don't handle ppc_fp128 here or i1 conversions.
8665   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8666     return SDValue();
8667   if (Op.getOperand(0).getValueType() == MVT::i1)
8668     return SDValue();
8669
8670   // For i32 intermediate values, unfortunately, the conversion functions
8671   // leave the upper 32 bits of the value are undefined. Within the set of
8672   // scalar instructions, we have no method for zero- or sign-extending the
8673   // value. Thus, we cannot handle i32 intermediate values here.
8674   if (Op.getOperand(0).getValueType() == MVT::i32)
8675     return SDValue();
8676
8677   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8678          "UINT_TO_FP is supported only with FPCVT");
8679
8680   // If we have FCFIDS, then use it when converting to single-precision.
8681   // Otherwise, convert to double-precision and then round.
8682   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8683                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8684                                                             : PPCISD::FCFIDS)
8685                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8686                                                             : PPCISD::FCFID);
8687   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8688                   ? MVT::f32
8689                   : MVT::f64;
8690
8691   // If we're converting from a float, to an int, and back to a float again,
8692   // then we don't need the store/load pair at all.
8693   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8694        Subtarget.hasFPCVT()) ||
8695       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8696     SDValue Src = Op.getOperand(0).getOperand(0);
8697     if (Src.getValueType() == MVT::f32) {
8698       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8699       DCI.AddToWorklist(Src.getNode());
8700     }
8701
8702     unsigned FCTOp =
8703       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8704                                                         PPCISD::FCTIDUZ;
8705
8706     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8707     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8708
8709     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8710       FP = DAG.getNode(ISD::FP_ROUND, dl,
8711                        MVT::f32, FP, DAG.getIntPtrConstant(0));
8712       DCI.AddToWorklist(FP.getNode());
8713     }
8714
8715     return FP;
8716   }
8717
8718   return SDValue();
8719 }
8720
8721 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8722 // builtins) into loads with swaps.
8723 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8724                                               DAGCombinerInfo &DCI) const {
8725   SelectionDAG &DAG = DCI.DAG;
8726   SDLoc dl(N);
8727   SDValue Chain;
8728   SDValue Base;
8729   MachineMemOperand *MMO;
8730
8731   switch (N->getOpcode()) {
8732   default:
8733     llvm_unreachable("Unexpected opcode for little endian VSX load");
8734   case ISD::LOAD: {
8735     LoadSDNode *LD = cast<LoadSDNode>(N);
8736     Chain = LD->getChain();
8737     Base = LD->getBasePtr();
8738     MMO = LD->getMemOperand();
8739     // If the MMO suggests this isn't a load of a full vector, leave
8740     // things alone.  For a built-in, we have to make the change for
8741     // correctness, so if there is a size problem that will be a bug.
8742     if (MMO->getSize() < 16)
8743       return SDValue();
8744     break;
8745   }
8746   case ISD::INTRINSIC_W_CHAIN: {
8747     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8748     Chain = Intrin->getChain();
8749     Base = Intrin->getBasePtr();
8750     MMO = Intrin->getMemOperand();
8751     break;
8752   }
8753   }
8754
8755   MVT VecTy = N->getValueType(0).getSimpleVT();
8756   SDValue LoadOps[] = { Chain, Base };
8757   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8758                                          DAG.getVTList(VecTy, MVT::Other),
8759                                          LoadOps, VecTy, MMO);
8760   DCI.AddToWorklist(Load.getNode());
8761   Chain = Load.getValue(1);
8762   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8763                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8764   DCI.AddToWorklist(Swap.getNode());
8765   return Swap;
8766 }
8767
8768 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8769 // builtins) into stores with swaps.
8770 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8771                                                DAGCombinerInfo &DCI) const {
8772   SelectionDAG &DAG = DCI.DAG;
8773   SDLoc dl(N);
8774   SDValue Chain;
8775   SDValue Base;
8776   unsigned SrcOpnd;
8777   MachineMemOperand *MMO;
8778
8779   switch (N->getOpcode()) {
8780   default:
8781     llvm_unreachable("Unexpected opcode for little endian VSX store");
8782   case ISD::STORE: {
8783     StoreSDNode *ST = cast<StoreSDNode>(N);
8784     Chain = ST->getChain();
8785     Base = ST->getBasePtr();
8786     MMO = ST->getMemOperand();
8787     SrcOpnd = 1;
8788     // If the MMO suggests this isn't a store of a full vector, leave
8789     // things alone.  For a built-in, we have to make the change for
8790     // correctness, so if there is a size problem that will be a bug.
8791     if (MMO->getSize() < 16)
8792       return SDValue();
8793     break;
8794   }
8795   case ISD::INTRINSIC_VOID: {
8796     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8797     Chain = Intrin->getChain();
8798     // Intrin->getBasePtr() oddly does not get what we want.
8799     Base = Intrin->getOperand(3);
8800     MMO = Intrin->getMemOperand();
8801     SrcOpnd = 2;
8802     break;
8803   }
8804   }
8805
8806   SDValue Src = N->getOperand(SrcOpnd);
8807   MVT VecTy = Src.getValueType().getSimpleVT();
8808   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8809                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8810   DCI.AddToWorklist(Swap.getNode());
8811   Chain = Swap.getValue(1);
8812   SDValue StoreOps[] = { Chain, Swap, Base };
8813   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8814                                           DAG.getVTList(MVT::Other),
8815                                           StoreOps, VecTy, MMO);
8816   DCI.AddToWorklist(Store.getNode());
8817   return Store;
8818 }
8819
8820 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8821                                              DAGCombinerInfo &DCI) const {
8822   SelectionDAG &DAG = DCI.DAG;
8823   SDLoc dl(N);
8824   switch (N->getOpcode()) {
8825   default: break;
8826   case PPCISD::SHL:
8827     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8828       if (C->isNullValue())   // 0 << V -> 0.
8829         return N->getOperand(0);
8830     }
8831     break;
8832   case PPCISD::SRL:
8833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8834       if (C->isNullValue())   // 0 >>u V -> 0.
8835         return N->getOperand(0);
8836     }
8837     break;
8838   case PPCISD::SRA:
8839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8840       if (C->isNullValue() ||   //  0 >>s V -> 0.
8841           C->isAllOnesValue())    // -1 >>s V -> -1.
8842         return N->getOperand(0);
8843     }
8844     break;
8845   case ISD::SIGN_EXTEND:
8846   case ISD::ZERO_EXTEND:
8847   case ISD::ANY_EXTEND: 
8848     return DAGCombineExtBoolTrunc(N, DCI);
8849   case ISD::TRUNCATE:
8850   case ISD::SETCC:
8851   case ISD::SELECT_CC:
8852     return DAGCombineTruncBoolExt(N, DCI);
8853   case ISD::SINT_TO_FP:
8854   case ISD::UINT_TO_FP:
8855     return combineFPToIntToFP(N, DCI);
8856   case ISD::STORE: {
8857     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8858     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
8859         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8860         N->getOperand(1).getValueType() == MVT::i32 &&
8861         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8862       SDValue Val = N->getOperand(1).getOperand(0);
8863       if (Val.getValueType() == MVT::f32) {
8864         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8865         DCI.AddToWorklist(Val.getNode());
8866       }
8867       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8868       DCI.AddToWorklist(Val.getNode());
8869
8870       SDValue Ops[] = {
8871         N->getOperand(0), Val, N->getOperand(2),
8872         DAG.getValueType(N->getOperand(1).getValueType())
8873       };
8874
8875       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8876               DAG.getVTList(MVT::Other), Ops,
8877               cast<StoreSDNode>(N)->getMemoryVT(),
8878               cast<StoreSDNode>(N)->getMemOperand());
8879       DCI.AddToWorklist(Val.getNode());
8880       return Val;
8881     }
8882
8883     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8884     if (cast<StoreSDNode>(N)->isUnindexed() &&
8885         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8886         N->getOperand(1).getNode()->hasOneUse() &&
8887         (N->getOperand(1).getValueType() == MVT::i32 ||
8888          N->getOperand(1).getValueType() == MVT::i16 ||
8889          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
8890           N->getOperand(1).getValueType() == MVT::i64))) {
8891       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8892       // Do an any-extend to 32-bits if this is a half-word input.
8893       if (BSwapOp.getValueType() == MVT::i16)
8894         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8895
8896       SDValue Ops[] = {
8897         N->getOperand(0), BSwapOp, N->getOperand(2),
8898         DAG.getValueType(N->getOperand(1).getValueType())
8899       };
8900       return
8901         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8902                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8903                                 cast<StoreSDNode>(N)->getMemOperand());
8904     }
8905
8906     // For little endian, VSX stores require generating xxswapd/lxvd2x.
8907     EVT VT = N->getOperand(1).getValueType();
8908     if (VT.isSimple()) {
8909       MVT StoreVT = VT.getSimpleVT();
8910       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8911           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8912            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8913         return expandVSXStoreForLE(N, DCI);
8914     }
8915     break;
8916   }
8917   case ISD::LOAD: {
8918     LoadSDNode *LD = cast<LoadSDNode>(N);
8919     EVT VT = LD->getValueType(0);
8920
8921     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8922     if (VT.isSimple()) {
8923       MVT LoadVT = VT.getSimpleVT();
8924       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8925           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8926            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8927         return expandVSXLoadForLE(N, DCI);
8928     }
8929
8930     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8931     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8932     if (ISD::isNON_EXTLoad(N) && VT.isVector() && Subtarget.hasAltivec() &&
8933         // P8 and later hardware should just use LOAD.
8934         !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8935                                      VT == MVT::v4i32 || VT == MVT::v4f32) &&
8936         LD->getAlignment() < ABIAlignment) {
8937       // This is a type-legal unaligned Altivec load.
8938       SDValue Chain = LD->getChain();
8939       SDValue Ptr = LD->getBasePtr();
8940       bool isLittleEndian = Subtarget.isLittleEndian();
8941
8942       // This implements the loading of unaligned vectors as described in
8943       // the venerable Apple Velocity Engine overview. Specifically:
8944       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8945       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8946       //
8947       // The general idea is to expand a sequence of one or more unaligned
8948       // loads into an alignment-based permutation-control instruction (lvsl
8949       // or lvsr), a series of regular vector loads (which always truncate
8950       // their input address to an aligned address), and a series of
8951       // permutations.  The results of these permutations are the requested
8952       // loaded values.  The trick is that the last "extra" load is not taken
8953       // from the address you might suspect (sizeof(vector) bytes after the
8954       // last requested load), but rather sizeof(vector) - 1 bytes after the
8955       // last requested vector. The point of this is to avoid a page fault if
8956       // the base address happened to be aligned. This works because if the
8957       // base address is aligned, then adding less than a full vector length
8958       // will cause the last vector in the sequence to be (re)loaded.
8959       // Otherwise, the next vector will be fetched as you might suspect was
8960       // necessary.
8961
8962       // We might be able to reuse the permutation generation from
8963       // a different base address offset from this one by an aligned amount.
8964       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8965       // optimization later.
8966       Intrinsic::ID Intr = (isLittleEndian ?
8967                             Intrinsic::ppc_altivec_lvsr :
8968                             Intrinsic::ppc_altivec_lvsl);
8969       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8970
8971       // Create the new MMO for the new base load. It is like the original MMO,
8972       // but represents an area in memory almost twice the vector size centered
8973       // on the original address. If the address is unaligned, we might start
8974       // reading up to (sizeof(vector)-1) bytes below the address of the
8975       // original unaligned load.
8976       MachineFunction &MF = DAG.getMachineFunction();
8977       MachineMemOperand *BaseMMO =
8978         MF.getMachineMemOperand(LD->getMemOperand(),
8979                                 -LD->getMemoryVT().getStoreSize()+1,
8980                                 2*LD->getMemoryVT().getStoreSize()-1);
8981
8982       // Create the new base load.
8983       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8984                                                getPointerTy());
8985       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8986       SDValue BaseLoad =
8987         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8988                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8989                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8990
8991       // Note that the value of IncOffset (which is provided to the next
8992       // load's pointer info offset value, and thus used to calculate the
8993       // alignment), and the value of IncValue (which is actually used to
8994       // increment the pointer value) are different! This is because we
8995       // require the next load to appear to be aligned, even though it
8996       // is actually offset from the base pointer by a lesser amount.
8997       int IncOffset = VT.getSizeInBits() / 8;
8998       int IncValue = IncOffset;
8999
9000       // Walk (both up and down) the chain looking for another load at the real
9001       // (aligned) offset (the alignment of the other load does not matter in
9002       // this case). If found, then do not use the offset reduction trick, as
9003       // that will prevent the loads from being later combined (as they would
9004       // otherwise be duplicates).
9005       if (!findConsecutiveLoad(LD, DAG))
9006         --IncValue;
9007
9008       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9009       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9010
9011       MachineMemOperand *ExtraMMO =
9012         MF.getMachineMemOperand(LD->getMemOperand(),
9013                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
9014       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9015       SDValue ExtraLoad =
9016         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9017                                 DAG.getVTList(MVT::v4i32, MVT::Other),
9018                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
9019
9020       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9021         BaseLoad.getValue(1), ExtraLoad.getValue(1));
9022
9023       // Because vperm has a big-endian bias, we must reverse the order
9024       // of the input vectors and complement the permute control vector
9025       // when generating little endian code.  We have already handled the
9026       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9027       // and ExtraLoad here.
9028       SDValue Perm;
9029       if (isLittleEndian)
9030         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9031                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9032       else
9033         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9034                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9035
9036       if (VT != MVT::v4i32)
9037         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
9038
9039       // The output of the permutation is our loaded result, the TokenFactor is
9040       // our new chain.
9041       DCI.CombineTo(N, Perm, TF);
9042       return SDValue(N, 0);
9043     }
9044     }
9045     break;
9046     case ISD::INTRINSIC_WO_CHAIN: {
9047       bool isLittleEndian = Subtarget.isLittleEndian();
9048       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9049                                            : Intrinsic::ppc_altivec_lvsl);
9050       if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
9051           N->getOperand(1)->getOpcode() == ISD::ADD) {
9052         SDValue Add = N->getOperand(1);
9053
9054         if (DAG.MaskedValueIsZero(
9055                 Add->getOperand(1),
9056                 APInt::getAllOnesValue(4 /* 16 byte alignment */)
9057                     .zext(
9058                         Add.getValueType().getScalarType().getSizeInBits()))) {
9059           SDNode *BasePtr = Add->getOperand(0).getNode();
9060           for (SDNode::use_iterator UI = BasePtr->use_begin(),
9061                                     UE = BasePtr->use_end();
9062                UI != UE; ++UI) {
9063             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9064                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
9065                     Intr) {
9066               // We've found another LVSL/LVSR, and this address is an aligned
9067               // multiple of that one. The results will be the same, so use the
9068               // one we've just found instead.
9069
9070               return SDValue(*UI, 0);
9071             }
9072           }
9073         }
9074       }
9075     }
9076
9077     break;
9078   case ISD::INTRINSIC_W_CHAIN: {
9079     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9080     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9081       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9082       default:
9083         break;
9084       case Intrinsic::ppc_vsx_lxvw4x:
9085       case Intrinsic::ppc_vsx_lxvd2x:
9086         return expandVSXLoadForLE(N, DCI);
9087       }
9088     }
9089     break;
9090   }
9091   case ISD::INTRINSIC_VOID: {
9092     // For little endian, VSX stores require generating xxswapd/stxvd2x.
9093     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9094       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9095       default:
9096         break;
9097       case Intrinsic::ppc_vsx_stxvw4x:
9098       case Intrinsic::ppc_vsx_stxvd2x:
9099         return expandVSXStoreForLE(N, DCI);
9100       }
9101     }
9102     break;
9103   }
9104   case ISD::BSWAP:
9105     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
9106     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
9107         N->getOperand(0).hasOneUse() &&
9108         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
9109          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9110           N->getValueType(0) == MVT::i64))) {
9111       SDValue Load = N->getOperand(0);
9112       LoadSDNode *LD = cast<LoadSDNode>(Load);
9113       // Create the byte-swapping load.
9114       SDValue Ops[] = {
9115         LD->getChain(),    // Chain
9116         LD->getBasePtr(),  // Ptr
9117         DAG.getValueType(N->getValueType(0)) // VT
9118       };
9119       SDValue BSLoad =
9120         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
9121                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
9122                                               MVT::i64 : MVT::i32, MVT::Other),
9123                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9124
9125       // If this is an i16 load, insert the truncate.
9126       SDValue ResVal = BSLoad;
9127       if (N->getValueType(0) == MVT::i16)
9128         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
9129
9130       // First, combine the bswap away.  This makes the value produced by the
9131       // load dead.
9132       DCI.CombineTo(N, ResVal);
9133
9134       // Next, combine the load away, we give it a bogus result value but a real
9135       // chain result.  The result value is dead because the bswap is dead.
9136       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9137
9138       // Return N so it doesn't get rechecked!
9139       return SDValue(N, 0);
9140     }
9141
9142     break;
9143   case PPCISD::VCMP: {
9144     // If a VCMPo node already exists with exactly the same operands as this
9145     // node, use its result instead of this node (VCMPo computes both a CR6 and
9146     // a normal output).
9147     //
9148     if (!N->getOperand(0).hasOneUse() &&
9149         !N->getOperand(1).hasOneUse() &&
9150         !N->getOperand(2).hasOneUse()) {
9151
9152       // Scan all of the users of the LHS, looking for VCMPo's that match.
9153       SDNode *VCMPoNode = nullptr;
9154
9155       SDNode *LHSN = N->getOperand(0).getNode();
9156       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9157            UI != E; ++UI)
9158         if (UI->getOpcode() == PPCISD::VCMPo &&
9159             UI->getOperand(1) == N->getOperand(1) &&
9160             UI->getOperand(2) == N->getOperand(2) &&
9161             UI->getOperand(0) == N->getOperand(0)) {
9162           VCMPoNode = *UI;
9163           break;
9164         }
9165
9166       // If there is no VCMPo node, or if the flag value has a single use, don't
9167       // transform this.
9168       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9169         break;
9170
9171       // Look at the (necessarily single) use of the flag value.  If it has a
9172       // chain, this transformation is more complex.  Note that multiple things
9173       // could use the value result, which we should ignore.
9174       SDNode *FlagUser = nullptr;
9175       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9176            FlagUser == nullptr; ++UI) {
9177         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9178         SDNode *User = *UI;
9179         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9180           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9181             FlagUser = User;
9182             break;
9183           }
9184         }
9185       }
9186
9187       // If the user is a MFOCRF instruction, we know this is safe.
9188       // Otherwise we give up for right now.
9189       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9190         return SDValue(VCMPoNode, 0);
9191     }
9192     break;
9193   }
9194   case ISD::BRCOND: {
9195     SDValue Cond = N->getOperand(1);
9196     SDValue Target = N->getOperand(2);
9197  
9198     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9199         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9200           Intrinsic::ppc_is_decremented_ctr_nonzero) {
9201
9202       // We now need to make the intrinsic dead (it cannot be instruction
9203       // selected).
9204       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9205       assert(Cond.getNode()->hasOneUse() &&
9206              "Counter decrement has more than one use");
9207
9208       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9209                          N->getOperand(0), Target);
9210     }
9211   }
9212   break;
9213   case ISD::BR_CC: {
9214     // If this is a branch on an altivec predicate comparison, lower this so
9215     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
9216     // lowering is done pre-legalize, because the legalizer lowers the predicate
9217     // compare down to code that is difficult to reassemble.
9218     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9219     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9220
9221     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9222     // value. If so, pass-through the AND to get to the intrinsic.
9223     if (LHS.getOpcode() == ISD::AND &&
9224         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9225         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9226           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9227         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9228         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9229           isZero())
9230       LHS = LHS.getOperand(0);
9231
9232     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9233         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9234           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9235         isa<ConstantSDNode>(RHS)) {
9236       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9237              "Counter decrement comparison is not EQ or NE");
9238
9239       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9240       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9241                     (CC == ISD::SETNE && !Val);
9242
9243       // We now need to make the intrinsic dead (it cannot be instruction
9244       // selected).
9245       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9246       assert(LHS.getNode()->hasOneUse() &&
9247              "Counter decrement has more than one use");
9248
9249       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9250                          N->getOperand(0), N->getOperand(4));
9251     }
9252
9253     int CompareOpc;
9254     bool isDot;
9255
9256     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9257         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9258         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9259       assert(isDot && "Can't compare against a vector result!");
9260
9261       // If this is a comparison against something other than 0/1, then we know
9262       // that the condition is never/always true.
9263       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9264       if (Val != 0 && Val != 1) {
9265         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
9266           return N->getOperand(0);
9267         // Always !=, turn it into an unconditional branch.
9268         return DAG.getNode(ISD::BR, dl, MVT::Other,
9269                            N->getOperand(0), N->getOperand(4));
9270       }
9271
9272       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9273
9274       // Create the PPCISD altivec 'dot' comparison node.
9275       SDValue Ops[] = {
9276         LHS.getOperand(2),  // LHS of compare
9277         LHS.getOperand(3),  // RHS of compare
9278         DAG.getConstant(CompareOpc, MVT::i32)
9279       };
9280       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9281       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9282
9283       // Unpack the result based on how the target uses it.
9284       PPC::Predicate CompOpc;
9285       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9286       default:  // Can't happen, don't crash on invalid number though.
9287       case 0:   // Branch on the value of the EQ bit of CR6.
9288         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9289         break;
9290       case 1:   // Branch on the inverted value of the EQ bit of CR6.
9291         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9292         break;
9293       case 2:   // Branch on the value of the LT bit of CR6.
9294         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9295         break;
9296       case 3:   // Branch on the inverted value of the LT bit of CR6.
9297         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9298         break;
9299       }
9300
9301       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9302                          DAG.getConstant(CompOpc, MVT::i32),
9303                          DAG.getRegister(PPC::CR6, MVT::i32),
9304                          N->getOperand(4), CompNode.getValue(1));
9305     }
9306     break;
9307   }
9308   }
9309
9310   return SDValue();
9311 }
9312
9313 SDValue
9314 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9315                                   SelectionDAG &DAG,
9316                                   std::vector<SDNode *> *Created) const {
9317   // fold (sdiv X, pow2)
9318   EVT VT = N->getValueType(0);
9319   if (VT == MVT::i64 && !Subtarget.isPPC64())
9320     return SDValue();
9321   if ((VT != MVT::i32 && VT != MVT::i64) ||
9322       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9323     return SDValue();
9324
9325   SDLoc DL(N);
9326   SDValue N0 = N->getOperand(0);
9327
9328   bool IsNegPow2 = (-Divisor).isPowerOf2();
9329   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9330   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9331
9332   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9333   if (Created)
9334     Created->push_back(Op.getNode());
9335
9336   if (IsNegPow2) {
9337     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9338     if (Created)
9339       Created->push_back(Op.getNode());
9340   }
9341
9342   return Op;
9343 }
9344
9345 //===----------------------------------------------------------------------===//
9346 // Inline Assembly Support
9347 //===----------------------------------------------------------------------===//
9348
9349 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9350                                                       APInt &KnownZero,
9351                                                       APInt &KnownOne,
9352                                                       const SelectionDAG &DAG,
9353                                                       unsigned Depth) const {
9354   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9355   switch (Op.getOpcode()) {
9356   default: break;
9357   case PPCISD::LBRX: {
9358     // lhbrx is known to have the top bits cleared out.
9359     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9360       KnownZero = 0xFFFF0000;
9361     break;
9362   }
9363   case ISD::INTRINSIC_WO_CHAIN: {
9364     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9365     default: break;
9366     case Intrinsic::ppc_altivec_vcmpbfp_p:
9367     case Intrinsic::ppc_altivec_vcmpeqfp_p:
9368     case Intrinsic::ppc_altivec_vcmpequb_p:
9369     case Intrinsic::ppc_altivec_vcmpequh_p:
9370     case Intrinsic::ppc_altivec_vcmpequw_p:
9371     case Intrinsic::ppc_altivec_vcmpgefp_p:
9372     case Intrinsic::ppc_altivec_vcmpgtfp_p:
9373     case Intrinsic::ppc_altivec_vcmpgtsb_p:
9374     case Intrinsic::ppc_altivec_vcmpgtsh_p:
9375     case Intrinsic::ppc_altivec_vcmpgtsw_p:
9376     case Intrinsic::ppc_altivec_vcmpgtub_p:
9377     case Intrinsic::ppc_altivec_vcmpgtuh_p:
9378     case Intrinsic::ppc_altivec_vcmpgtuw_p:
9379       KnownZero = ~1U;  // All bits but the low one are known to be zero.
9380       break;
9381     }
9382   }
9383   }
9384 }
9385
9386 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9387   switch (Subtarget.getDarwinDirective()) {
9388   default: break;
9389   case PPC::DIR_970:
9390   case PPC::DIR_PWR4:
9391   case PPC::DIR_PWR5:
9392   case PPC::DIR_PWR5X:
9393   case PPC::DIR_PWR6:
9394   case PPC::DIR_PWR6X:
9395   case PPC::DIR_PWR7:
9396   case PPC::DIR_PWR8: {
9397     if (!ML)
9398       break;
9399
9400     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
9401
9402     // For small loops (between 5 and 8 instructions), align to a 32-byte
9403     // boundary so that the entire loop fits in one instruction-cache line.
9404     uint64_t LoopSize = 0;
9405     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9406       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9407         LoopSize += TII->GetInstSizeInBytes(J);
9408
9409     if (LoopSize > 16 && LoopSize <= 32)
9410       return 5;
9411
9412     break;
9413   }
9414   }
9415
9416   return TargetLowering::getPrefLoopAlignment(ML);
9417 }
9418
9419 /// getConstraintType - Given a constraint, return the type of
9420 /// constraint it is for this target.
9421 PPCTargetLowering::ConstraintType
9422 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9423   if (Constraint.size() == 1) {
9424     switch (Constraint[0]) {
9425     default: break;
9426     case 'b':
9427     case 'r':
9428     case 'f':
9429     case 'v':
9430     case 'y':
9431       return C_RegisterClass;
9432     case 'Z':
9433       // FIXME: While Z does indicate a memory constraint, it specifically
9434       // indicates an r+r address (used in conjunction with the 'y' modifier
9435       // in the replacement string). Currently, we're forcing the base
9436       // register to be r0 in the asm printer (which is interpreted as zero)
9437       // and forming the complete address in the second register. This is
9438       // suboptimal.
9439       return C_Memory;
9440     }
9441   } else if (Constraint == "wc") { // individual CR bits.
9442     return C_RegisterClass;
9443   } else if (Constraint == "wa" || Constraint == "wd" ||
9444              Constraint == "wf" || Constraint == "ws") {
9445     return C_RegisterClass; // VSX registers.
9446   }
9447   return TargetLowering::getConstraintType(Constraint);
9448 }
9449
9450 /// Examine constraint type and operand type and determine a weight value.
9451 /// This object must already have been set up with the operand type
9452 /// and the current alternative constraint selected.
9453 TargetLowering::ConstraintWeight
9454 PPCTargetLowering::getSingleConstraintMatchWeight(
9455     AsmOperandInfo &info, const char *constraint) const {
9456   ConstraintWeight weight = CW_Invalid;
9457   Value *CallOperandVal = info.CallOperandVal;
9458     // If we don't have a value, we can't do a match,
9459     // but allow it at the lowest weight.
9460   if (!CallOperandVal)
9461     return CW_Default;
9462   Type *type = CallOperandVal->getType();
9463
9464   // Look at the constraint type.
9465   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9466     return CW_Register; // an individual CR bit.
9467   else if ((StringRef(constraint) == "wa" ||
9468             StringRef(constraint) == "wd" ||
9469             StringRef(constraint) == "wf") &&
9470            type->isVectorTy())
9471     return CW_Register;
9472   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9473     return CW_Register;
9474
9475   switch (*constraint) {
9476   default:
9477     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9478     break;
9479   case 'b':
9480     if (type->isIntegerTy())
9481       weight = CW_Register;
9482     break;
9483   case 'f':
9484     if (type->isFloatTy())
9485       weight = CW_Register;
9486     break;
9487   case 'd':
9488     if (type->isDoubleTy())
9489       weight = CW_Register;
9490     break;
9491   case 'v':
9492     if (type->isVectorTy())
9493       weight = CW_Register;
9494     break;
9495   case 'y':
9496     weight = CW_Register;
9497     break;
9498   case 'Z':
9499     weight = CW_Memory;
9500     break;
9501   }
9502   return weight;
9503 }
9504
9505 std::pair<unsigned, const TargetRegisterClass*>
9506 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9507                                                 MVT VT) const {
9508   if (Constraint.size() == 1) {
9509     // GCC RS6000 Constraint Letters
9510     switch (Constraint[0]) {
9511     case 'b':   // R1-R31
9512       if (VT == MVT::i64 && Subtarget.isPPC64())
9513         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9514       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9515     case 'r':   // R0-R31
9516       if (VT == MVT::i64 && Subtarget.isPPC64())
9517         return std::make_pair(0U, &PPC::G8RCRegClass);
9518       return std::make_pair(0U, &PPC::GPRCRegClass);
9519     case 'f':
9520       if (VT == MVT::f32 || VT == MVT::i32)
9521         return std::make_pair(0U, &PPC::F4RCRegClass);
9522       if (VT == MVT::f64 || VT == MVT::i64)
9523         return std::make_pair(0U, &PPC::F8RCRegClass);
9524       break;
9525     case 'v':
9526       return std::make_pair(0U, &PPC::VRRCRegClass);
9527     case 'y':   // crrc
9528       return std::make_pair(0U, &PPC::CRRCRegClass);
9529     }
9530   } else if (Constraint == "wc") { // an individual CR bit.
9531     return std::make_pair(0U, &PPC::CRBITRCRegClass);
9532   } else if (Constraint == "wa" || Constraint == "wd" ||
9533              Constraint == "wf") {
9534     return std::make_pair(0U, &PPC::VSRCRegClass);
9535   } else if (Constraint == "ws") {
9536     return std::make_pair(0U, &PPC::VSFRCRegClass);
9537   }
9538
9539   std::pair<unsigned, const TargetRegisterClass*> R =
9540     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9541
9542   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9543   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9544   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9545   // register.
9546   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9547   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9548   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9549       PPC::GPRCRegClass.contains(R.first)) {
9550     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9551     return std::make_pair(TRI->getMatchingSuperReg(R.first,
9552                             PPC::sub_32, &PPC::G8RCRegClass),
9553                           &PPC::G8RCRegClass);
9554   }
9555
9556   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9557   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9558     R.first = PPC::CR0;
9559     R.second = &PPC::CRRCRegClass;
9560   }
9561
9562   return R;
9563 }
9564
9565
9566 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9567 /// vector.  If it is invalid, don't add anything to Ops.
9568 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9569                                                      std::string &Constraint,
9570                                                      std::vector<SDValue>&Ops,
9571                                                      SelectionDAG &DAG) const {
9572   SDValue Result;
9573
9574   // Only support length 1 constraints.
9575   if (Constraint.length() > 1) return;
9576
9577   char Letter = Constraint[0];
9578   switch (Letter) {
9579   default: break;
9580   case 'I':
9581   case 'J':
9582   case 'K':
9583   case 'L':
9584   case 'M':
9585   case 'N':
9586   case 'O':
9587   case 'P': {
9588     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9589     if (!CST) return; // Must be an immediate to match.
9590     int64_t Value = CST->getSExtValue();
9591     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9592                          // numbers are printed as such.
9593     switch (Letter) {
9594     default: llvm_unreachable("Unknown constraint letter!");
9595     case 'I':  // "I" is a signed 16-bit constant.
9596       if (isInt<16>(Value))
9597         Result = DAG.getTargetConstant(Value, TCVT);
9598       break;
9599     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9600       if (isShiftedUInt<16, 16>(Value))
9601         Result = DAG.getTargetConstant(Value, TCVT);
9602       break;
9603     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9604       if (isShiftedInt<16, 16>(Value))
9605         Result = DAG.getTargetConstant(Value, TCVT);
9606       break;
9607     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9608       if (isUInt<16>(Value))
9609         Result = DAG.getTargetConstant(Value, TCVT);
9610       break;
9611     case 'M':  // "M" is a constant that is greater than 31.
9612       if (Value > 31)
9613         Result = DAG.getTargetConstant(Value, TCVT);
9614       break;
9615     case 'N':  // "N" is a positive constant that is an exact power of two.
9616       if (Value > 0 && isPowerOf2_64(Value))
9617         Result = DAG.getTargetConstant(Value, TCVT);
9618       break;
9619     case 'O':  // "O" is the constant zero.
9620       if (Value == 0)
9621         Result = DAG.getTargetConstant(Value, TCVT);
9622       break;
9623     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9624       if (isInt<16>(-Value))
9625         Result = DAG.getTargetConstant(Value, TCVT);
9626       break;
9627     }
9628     break;
9629   }
9630   }
9631
9632   if (Result.getNode()) {
9633     Ops.push_back(Result);
9634     return;
9635   }
9636
9637   // Handle standard constraint letters.
9638   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9639 }
9640
9641 // isLegalAddressingMode - Return true if the addressing mode represented
9642 // by AM is legal for this target, for a load/store of the specified type.
9643 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9644                                               Type *Ty) const {
9645   // FIXME: PPC does not allow r+i addressing modes for vectors!
9646
9647   // PPC allows a sign-extended 16-bit immediate field.
9648   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9649     return false;
9650
9651   // No global is ever allowed as a base.
9652   if (AM.BaseGV)
9653     return false;
9654
9655   // PPC only support r+r,
9656   switch (AM.Scale) {
9657   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9658     break;
9659   case 1:
9660     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9661       return false;
9662     // Otherwise we have r+r or r+i.
9663     break;
9664   case 2:
9665     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9666       return false;
9667     // Allow 2*r as r+r.
9668     break;
9669   default:
9670     // No other scales are supported.
9671     return false;
9672   }
9673
9674   return true;
9675 }
9676
9677 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9678                                            SelectionDAG &DAG) const {
9679   MachineFunction &MF = DAG.getMachineFunction();
9680   MachineFrameInfo *MFI = MF.getFrameInfo();
9681   MFI->setReturnAddressIsTaken(true);
9682
9683   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9684     return SDValue();
9685
9686   SDLoc dl(Op);
9687   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9688
9689   // Make sure the function does not optimize away the store of the RA to
9690   // the stack.
9691   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9692   FuncInfo->setLRStoreRequired();
9693   bool isPPC64 = Subtarget.isPPC64();
9694   bool isDarwinABI = Subtarget.isDarwinABI();
9695
9696   if (Depth > 0) {
9697     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9698     SDValue Offset =
9699
9700       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9701                       isPPC64? MVT::i64 : MVT::i32);
9702     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9703                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9704                                    FrameAddr, Offset),
9705                        MachinePointerInfo(), false, false, false, 0);
9706   }
9707
9708   // Just load the return address off the stack.
9709   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9710   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9711                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9712 }
9713
9714 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9715                                           SelectionDAG &DAG) const {
9716   SDLoc dl(Op);
9717   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9718
9719   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9720   bool isPPC64 = PtrVT == MVT::i64;
9721
9722   MachineFunction &MF = DAG.getMachineFunction();
9723   MachineFrameInfo *MFI = MF.getFrameInfo();
9724   MFI->setFrameAddressIsTaken(true);
9725
9726   // Naked functions never have a frame pointer, and so we use r1. For all
9727   // other functions, this decision must be delayed until during PEI.
9728   unsigned FrameReg;
9729   if (MF.getFunction()->getAttributes().hasAttribute(
9730         AttributeSet::FunctionIndex, Attribute::Naked))
9731     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9732   else
9733     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9734
9735   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9736                                          PtrVT);
9737   while (Depth--)
9738     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9739                             FrameAddr, MachinePointerInfo(), false, false,
9740                             false, 0);
9741   return FrameAddr;
9742 }
9743
9744 // FIXME? Maybe this could be a TableGen attribute on some registers and
9745 // this table could be generated automatically from RegInfo.
9746 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9747                                               EVT VT) const {
9748   bool isPPC64 = Subtarget.isPPC64();
9749   bool isDarwinABI = Subtarget.isDarwinABI();
9750
9751   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9752       (!isPPC64 && VT != MVT::i32))
9753     report_fatal_error("Invalid register global variable type");
9754
9755   bool is64Bit = isPPC64 && VT == MVT::i64;
9756   unsigned Reg = StringSwitch<unsigned>(RegName)
9757                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9758                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
9759                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9760                                   (is64Bit ? PPC::X13 : PPC::R13))
9761                    .Default(0);
9762
9763   if (Reg)
9764     return Reg;
9765   report_fatal_error("Invalid register name global variable");
9766 }
9767
9768 bool
9769 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9770   // The PowerPC target isn't yet aware of offsets.
9771   return false;
9772 }
9773
9774 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9775                                            const CallInst &I,
9776                                            unsigned Intrinsic) const {
9777
9778   switch (Intrinsic) {
9779   case Intrinsic::ppc_altivec_lvx:
9780   case Intrinsic::ppc_altivec_lvxl:
9781   case Intrinsic::ppc_altivec_lvebx:
9782   case Intrinsic::ppc_altivec_lvehx:
9783   case Intrinsic::ppc_altivec_lvewx:
9784   case Intrinsic::ppc_vsx_lxvd2x:
9785   case Intrinsic::ppc_vsx_lxvw4x: {
9786     EVT VT;
9787     switch (Intrinsic) {
9788     case Intrinsic::ppc_altivec_lvebx:
9789       VT = MVT::i8;
9790       break;
9791     case Intrinsic::ppc_altivec_lvehx:
9792       VT = MVT::i16;
9793       break;
9794     case Intrinsic::ppc_altivec_lvewx:
9795       VT = MVT::i32;
9796       break;
9797     case Intrinsic::ppc_vsx_lxvd2x:
9798       VT = MVT::v2f64;
9799       break;
9800     default:
9801       VT = MVT::v4i32;
9802       break;
9803     }
9804
9805     Info.opc = ISD::INTRINSIC_W_CHAIN;
9806     Info.memVT = VT;
9807     Info.ptrVal = I.getArgOperand(0);
9808     Info.offset = -VT.getStoreSize()+1;
9809     Info.size = 2*VT.getStoreSize()-1;
9810     Info.align = 1;
9811     Info.vol = false;
9812     Info.readMem = true;
9813     Info.writeMem = false;
9814     return true;
9815   }
9816   case Intrinsic::ppc_altivec_stvx:
9817   case Intrinsic::ppc_altivec_stvxl:
9818   case Intrinsic::ppc_altivec_stvebx:
9819   case Intrinsic::ppc_altivec_stvehx:
9820   case Intrinsic::ppc_altivec_stvewx:
9821   case Intrinsic::ppc_vsx_stxvd2x:
9822   case Intrinsic::ppc_vsx_stxvw4x: {
9823     EVT VT;
9824     switch (Intrinsic) {
9825     case Intrinsic::ppc_altivec_stvebx:
9826       VT = MVT::i8;
9827       break;
9828     case Intrinsic::ppc_altivec_stvehx:
9829       VT = MVT::i16;
9830       break;
9831     case Intrinsic::ppc_altivec_stvewx:
9832       VT = MVT::i32;
9833       break;
9834     case Intrinsic::ppc_vsx_stxvd2x:
9835       VT = MVT::v2f64;
9836       break;
9837     default:
9838       VT = MVT::v4i32;
9839       break;
9840     }
9841
9842     Info.opc = ISD::INTRINSIC_VOID;
9843     Info.memVT = VT;
9844     Info.ptrVal = I.getArgOperand(1);
9845     Info.offset = -VT.getStoreSize()+1;
9846     Info.size = 2*VT.getStoreSize()-1;
9847     Info.align = 1;
9848     Info.vol = false;
9849     Info.readMem = false;
9850     Info.writeMem = true;
9851     return true;
9852   }
9853   default:
9854     break;
9855   }
9856
9857   return false;
9858 }
9859
9860 /// getOptimalMemOpType - Returns the target specific optimal type for load
9861 /// and store operations as a result of memset, memcpy, and memmove
9862 /// lowering. If DstAlign is zero that means it's safe to destination
9863 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9864 /// means there isn't a need to check it against alignment requirement,
9865 /// probably because the source does not need to be loaded. If 'IsMemset' is
9866 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9867 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9868 /// source is constant so it does not need to be loaded.
9869 /// It returns EVT::Other if the type should be determined using generic
9870 /// target-independent logic.
9871 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9872                                            unsigned DstAlign, unsigned SrcAlign,
9873                                            bool IsMemset, bool ZeroMemset,
9874                                            bool MemcpyStrSrc,
9875                                            MachineFunction &MF) const {
9876   if (Subtarget.isPPC64()) {
9877     return MVT::i64;
9878   } else {
9879     return MVT::i32;
9880   }
9881 }
9882
9883 /// \brief Returns true if it is beneficial to convert a load of a constant
9884 /// to just the constant itself.
9885 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9886                                                           Type *Ty) const {
9887   assert(Ty->isIntegerTy());
9888
9889   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9890   if (BitSize == 0 || BitSize > 64)
9891     return false;
9892   return true;
9893 }
9894
9895 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9896   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9897     return false;
9898   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9899   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9900   return NumBits1 == 64 && NumBits2 == 32;
9901 }
9902
9903 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9904   if (!VT1.isInteger() || !VT2.isInteger())
9905     return false;
9906   unsigned NumBits1 = VT1.getSizeInBits();
9907   unsigned NumBits2 = VT2.getSizeInBits();
9908   return NumBits1 == 64 && NumBits2 == 32;
9909 }
9910
9911 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9912   // Generally speaking, zexts are not free, but they are free when they can be
9913   // folded with other operations.
9914   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
9915     EVT MemVT = LD->getMemoryVT();
9916     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
9917          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
9918         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
9919          LD->getExtensionType() == ISD::ZEXTLOAD))
9920       return true;
9921   }
9922
9923   // FIXME: Add other cases...
9924   //  - 32-bit shifts with a zext to i64
9925   //  - zext after ctlz, bswap, etc.
9926   //  - zext after and by a constant mask
9927
9928   return TargetLowering::isZExtFree(Val, VT2);
9929 }
9930
9931 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
9932   assert(VT.isFloatingPoint());
9933   return true;
9934 }
9935
9936 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9937   return isInt<16>(Imm) || isUInt<16>(Imm);
9938 }
9939
9940 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9941   return isInt<16>(Imm) || isUInt<16>(Imm);
9942 }
9943
9944 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9945                                                        unsigned,
9946                                                        unsigned,
9947                                                        bool *Fast) const {
9948   if (DisablePPCUnaligned)
9949     return false;
9950
9951   // PowerPC supports unaligned memory access for simple non-vector types.
9952   // Although accessing unaligned addresses is not as efficient as accessing
9953   // aligned addresses, it is generally more efficient than manual expansion,
9954   // and generally only traps for software emulation when crossing page
9955   // boundaries.
9956
9957   if (!VT.isSimple())
9958     return false;
9959
9960   if (VT.getSimpleVT().isVector()) {
9961     if (Subtarget.hasVSX()) {
9962       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9963           VT != MVT::v4f32 && VT != MVT::v4i32)
9964         return false;
9965     } else {
9966       return false;
9967     }
9968   }
9969
9970   if (VT == MVT::ppcf128)
9971     return false;
9972
9973   if (Fast)
9974     *Fast = true;
9975
9976   return true;
9977 }
9978
9979 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9980   VT = VT.getScalarType();
9981
9982   if (!VT.isSimple())
9983     return false;
9984
9985   switch (VT.getSimpleVT().SimpleTy) {
9986   case MVT::f32:
9987   case MVT::f64:
9988     return true;
9989   default:
9990     break;
9991   }
9992
9993   return false;
9994 }
9995
9996 const MCPhysReg *
9997 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
9998   // LR is a callee-save register, but we must treat it as clobbered by any call
9999   // site. Hence we include LR in the scratch registers, which are in turn added
10000   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
10001   // to CTR, which is used by any indirect call.
10002   static const MCPhysReg ScratchRegs[] = {
10003     PPC::X12, PPC::LR8, PPC::CTR8, 0
10004   };
10005
10006   return ScratchRegs;
10007 }
10008
10009 bool
10010 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
10011                      EVT VT , unsigned DefinedValues) const {
10012   if (VT == MVT::v2i64)
10013     return false;
10014
10015   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
10016 }
10017
10018 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
10019   if (DisableILPPref || Subtarget.enableMachineScheduler())
10020     return TargetLowering::getSchedulingPreference(N);
10021
10022   return Sched::ILP;
10023 }
10024
10025 // Create a fast isel object.
10026 FastISel *
10027 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
10028                                   const TargetLibraryInfo *LibInfo) const {
10029   return PPC::createFastISel(FuncInfo, LibInfo);
10030 }