[PowerPC] Reuse a load operand in int->fp conversions
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
41 using namespace llvm;
42
43 // FIXME: Remove this once soft-float is supported.
44 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
45 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
46
47 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
48 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
49
50 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
51 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
52
53 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
54 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
55
56 // FIXME: Remove this once the bug has been fixed!
57 extern cl::opt<bool> ANDIGlueBug;
58
59 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
60     : TargetLowering(TM),
61       Subtarget(*TM.getSubtargetImpl()) {
62   // Use _setjmp/_longjmp instead of setjmp/longjmp.
63   setUseUnderscoreSetJmp(true);
64   setUseUnderscoreLongJmp(true);
65
66   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
67   // arguments are at least 4/8 bytes aligned.
68   bool isPPC64 = Subtarget.isPPC64();
69   setMinStackArgumentAlignment(isPPC64 ? 8:4);
70
71   // Set up the register classes.
72   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
73   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
74   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
75
76   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
77   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
78   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
79
80   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
81
82   // PowerPC has pre-inc load and store's.
83   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
84   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
85   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
88   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
89   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
90   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
91   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
92   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
93
94   if (Subtarget.useCRBits()) {
95     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
96
97     if (isPPC64 || Subtarget.hasFPCVT()) {
98       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
99       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
100                          isPPC64 ? MVT::i64 : MVT::i32);
101       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
102       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
103                          isPPC64 ? MVT::i64 : MVT::i32);
104     } else {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
106       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
107     }
108
109     // PowerPC does not support direct load / store of condition registers
110     setOperationAction(ISD::LOAD, MVT::i1, Custom);
111     setOperationAction(ISD::STORE, MVT::i1, Custom);
112
113     // FIXME: Remove this once the ANDI glue bug is fixed:
114     if (ANDIGlueBug)
115       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
116
117     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
118     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
120     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
121     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
122     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
123
124     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
125   }
126
127   // This is used in the ppcf128->int sequence.  Note it has different semantics
128   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
129   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
130
131   // We do not currently implement these libm ops for PowerPC.
132   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
133   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
134   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
135   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
136   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
137   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
138
139   // PowerPC has no SREM/UREM instructions
140   setOperationAction(ISD::SREM, MVT::i32, Expand);
141   setOperationAction(ISD::UREM, MVT::i32, Expand);
142   setOperationAction(ISD::SREM, MVT::i64, Expand);
143   setOperationAction(ISD::UREM, MVT::i64, Expand);
144
145   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
146   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
147   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
148   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
149   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
150   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
151   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
152   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
153   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
154
155   // We don't support sin/cos/sqrt/fmod/pow
156   setOperationAction(ISD::FSIN , MVT::f64, Expand);
157   setOperationAction(ISD::FCOS , MVT::f64, Expand);
158   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
159   setOperationAction(ISD::FREM , MVT::f64, Expand);
160   setOperationAction(ISD::FPOW , MVT::f64, Expand);
161   setOperationAction(ISD::FMA  , MVT::f64, Legal);
162   setOperationAction(ISD::FSIN , MVT::f32, Expand);
163   setOperationAction(ISD::FCOS , MVT::f32, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
165   setOperationAction(ISD::FREM , MVT::f32, Expand);
166   setOperationAction(ISD::FPOW , MVT::f32, Expand);
167   setOperationAction(ISD::FMA  , MVT::f32, Legal);
168
169   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
170
171   // If we're enabling GP optimizations, use hardware square root
172   if (!Subtarget.hasFSQRT() &&
173       !(TM.Options.UnsafeFPMath &&
174         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
175     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
176
177   if (!Subtarget.hasFSQRT() &&
178       !(TM.Options.UnsafeFPMath &&
179         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
180     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
181
182   if (Subtarget.hasFCPSGN()) {
183     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
184     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
185   } else {
186     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
187     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
188   }
189
190   if (Subtarget.hasFPRND()) {
191     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
192     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
193     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
194     setOperationAction(ISD::FROUND, MVT::f64, Legal);
195
196     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
197     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
198     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
199     setOperationAction(ISD::FROUND, MVT::f32, Legal);
200   }
201
202   // PowerPC does not have BSWAP, CTPOP or CTTZ
203   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
204   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
205   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
206   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
207   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
208   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
209   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
210   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
211
212   if (Subtarget.hasPOPCNTD()) {
213     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
214     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
215   } else {
216     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
217     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
218   }
219
220   // PowerPC does not have ROTR
221   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
222   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
223
224   if (!Subtarget.useCRBits()) {
225     // PowerPC does not have Select
226     setOperationAction(ISD::SELECT, MVT::i32, Expand);
227     setOperationAction(ISD::SELECT, MVT::i64, Expand);
228     setOperationAction(ISD::SELECT, MVT::f32, Expand);
229     setOperationAction(ISD::SELECT, MVT::f64, Expand);
230   }
231
232   // PowerPC wants to turn select_cc of FP into fsel when possible.
233   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
234   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
235
236   // PowerPC wants to optimize integer setcc a bit
237   if (!Subtarget.useCRBits())
238     setOperationAction(ISD::SETCC, MVT::i32, Custom);
239
240   // PowerPC does not have BRCOND which requires SetCC
241   if (!Subtarget.useCRBits())
242     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
243
244   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
245
246   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
247   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
248
249   // PowerPC does not have [U|S]INT_TO_FP
250   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
251   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
252
253   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
254   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
255   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
256   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
257
258   // We cannot sextinreg(i1).  Expand to shifts.
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
260
261   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
262   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
263   // support continuation, user-level threading, and etc.. As a result, no
264   // other SjLj exception interfaces are implemented and please don't build
265   // your own exception handling based on them.
266   // LLVM/Clang supports zero-cost DWARF exception handling.
267   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
268   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
269
270   // We want to legalize GlobalAddress and ConstantPool nodes into the
271   // appropriate instructions to materialize the address.
272   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
273   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
274   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
275   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
276   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
277   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
278   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
279   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
280   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
281   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
282
283   // TRAP is legal.
284   setOperationAction(ISD::TRAP, MVT::Other, Legal);
285
286   // TRAMPOLINE is custom lowered.
287   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
288   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
289
290   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
291   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
292
293   if (Subtarget.isSVR4ABI()) {
294     if (isPPC64) {
295       // VAARG always uses double-word chunks, so promote anything smaller.
296       setOperationAction(ISD::VAARG, MVT::i1, Promote);
297       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
298       setOperationAction(ISD::VAARG, MVT::i8, Promote);
299       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
300       setOperationAction(ISD::VAARG, MVT::i16, Promote);
301       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
302       setOperationAction(ISD::VAARG, MVT::i32, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::Other, Expand);
305     } else {
306       // VAARG is custom lowered with the 32-bit SVR4 ABI.
307       setOperationAction(ISD::VAARG, MVT::Other, Custom);
308       setOperationAction(ISD::VAARG, MVT::i64, Custom);
309     }
310   } else
311     setOperationAction(ISD::VAARG, MVT::Other, Expand);
312
313   if (Subtarget.isSVR4ABI() && !isPPC64)
314     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
315     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
316   else
317     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
318
319   // Use the default implementation.
320   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
321   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
322   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
323   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
324   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
325
326   // We want to custom lower some of our intrinsics.
327   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
328
329   // To handle counter-based loop conditions.
330   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
331
332   // Comparisons that require checking two conditions.
333   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
334   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
335   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
336   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
337   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
338   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
339   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
345
346   if (Subtarget.has64BitSupport()) {
347     // They also have instructions for converting between i64 and fp.
348     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
349     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
350     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
351     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
352     // This is just the low 32 bits of a (signed) fp->i64 conversion.
353     // We cannot do this with Promote because i64 is not a legal type.
354     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
355
356     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
357       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
358   } else {
359     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
361   }
362
363   // With the instructions enabled under FPCVT, we can do everything.
364   if (Subtarget.hasFPCVT()) {
365     if (Subtarget.has64BitSupport()) {
366       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
367       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
368       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
369       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
370     }
371
372     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
373     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
374     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
375     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
376   }
377
378   if (Subtarget.use64BitRegs()) {
379     // 64-bit PowerPC implementations can support i64 types directly
380     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
381     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
382     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
383     // 64-bit PowerPC wants to expand i128 shifts itself.
384     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
385     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
386     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
387   } else {
388     // 32-bit PowerPC wants to expand i64 shifts itself.
389     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
390     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
391     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
392   }
393
394   if (Subtarget.hasAltivec()) {
395     // First set operation action for all vector types to expand. Then we
396     // will selectively turn on ones that can be effectively codegen'd.
397     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
398          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
399       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
400
401       // add/sub are legal for all supported vector VT's.
402       setOperationAction(ISD::ADD , VT, Legal);
403       setOperationAction(ISD::SUB , VT, Legal);
404
405       // We promote all shuffles to v16i8.
406       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
407       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
408
409       // We promote all non-typed operations to v4i32.
410       setOperationAction(ISD::AND   , VT, Promote);
411       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
412       setOperationAction(ISD::OR    , VT, Promote);
413       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
414       setOperationAction(ISD::XOR   , VT, Promote);
415       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
416       setOperationAction(ISD::LOAD  , VT, Promote);
417       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
418       setOperationAction(ISD::SELECT, VT, Promote);
419       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
420       setOperationAction(ISD::STORE, VT, Promote);
421       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
422
423       // No other operations are legal.
424       setOperationAction(ISD::MUL , VT, Expand);
425       setOperationAction(ISD::SDIV, VT, Expand);
426       setOperationAction(ISD::SREM, VT, Expand);
427       setOperationAction(ISD::UDIV, VT, Expand);
428       setOperationAction(ISD::UREM, VT, Expand);
429       setOperationAction(ISD::FDIV, VT, Expand);
430       setOperationAction(ISD::FREM, VT, Expand);
431       setOperationAction(ISD::FNEG, VT, Expand);
432       setOperationAction(ISD::FSQRT, VT, Expand);
433       setOperationAction(ISD::FLOG, VT, Expand);
434       setOperationAction(ISD::FLOG10, VT, Expand);
435       setOperationAction(ISD::FLOG2, VT, Expand);
436       setOperationAction(ISD::FEXP, VT, Expand);
437       setOperationAction(ISD::FEXP2, VT, Expand);
438       setOperationAction(ISD::FSIN, VT, Expand);
439       setOperationAction(ISD::FCOS, VT, Expand);
440       setOperationAction(ISD::FABS, VT, Expand);
441       setOperationAction(ISD::FPOWI, VT, Expand);
442       setOperationAction(ISD::FFLOOR, VT, Expand);
443       setOperationAction(ISD::FCEIL,  VT, Expand);
444       setOperationAction(ISD::FTRUNC, VT, Expand);
445       setOperationAction(ISD::FRINT,  VT, Expand);
446       setOperationAction(ISD::FNEARBYINT, VT, Expand);
447       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
448       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
449       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
450       setOperationAction(ISD::MULHU, VT, Expand);
451       setOperationAction(ISD::MULHS, VT, Expand);
452       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
453       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454       setOperationAction(ISD::UDIVREM, VT, Expand);
455       setOperationAction(ISD::SDIVREM, VT, Expand);
456       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
457       setOperationAction(ISD::FPOW, VT, Expand);
458       setOperationAction(ISD::BSWAP, VT, Expand);
459       setOperationAction(ISD::CTPOP, VT, Expand);
460       setOperationAction(ISD::CTLZ, VT, Expand);
461       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
462       setOperationAction(ISD::CTTZ, VT, Expand);
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
464       setOperationAction(ISD::VSELECT, VT, Expand);
465       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
466
467       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
468            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
469         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
470         setTruncStoreAction(VT, InnerVT, Expand);
471       }
472       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
473       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
474       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
475     }
476
477     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
478     // with merges, splats, etc.
479     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
480
481     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
482     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
483     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
484     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
485     setOperationAction(ISD::SELECT, MVT::v4i32,
486                        Subtarget.useCRBits() ? Legal : Expand);
487     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
488     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
489     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
490     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
491     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
492     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
493     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
494     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
495     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
496
497     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
498     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
499     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
500     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
501
502     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
503     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
504
505     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
506       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
507       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
508     }
509
510     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
511     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
512     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
513
514     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
515     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
516
517     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
518     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
519     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
520     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
521
522     // Altivec does not contain unordered floating-point compare instructions
523     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
524     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
525     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
526     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
527
528     if (Subtarget.hasVSX()) {
529       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
530       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
531
532       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
533       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
534       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
535       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
536       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
537
538       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
539
540       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
541       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
542
543       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
544       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
545
546       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
547       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
548       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
549       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
550       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
551
552       // Share the Altivec comparison restrictions.
553       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
554       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
555       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
556       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
557
558       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
559       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
560
561       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
562
563       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
564
565       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
566       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
567
568       // VSX v2i64 only supports non-arithmetic operations.
569       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
570       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
571
572       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
573       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
574       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
575
576       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
577
578       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
579       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
580       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
581       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
582
583       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
584
585       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
586       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
587       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
588       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
589
590       // Vector operation legalization checks the result type of
591       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
592       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
593       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
594       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
595       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
596
597       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
598     }
599   }
600
601   if (Subtarget.has64BitSupport())
602     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
603
604   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
605
606   if (!isPPC64) {
607     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
608     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
609   }
610
611   setBooleanContents(ZeroOrOneBooleanContent);
612   // Altivec instructions set fields to all zeros or all ones.
613   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
614
615   if (!isPPC64) {
616     // These libcalls are not available in 32-bit.
617     setLibcallName(RTLIB::SHL_I128, nullptr);
618     setLibcallName(RTLIB::SRL_I128, nullptr);
619     setLibcallName(RTLIB::SRA_I128, nullptr);
620   }
621
622   if (isPPC64) {
623     setStackPointerRegisterToSaveRestore(PPC::X1);
624     setExceptionPointerRegister(PPC::X3);
625     setExceptionSelectorRegister(PPC::X4);
626   } else {
627     setStackPointerRegisterToSaveRestore(PPC::R1);
628     setExceptionPointerRegister(PPC::R3);
629     setExceptionSelectorRegister(PPC::R4);
630   }
631
632   // We have target-specific dag combine patterns for the following nodes:
633   setTargetDAGCombine(ISD::SINT_TO_FP);
634   if (Subtarget.hasFPCVT())
635     setTargetDAGCombine(ISD::UINT_TO_FP);
636   setTargetDAGCombine(ISD::LOAD);
637   setTargetDAGCombine(ISD::STORE);
638   setTargetDAGCombine(ISD::BR_CC);
639   if (Subtarget.useCRBits())
640     setTargetDAGCombine(ISD::BRCOND);
641   setTargetDAGCombine(ISD::BSWAP);
642   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
643   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
644   setTargetDAGCombine(ISD::INTRINSIC_VOID);
645
646   setTargetDAGCombine(ISD::SIGN_EXTEND);
647   setTargetDAGCombine(ISD::ZERO_EXTEND);
648   setTargetDAGCombine(ISD::ANY_EXTEND);
649
650   if (Subtarget.useCRBits()) {
651     setTargetDAGCombine(ISD::TRUNCATE);
652     setTargetDAGCombine(ISD::SETCC);
653     setTargetDAGCombine(ISD::SELECT_CC);
654   }
655
656   // Use reciprocal estimates.
657   if (TM.Options.UnsafeFPMath) {
658     setTargetDAGCombine(ISD::FDIV);
659     setTargetDAGCombine(ISD::FSQRT);
660   }
661
662   // Darwin long double math library functions have $LDBL128 appended.
663   if (Subtarget.isDarwin()) {
664     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
665     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
666     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
667     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
668     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
669     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
670     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
671     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
672     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
673     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
674   }
675
676   // With 32 condition bits, we don't need to sink (and duplicate) compares
677   // aggressively in CodeGenPrep.
678   if (Subtarget.useCRBits())
679     setHasMultipleConditionRegisters();
680
681   setMinFunctionAlignment(2);
682   if (Subtarget.isDarwin())
683     setPrefFunctionAlignment(4);
684
685   switch (Subtarget.getDarwinDirective()) {
686   default: break;
687   case PPC::DIR_970:
688   case PPC::DIR_A2:
689   case PPC::DIR_E500mc:
690   case PPC::DIR_E5500:
691   case PPC::DIR_PWR4:
692   case PPC::DIR_PWR5:
693   case PPC::DIR_PWR5X:
694   case PPC::DIR_PWR6:
695   case PPC::DIR_PWR6X:
696   case PPC::DIR_PWR7:
697   case PPC::DIR_PWR8:
698     setPrefFunctionAlignment(4);
699     setPrefLoopAlignment(4);
700     break;
701   }
702
703   setInsertFencesForAtomic(true);
704
705   if (Subtarget.enableMachineScheduler())
706     setSchedulingPreference(Sched::Source);
707   else
708     setSchedulingPreference(Sched::Hybrid);
709
710   computeRegisterProperties();
711
712   // The Freescale cores do better with aggressive inlining of memcpy and
713   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
714   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
715       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
716     MaxStoresPerMemset = 32;
717     MaxStoresPerMemsetOptSize = 16;
718     MaxStoresPerMemcpy = 32;
719     MaxStoresPerMemcpyOptSize = 8;
720     MaxStoresPerMemmove = 32;
721     MaxStoresPerMemmoveOptSize = 8;
722   }
723 }
724
725 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
726 /// the desired ByVal argument alignment.
727 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
728                              unsigned MaxMaxAlign) {
729   if (MaxAlign == MaxMaxAlign)
730     return;
731   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
732     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
733       MaxAlign = 32;
734     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
735       MaxAlign = 16;
736   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
737     unsigned EltAlign = 0;
738     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
739     if (EltAlign > MaxAlign)
740       MaxAlign = EltAlign;
741   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
742     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
743       unsigned EltAlign = 0;
744       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
745       if (EltAlign > MaxAlign)
746         MaxAlign = EltAlign;
747       if (MaxAlign == MaxMaxAlign)
748         break;
749     }
750   }
751 }
752
753 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
754 /// function arguments in the caller parameter area.
755 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
756   // Darwin passes everything on 4 byte boundary.
757   if (Subtarget.isDarwin())
758     return 4;
759
760   // 16byte and wider vectors are passed on 16byte boundary.
761   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
762   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
763   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
764     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
765   return Align;
766 }
767
768 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
769   switch (Opcode) {
770   default: return nullptr;
771   case PPCISD::FSEL:            return "PPCISD::FSEL";
772   case PPCISD::FCFID:           return "PPCISD::FCFID";
773   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
774   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
775   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
776   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
777   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
778   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
779   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
780   case PPCISD::FRE:             return "PPCISD::FRE";
781   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
782   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
783   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
784   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
785   case PPCISD::VPERM:           return "PPCISD::VPERM";
786   case PPCISD::CMPB:            return "PPCISD::CMPB";
787   case PPCISD::Hi:              return "PPCISD::Hi";
788   case PPCISD::Lo:              return "PPCISD::Lo";
789   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
790   case PPCISD::LOAD:            return "PPCISD::LOAD";
791   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
792   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
793   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
794   case PPCISD::SRL:             return "PPCISD::SRL";
795   case PPCISD::SRA:             return "PPCISD::SRA";
796   case PPCISD::SHL:             return "PPCISD::SHL";
797   case PPCISD::CALL:            return "PPCISD::CALL";
798   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
799   case PPCISD::CALL_TLS:        return "PPCISD::CALL_TLS";
800   case PPCISD::CALL_NOP_TLS:    return "PPCISD::CALL_NOP_TLS";
801   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
802   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
803   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
804   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
805   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
806   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
807   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
808   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
809   case PPCISD::VCMP:            return "PPCISD::VCMP";
810   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
811   case PPCISD::LBRX:            return "PPCISD::LBRX";
812   case PPCISD::STBRX:           return "PPCISD::STBRX";
813   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
814   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
815   case PPCISD::LARX:            return "PPCISD::LARX";
816   case PPCISD::STCX:            return "PPCISD::STCX";
817   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
818   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
819   case PPCISD::BDZ:             return "PPCISD::BDZ";
820   case PPCISD::MFFS:            return "PPCISD::MFFS";
821   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
822   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
823   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
824   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
825   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
826   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
827   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
828   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
829   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
830   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
831   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
832   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
833   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
834   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
835   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
836   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
837   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
838   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
839   case PPCISD::SC:              return "PPCISD::SC";
840   }
841 }
842
843 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
844   if (!VT.isVector())
845     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
846   return VT.changeVectorElementTypeToInteger();
847 }
848
849 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
850   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
851   return true;
852 }
853
854 //===----------------------------------------------------------------------===//
855 // Node matching predicates, for use by the tblgen matching code.
856 //===----------------------------------------------------------------------===//
857
858 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
859 static bool isFloatingPointZero(SDValue Op) {
860   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
861     return CFP->getValueAPF().isZero();
862   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
863     // Maybe this has already been legalized into the constant pool?
864     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
865       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
866         return CFP->getValueAPF().isZero();
867   }
868   return false;
869 }
870
871 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
872 /// true if Op is undef or if it matches the specified value.
873 static bool isConstantOrUndef(int Op, int Val) {
874   return Op < 0 || Op == Val;
875 }
876
877 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
878 /// VPKUHUM instruction.
879 /// The ShuffleKind distinguishes between big-endian operations with
880 /// two different inputs (0), either-endian operations with two identical
881 /// inputs (1), and little-endian operantion with two different inputs (2).
882 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
883 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
884                                SelectionDAG &DAG) {
885   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
886   if (ShuffleKind == 0) {
887     if (IsLE)
888       return false;
889     for (unsigned i = 0; i != 16; ++i)
890       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
891         return false;
892   } else if (ShuffleKind == 2) {
893     if (!IsLE)
894       return false;
895     for (unsigned i = 0; i != 16; ++i)
896       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
897         return false;
898   } else if (ShuffleKind == 1) {
899     unsigned j = IsLE ? 0 : 1;
900     for (unsigned i = 0; i != 8; ++i)
901       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
902           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
903         return false;
904   }
905   return true;
906 }
907
908 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
909 /// VPKUWUM instruction.
910 /// The ShuffleKind distinguishes between big-endian operations with
911 /// two different inputs (0), either-endian operations with two identical
912 /// inputs (1), and little-endian operantion with two different inputs (2).
913 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
914 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
915                                SelectionDAG &DAG) {
916   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
917   if (ShuffleKind == 0) {
918     if (IsLE)
919       return false;
920     for (unsigned i = 0; i != 16; i += 2)
921       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
922           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
923         return false;
924   } else if (ShuffleKind == 2) {
925     if (!IsLE)
926       return false;
927     for (unsigned i = 0; i != 16; i += 2)
928       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
929           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
930         return false;
931   } else if (ShuffleKind == 1) {
932     unsigned j = IsLE ? 0 : 2;
933     for (unsigned i = 0; i != 8; i += 2)
934       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
935           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
936           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
937           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
938         return false;
939   }
940   return true;
941 }
942
943 /// isVMerge - Common function, used to match vmrg* shuffles.
944 ///
945 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
946                      unsigned LHSStart, unsigned RHSStart) {
947   if (N->getValueType(0) != MVT::v16i8)
948     return false;
949   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
950          "Unsupported merge size!");
951
952   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
953     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
954       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
955                              LHSStart+j+i*UnitSize) ||
956           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
957                              RHSStart+j+i*UnitSize))
958         return false;
959     }
960   return true;
961 }
962
963 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
964 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
965 /// The ShuffleKind distinguishes between big-endian merges with two 
966 /// different inputs (0), either-endian merges with two identical inputs (1),
967 /// and little-endian merges with two different inputs (2).  For the latter,
968 /// the input operands are swapped (see PPCInstrAltivec.td).
969 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
970                              unsigned ShuffleKind, SelectionDAG &DAG) {
971   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
972     if (ShuffleKind == 1) // unary
973       return isVMerge(N, UnitSize, 0, 0);
974     else if (ShuffleKind == 2) // swapped
975       return isVMerge(N, UnitSize, 0, 16);
976     else
977       return false;
978   } else {
979     if (ShuffleKind == 1) // unary
980       return isVMerge(N, UnitSize, 8, 8);
981     else if (ShuffleKind == 0) // normal
982       return isVMerge(N, UnitSize, 8, 24);
983     else
984       return false;
985   }
986 }
987
988 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
989 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
990 /// The ShuffleKind distinguishes between big-endian merges with two 
991 /// different inputs (0), either-endian merges with two identical inputs (1),
992 /// and little-endian merges with two different inputs (2).  For the latter,
993 /// the input operands are swapped (see PPCInstrAltivec.td).
994 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
995                              unsigned ShuffleKind, SelectionDAG &DAG) {
996   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
997     if (ShuffleKind == 1) // unary
998       return isVMerge(N, UnitSize, 8, 8);
999     else if (ShuffleKind == 2) // swapped
1000       return isVMerge(N, UnitSize, 8, 24);
1001     else
1002       return false;
1003   } else {
1004     if (ShuffleKind == 1) // unary
1005       return isVMerge(N, UnitSize, 0, 0);
1006     else if (ShuffleKind == 0) // normal
1007       return isVMerge(N, UnitSize, 0, 16);
1008     else
1009       return false;
1010   }
1011 }
1012
1013
1014 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1015 /// amount, otherwise return -1.
1016 /// The ShuffleKind distinguishes between big-endian operations with two 
1017 /// different inputs (0), either-endian operations with two identical inputs
1018 /// (1), and little-endian operations with two different inputs (2).  For the
1019 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1020 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1021                              SelectionDAG &DAG) {
1022   if (N->getValueType(0) != MVT::v16i8)
1023     return -1;
1024
1025   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1026
1027   // Find the first non-undef value in the shuffle mask.
1028   unsigned i;
1029   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1030     /*search*/;
1031
1032   if (i == 16) return -1;  // all undef.
1033
1034   // Otherwise, check to see if the rest of the elements are consecutively
1035   // numbered from this value.
1036   unsigned ShiftAmt = SVOp->getMaskElt(i);
1037   if (ShiftAmt < i) return -1;
1038
1039   ShiftAmt -= i;
1040   bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1041     isLittleEndian();
1042
1043   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1044     // Check the rest of the elements to see if they are consecutive.
1045     for (++i; i != 16; ++i)
1046       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1047         return -1;
1048   } else if (ShuffleKind == 1) {
1049     // Check the rest of the elements to see if they are consecutive.
1050     for (++i; i != 16; ++i)
1051       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1052         return -1;
1053   } else
1054     return -1;
1055
1056   if (ShuffleKind == 2 && isLE)
1057     ShiftAmt = 16 - ShiftAmt;
1058
1059   return ShiftAmt;
1060 }
1061
1062 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1063 /// specifies a splat of a single element that is suitable for input to
1064 /// VSPLTB/VSPLTH/VSPLTW.
1065 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1066   assert(N->getValueType(0) == MVT::v16i8 &&
1067          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1068
1069   // This is a splat operation if each element of the permute is the same, and
1070   // if the value doesn't reference the second vector.
1071   unsigned ElementBase = N->getMaskElt(0);
1072
1073   // FIXME: Handle UNDEF elements too!
1074   if (ElementBase >= 16)
1075     return false;
1076
1077   // Check that the indices are consecutive, in the case of a multi-byte element
1078   // splatted with a v16i8 mask.
1079   for (unsigned i = 1; i != EltSize; ++i)
1080     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1081       return false;
1082
1083   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1084     if (N->getMaskElt(i) < 0) continue;
1085     for (unsigned j = 0; j != EltSize; ++j)
1086       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1087         return false;
1088   }
1089   return true;
1090 }
1091
1092 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1093 /// are -0.0.
1094 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1095   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1096
1097   APInt APVal, APUndef;
1098   unsigned BitSize;
1099   bool HasAnyUndefs;
1100
1101   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1102     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1103       return CFP->getValueAPF().isNegZero();
1104
1105   return false;
1106 }
1107
1108 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1109 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1110 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1111                                 SelectionDAG &DAG) {
1112   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1113   assert(isSplatShuffleMask(SVOp, EltSize));
1114   if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1115     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1116   else
1117     return SVOp->getMaskElt(0) / EltSize;
1118 }
1119
1120 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1121 /// by using a vspltis[bhw] instruction of the specified element size, return
1122 /// the constant being splatted.  The ByteSize field indicates the number of
1123 /// bytes of each element [124] -> [bhw].
1124 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1125   SDValue OpVal(nullptr, 0);
1126
1127   // If ByteSize of the splat is bigger than the element size of the
1128   // build_vector, then we have a case where we are checking for a splat where
1129   // multiple elements of the buildvector are folded together into a single
1130   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1131   unsigned EltSize = 16/N->getNumOperands();
1132   if (EltSize < ByteSize) {
1133     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1134     SDValue UniquedVals[4];
1135     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1136
1137     // See if all of the elements in the buildvector agree across.
1138     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1139       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1140       // If the element isn't a constant, bail fully out.
1141       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1142
1143
1144       if (!UniquedVals[i&(Multiple-1)].getNode())
1145         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1146       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1147         return SDValue();  // no match.
1148     }
1149
1150     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1151     // either constant or undef values that are identical for each chunk.  See
1152     // if these chunks can form into a larger vspltis*.
1153
1154     // Check to see if all of the leading entries are either 0 or -1.  If
1155     // neither, then this won't fit into the immediate field.
1156     bool LeadingZero = true;
1157     bool LeadingOnes = true;
1158     for (unsigned i = 0; i != Multiple-1; ++i) {
1159       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1160
1161       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1162       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1163     }
1164     // Finally, check the least significant entry.
1165     if (LeadingZero) {
1166       if (!UniquedVals[Multiple-1].getNode())
1167         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1168       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1169       if (Val < 16)
1170         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1171     }
1172     if (LeadingOnes) {
1173       if (!UniquedVals[Multiple-1].getNode())
1174         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1175       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1176       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1177         return DAG.getTargetConstant(Val, MVT::i32);
1178     }
1179
1180     return SDValue();
1181   }
1182
1183   // Check to see if this buildvec has a single non-undef value in its elements.
1184   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1185     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1186     if (!OpVal.getNode())
1187       OpVal = N->getOperand(i);
1188     else if (OpVal != N->getOperand(i))
1189       return SDValue();
1190   }
1191
1192   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1193
1194   unsigned ValSizeInBytes = EltSize;
1195   uint64_t Value = 0;
1196   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1197     Value = CN->getZExtValue();
1198   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1199     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1200     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1201   }
1202
1203   // If the splat value is larger than the element value, then we can never do
1204   // this splat.  The only case that we could fit the replicated bits into our
1205   // immediate field for would be zero, and we prefer to use vxor for it.
1206   if (ValSizeInBytes < ByteSize) return SDValue();
1207
1208   // If the element value is larger than the splat value, cut it in half and
1209   // check to see if the two halves are equal.  Continue doing this until we
1210   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1211   while (ValSizeInBytes > ByteSize) {
1212     ValSizeInBytes >>= 1;
1213
1214     // If the top half equals the bottom half, we're still ok.
1215     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1216          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1217       return SDValue();
1218   }
1219
1220   // Properly sign extend the value.
1221   int MaskVal = SignExtend32(Value, ByteSize * 8);
1222
1223   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1224   if (MaskVal == 0) return SDValue();
1225
1226   // Finally, if this value fits in a 5 bit sext field, return it
1227   if (SignExtend32<5>(MaskVal) == MaskVal)
1228     return DAG.getTargetConstant(MaskVal, MVT::i32);
1229   return SDValue();
1230 }
1231
1232 //===----------------------------------------------------------------------===//
1233 //  Addressing Mode Selection
1234 //===----------------------------------------------------------------------===//
1235
1236 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1237 /// or 64-bit immediate, and if the value can be accurately represented as a
1238 /// sign extension from a 16-bit value.  If so, this returns true and the
1239 /// immediate.
1240 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1241   if (!isa<ConstantSDNode>(N))
1242     return false;
1243
1244   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1245   if (N->getValueType(0) == MVT::i32)
1246     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1247   else
1248     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1249 }
1250 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1251   return isIntS16Immediate(Op.getNode(), Imm);
1252 }
1253
1254
1255 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1256 /// can be represented as an indexed [r+r] operation.  Returns false if it
1257 /// can be more efficiently represented with [r+imm].
1258 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1259                                             SDValue &Index,
1260                                             SelectionDAG &DAG) const {
1261   short imm = 0;
1262   if (N.getOpcode() == ISD::ADD) {
1263     if (isIntS16Immediate(N.getOperand(1), imm))
1264       return false;    // r+i
1265     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1266       return false;    // r+i
1267
1268     Base = N.getOperand(0);
1269     Index = N.getOperand(1);
1270     return true;
1271   } else if (N.getOpcode() == ISD::OR) {
1272     if (isIntS16Immediate(N.getOperand(1), imm))
1273       return false;    // r+i can fold it if we can.
1274
1275     // If this is an or of disjoint bitfields, we can codegen this as an add
1276     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1277     // disjoint.
1278     APInt LHSKnownZero, LHSKnownOne;
1279     APInt RHSKnownZero, RHSKnownOne;
1280     DAG.computeKnownBits(N.getOperand(0),
1281                          LHSKnownZero, LHSKnownOne);
1282
1283     if (LHSKnownZero.getBoolValue()) {
1284       DAG.computeKnownBits(N.getOperand(1),
1285                            RHSKnownZero, RHSKnownOne);
1286       // If all of the bits are known zero on the LHS or RHS, the add won't
1287       // carry.
1288       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1289         Base = N.getOperand(0);
1290         Index = N.getOperand(1);
1291         return true;
1292       }
1293     }
1294   }
1295
1296   return false;
1297 }
1298
1299 // If we happen to be doing an i64 load or store into a stack slot that has
1300 // less than a 4-byte alignment, then the frame-index elimination may need to
1301 // use an indexed load or store instruction (because the offset may not be a
1302 // multiple of 4). The extra register needed to hold the offset comes from the
1303 // register scavenger, and it is possible that the scavenger will need to use
1304 // an emergency spill slot. As a result, we need to make sure that a spill slot
1305 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1306 // stack slot.
1307 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1308   // FIXME: This does not handle the LWA case.
1309   if (VT != MVT::i64)
1310     return;
1311
1312   // NOTE: We'll exclude negative FIs here, which come from argument
1313   // lowering, because there are no known test cases triggering this problem
1314   // using packed structures (or similar). We can remove this exclusion if
1315   // we find such a test case. The reason why this is so test-case driven is
1316   // because this entire 'fixup' is only to prevent crashes (from the
1317   // register scavenger) on not-really-valid inputs. For example, if we have:
1318   //   %a = alloca i1
1319   //   %b = bitcast i1* %a to i64*
1320   //   store i64* a, i64 b
1321   // then the store should really be marked as 'align 1', but is not. If it
1322   // were marked as 'align 1' then the indexed form would have been
1323   // instruction-selected initially, and the problem this 'fixup' is preventing
1324   // won't happen regardless.
1325   if (FrameIdx < 0)
1326     return;
1327
1328   MachineFunction &MF = DAG.getMachineFunction();
1329   MachineFrameInfo *MFI = MF.getFrameInfo();
1330
1331   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1332   if (Align >= 4)
1333     return;
1334
1335   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1336   FuncInfo->setHasNonRISpills();
1337 }
1338
1339 /// Returns true if the address N can be represented by a base register plus
1340 /// a signed 16-bit displacement [r+imm], and if it is not better
1341 /// represented as reg+reg.  If Aligned is true, only accept displacements
1342 /// suitable for STD and friends, i.e. multiples of 4.
1343 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1344                                             SDValue &Base,
1345                                             SelectionDAG &DAG,
1346                                             bool Aligned) const {
1347   // FIXME dl should come from parent load or store, not from address
1348   SDLoc dl(N);
1349   // If this can be more profitably realized as r+r, fail.
1350   if (SelectAddressRegReg(N, Disp, Base, DAG))
1351     return false;
1352
1353   if (N.getOpcode() == ISD::ADD) {
1354     short imm = 0;
1355     if (isIntS16Immediate(N.getOperand(1), imm) &&
1356         (!Aligned || (imm & 3) == 0)) {
1357       Disp = DAG.getTargetConstant(imm, N.getValueType());
1358       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1359         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1360         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1361       } else {
1362         Base = N.getOperand(0);
1363       }
1364       return true; // [r+i]
1365     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1366       // Match LOAD (ADD (X, Lo(G))).
1367       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1368              && "Cannot handle constant offsets yet!");
1369       Disp = N.getOperand(1).getOperand(0);  // The global address.
1370       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1371              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1372              Disp.getOpcode() == ISD::TargetConstantPool ||
1373              Disp.getOpcode() == ISD::TargetJumpTable);
1374       Base = N.getOperand(0);
1375       return true;  // [&g+r]
1376     }
1377   } else if (N.getOpcode() == ISD::OR) {
1378     short imm = 0;
1379     if (isIntS16Immediate(N.getOperand(1), imm) &&
1380         (!Aligned || (imm & 3) == 0)) {
1381       // If this is an or of disjoint bitfields, we can codegen this as an add
1382       // (for better address arithmetic) if the LHS and RHS of the OR are
1383       // provably disjoint.
1384       APInt LHSKnownZero, LHSKnownOne;
1385       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1386
1387       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1388         // If all of the bits are known zero on the LHS or RHS, the add won't
1389         // carry.
1390         if (FrameIndexSDNode *FI =
1391               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1392           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1393           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1394         } else {
1395           Base = N.getOperand(0);
1396         }
1397         Disp = DAG.getTargetConstant(imm, N.getValueType());
1398         return true;
1399       }
1400     }
1401   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1402     // Loading from a constant address.
1403
1404     // If this address fits entirely in a 16-bit sext immediate field, codegen
1405     // this as "d, 0"
1406     short Imm;
1407     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1408       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1409       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1410                              CN->getValueType(0));
1411       return true;
1412     }
1413
1414     // Handle 32-bit sext immediates with LIS + addr mode.
1415     if ((CN->getValueType(0) == MVT::i32 ||
1416          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1417         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1418       int Addr = (int)CN->getZExtValue();
1419
1420       // Otherwise, break this down into an LIS + disp.
1421       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1422
1423       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1424       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1425       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1426       return true;
1427     }
1428   }
1429
1430   Disp = DAG.getTargetConstant(0, getPointerTy());
1431   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1432     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1433     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1434   } else
1435     Base = N;
1436   return true;      // [r+0]
1437 }
1438
1439 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1440 /// represented as an indexed [r+r] operation.
1441 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1442                                                 SDValue &Index,
1443                                                 SelectionDAG &DAG) const {
1444   // Check to see if we can easily represent this as an [r+r] address.  This
1445   // will fail if it thinks that the address is more profitably represented as
1446   // reg+imm, e.g. where imm = 0.
1447   if (SelectAddressRegReg(N, Base, Index, DAG))
1448     return true;
1449
1450   // If the operand is an addition, always emit this as [r+r], since this is
1451   // better (for code size, and execution, as the memop does the add for free)
1452   // than emitting an explicit add.
1453   if (N.getOpcode() == ISD::ADD) {
1454     Base = N.getOperand(0);
1455     Index = N.getOperand(1);
1456     return true;
1457   }
1458
1459   // Otherwise, do it the hard way, using R0 as the base register.
1460   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1461                          N.getValueType());
1462   Index = N;
1463   return true;
1464 }
1465
1466 /// getPreIndexedAddressParts - returns true by value, base pointer and
1467 /// offset pointer and addressing mode by reference if the node's address
1468 /// can be legally represented as pre-indexed load / store address.
1469 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1470                                                   SDValue &Offset,
1471                                                   ISD::MemIndexedMode &AM,
1472                                                   SelectionDAG &DAG) const {
1473   if (DisablePPCPreinc) return false;
1474
1475   bool isLoad = true;
1476   SDValue Ptr;
1477   EVT VT;
1478   unsigned Alignment;
1479   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1480     Ptr = LD->getBasePtr();
1481     VT = LD->getMemoryVT();
1482     Alignment = LD->getAlignment();
1483   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1484     Ptr = ST->getBasePtr();
1485     VT  = ST->getMemoryVT();
1486     Alignment = ST->getAlignment();
1487     isLoad = false;
1488   } else
1489     return false;
1490
1491   // PowerPC doesn't have preinc load/store instructions for vectors.
1492   if (VT.isVector())
1493     return false;
1494
1495   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1496
1497     // Common code will reject creating a pre-inc form if the base pointer
1498     // is a frame index, or if N is a store and the base pointer is either
1499     // the same as or a predecessor of the value being stored.  Check for
1500     // those situations here, and try with swapped Base/Offset instead.
1501     bool Swap = false;
1502
1503     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1504       Swap = true;
1505     else if (!isLoad) {
1506       SDValue Val = cast<StoreSDNode>(N)->getValue();
1507       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1508         Swap = true;
1509     }
1510
1511     if (Swap)
1512       std::swap(Base, Offset);
1513
1514     AM = ISD::PRE_INC;
1515     return true;
1516   }
1517
1518   // LDU/STU can only handle immediates that are a multiple of 4.
1519   if (VT != MVT::i64) {
1520     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1521       return false;
1522   } else {
1523     // LDU/STU need an address with at least 4-byte alignment.
1524     if (Alignment < 4)
1525       return false;
1526
1527     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1528       return false;
1529   }
1530
1531   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1532     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1533     // sext i32 to i64 when addr mode is r+i.
1534     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1535         LD->getExtensionType() == ISD::SEXTLOAD &&
1536         isa<ConstantSDNode>(Offset))
1537       return false;
1538   }
1539
1540   AM = ISD::PRE_INC;
1541   return true;
1542 }
1543
1544 //===----------------------------------------------------------------------===//
1545 //  LowerOperation implementation
1546 //===----------------------------------------------------------------------===//
1547
1548 /// GetLabelAccessInfo - Return true if we should reference labels using a
1549 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1550 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1551                                unsigned &LoOpFlags,
1552                                const GlobalValue *GV = nullptr) {
1553   HiOpFlags = PPCII::MO_HA;
1554   LoOpFlags = PPCII::MO_LO;
1555
1556   // Don't use the pic base if not in PIC relocation model.
1557   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1558
1559   if (isPIC) {
1560     HiOpFlags |= PPCII::MO_PIC_FLAG;
1561     LoOpFlags |= PPCII::MO_PIC_FLAG;
1562   }
1563
1564   // If this is a reference to a global value that requires a non-lazy-ptr, make
1565   // sure that instruction lowering adds it.
1566   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1567     HiOpFlags |= PPCII::MO_NLP_FLAG;
1568     LoOpFlags |= PPCII::MO_NLP_FLAG;
1569
1570     if (GV->hasHiddenVisibility()) {
1571       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1572       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1573     }
1574   }
1575
1576   return isPIC;
1577 }
1578
1579 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1580                              SelectionDAG &DAG) {
1581   EVT PtrVT = HiPart.getValueType();
1582   SDValue Zero = DAG.getConstant(0, PtrVT);
1583   SDLoc DL(HiPart);
1584
1585   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1586   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1587
1588   // With PIC, the first instruction is actually "GR+hi(&G)".
1589   if (isPIC)
1590     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1591                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1592
1593   // Generate non-pic code that has direct accesses to the constant pool.
1594   // The address of the global is just (hi(&g)+lo(&g)).
1595   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1596 }
1597
1598 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1599                                              SelectionDAG &DAG) const {
1600   EVT PtrVT = Op.getValueType();
1601   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1602   const Constant *C = CP->getConstVal();
1603
1604   // 64-bit SVR4 ABI code is always position-independent.
1605   // The actual address of the GlobalValue is stored in the TOC.
1606   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1607     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1608     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1609                        DAG.getRegister(PPC::X2, MVT::i64));
1610   }
1611
1612   unsigned MOHiFlag, MOLoFlag;
1613   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1614
1615   if (isPIC && Subtarget.isSVR4ABI()) {
1616     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1617                                            PPCII::MO_PIC_FLAG);
1618     SDLoc DL(CP);
1619     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1620                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1621   }
1622
1623   SDValue CPIHi =
1624     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1625   SDValue CPILo =
1626     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1627   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1628 }
1629
1630 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1631   EVT PtrVT = Op.getValueType();
1632   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1633
1634   // 64-bit SVR4 ABI code is always position-independent.
1635   // The actual address of the GlobalValue is stored in the TOC.
1636   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1637     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1638     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1639                        DAG.getRegister(PPC::X2, MVT::i64));
1640   }
1641
1642   unsigned MOHiFlag, MOLoFlag;
1643   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1644
1645   if (isPIC && Subtarget.isSVR4ABI()) {
1646     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1647                                         PPCII::MO_PIC_FLAG);
1648     SDLoc DL(GA);
1649     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1650                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1651   }
1652
1653   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1654   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1655   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1656 }
1657
1658 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1659                                              SelectionDAG &DAG) const {
1660   EVT PtrVT = Op.getValueType();
1661   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1662   const BlockAddress *BA = BASDN->getBlockAddress();
1663
1664   // 64-bit SVR4 ABI code is always position-independent.
1665   // The actual BlockAddress is stored in the TOC.
1666   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1667     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1668     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1669                        DAG.getRegister(PPC::X2, MVT::i64));
1670   }
1671
1672   unsigned MOHiFlag, MOLoFlag;
1673   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1674   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1675   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1676   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1677 }
1678
1679 // Generate a call to __tls_get_addr for the given GOT entry Op.
1680 std::pair<SDValue,SDValue>
1681 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1682                                 SelectionDAG &DAG) const {
1683
1684   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1685   TargetLowering::ArgListTy Args;
1686   TargetLowering::ArgListEntry Entry;
1687   Entry.Node = Op;
1688   Entry.Ty = IntPtrTy;
1689   Args.push_back(Entry);
1690
1691   TargetLowering::CallLoweringInfo CLI(DAG);
1692   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1693     .setCallee(CallingConv::C, IntPtrTy,
1694                DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1695                std::move(Args), 0);
1696
1697   return LowerCallTo(CLI);
1698 }
1699
1700 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1701                                               SelectionDAG &DAG) const {
1702
1703   // FIXME: TLS addresses currently use medium model code sequences,
1704   // which is the most useful form.  Eventually support for small and
1705   // large models could be added if users need it, at the cost of
1706   // additional complexity.
1707   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1708   SDLoc dl(GA);
1709   const GlobalValue *GV = GA->getGlobal();
1710   EVT PtrVT = getPointerTy();
1711   bool is64bit = Subtarget.isPPC64();
1712   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1713   PICLevel::Level picLevel = M->getPICLevel();
1714
1715   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1716
1717   if (Model == TLSModel::LocalExec) {
1718     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1719                                                PPCII::MO_TPREL_HA);
1720     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1721                                                PPCII::MO_TPREL_LO);
1722     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1723                                      is64bit ? MVT::i64 : MVT::i32);
1724     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1725     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1726   }
1727
1728   if (Model == TLSModel::InitialExec) {
1729     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1730     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1731                                                 PPCII::MO_TLS);
1732     SDValue GOTPtr;
1733     if (is64bit) {
1734       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1735       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1736                            PtrVT, GOTReg, TGA);
1737     } else
1738       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1739     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1740                                    PtrVT, TGA, GOTPtr);
1741     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1742   }
1743
1744   if (Model == TLSModel::GeneralDynamic) {
1745     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1746                                              PPCII::MO_TLSGD);
1747     SDValue GOTPtr;
1748     if (is64bit) {
1749       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1750       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1751                                    GOTReg, TGA);
1752     } else {
1753       if (picLevel == PICLevel::Small)
1754         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1755       else
1756         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1757     }
1758     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1759                                    GOTPtr, TGA);
1760     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1761     return CallResult.first;
1762   }
1763
1764   if (Model == TLSModel::LocalDynamic) {
1765     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1766                                              PPCII::MO_TLSLD);
1767     SDValue GOTPtr;
1768     if (is64bit) {
1769       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1770       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1771                            GOTReg, TGA);
1772     } else {
1773       if (picLevel == PICLevel::Small)
1774         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1775       else
1776         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1777     }
1778     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1779                                    GOTPtr, TGA);
1780     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1781     SDValue TLSAddr = CallResult.first;
1782     SDValue Chain = CallResult.second;
1783     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1784                                       Chain, TLSAddr, TGA);
1785     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1786   }
1787
1788   llvm_unreachable("Unknown TLS model!");
1789 }
1790
1791 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1792                                               SelectionDAG &DAG) const {
1793   EVT PtrVT = Op.getValueType();
1794   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1795   SDLoc DL(GSDN);
1796   const GlobalValue *GV = GSDN->getGlobal();
1797
1798   // 64-bit SVR4 ABI code is always position-independent.
1799   // The actual address of the GlobalValue is stored in the TOC.
1800   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1801     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1802     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1803                        DAG.getRegister(PPC::X2, MVT::i64));
1804   }
1805
1806   unsigned MOHiFlag, MOLoFlag;
1807   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1808
1809   if (isPIC && Subtarget.isSVR4ABI()) {
1810     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1811                                             GSDN->getOffset(),
1812                                             PPCII::MO_PIC_FLAG);
1813     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1814                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1815   }
1816
1817   SDValue GAHi =
1818     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1819   SDValue GALo =
1820     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1821
1822   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1823
1824   // If the global reference is actually to a non-lazy-pointer, we have to do an
1825   // extra load to get the address of the global.
1826   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1827     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1828                       false, false, false, 0);
1829   return Ptr;
1830 }
1831
1832 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1833   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1834   SDLoc dl(Op);
1835
1836   if (Op.getValueType() == MVT::v2i64) {
1837     // When the operands themselves are v2i64 values, we need to do something
1838     // special because VSX has no underlying comparison operations for these.
1839     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1840       // Equality can be handled by casting to the legal type for Altivec
1841       // comparisons, everything else needs to be expanded.
1842       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1843         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1844                  DAG.getSetCC(dl, MVT::v4i32,
1845                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1846                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1847                    CC));
1848       }
1849
1850       return SDValue();
1851     }
1852
1853     // We handle most of these in the usual way.
1854     return Op;
1855   }
1856
1857   // If we're comparing for equality to zero, expose the fact that this is
1858   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1859   // fold the new nodes.
1860   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1861     if (C->isNullValue() && CC == ISD::SETEQ) {
1862       EVT VT = Op.getOperand(0).getValueType();
1863       SDValue Zext = Op.getOperand(0);
1864       if (VT.bitsLT(MVT::i32)) {
1865         VT = MVT::i32;
1866         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1867       }
1868       unsigned Log2b = Log2_32(VT.getSizeInBits());
1869       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1870       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1871                                 DAG.getConstant(Log2b, MVT::i32));
1872       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1873     }
1874     // Leave comparisons against 0 and -1 alone for now, since they're usually
1875     // optimized.  FIXME: revisit this when we can custom lower all setcc
1876     // optimizations.
1877     if (C->isAllOnesValue() || C->isNullValue())
1878       return SDValue();
1879   }
1880
1881   // If we have an integer seteq/setne, turn it into a compare against zero
1882   // by xor'ing the rhs with the lhs, which is faster than setting a
1883   // condition register, reading it back out, and masking the correct bit.  The
1884   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1885   // the result to other bit-twiddling opportunities.
1886   EVT LHSVT = Op.getOperand(0).getValueType();
1887   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1888     EVT VT = Op.getValueType();
1889     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1890                                 Op.getOperand(1));
1891     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1892   }
1893   return SDValue();
1894 }
1895
1896 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1897                                       const PPCSubtarget &Subtarget) const {
1898   SDNode *Node = Op.getNode();
1899   EVT VT = Node->getValueType(0);
1900   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1901   SDValue InChain = Node->getOperand(0);
1902   SDValue VAListPtr = Node->getOperand(1);
1903   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1904   SDLoc dl(Node);
1905
1906   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1907
1908   // gpr_index
1909   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1910                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1911                                     false, false, false, 0);
1912   InChain = GprIndex.getValue(1);
1913
1914   if (VT == MVT::i64) {
1915     // Check if GprIndex is even
1916     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1917                                  DAG.getConstant(1, MVT::i32));
1918     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1919                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1920     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1921                                           DAG.getConstant(1, MVT::i32));
1922     // Align GprIndex to be even if it isn't
1923     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1924                            GprIndex);
1925   }
1926
1927   // fpr index is 1 byte after gpr
1928   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1929                                DAG.getConstant(1, MVT::i32));
1930
1931   // fpr
1932   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1933                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1934                                     false, false, false, 0);
1935   InChain = FprIndex.getValue(1);
1936
1937   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1938                                        DAG.getConstant(8, MVT::i32));
1939
1940   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1941                                         DAG.getConstant(4, MVT::i32));
1942
1943   // areas
1944   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1945                                      MachinePointerInfo(), false, false,
1946                                      false, 0);
1947   InChain = OverflowArea.getValue(1);
1948
1949   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1950                                     MachinePointerInfo(), false, false,
1951                                     false, 0);
1952   InChain = RegSaveArea.getValue(1);
1953
1954   // select overflow_area if index > 8
1955   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1956                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1957
1958   // adjustment constant gpr_index * 4/8
1959   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1960                                     VT.isInteger() ? GprIndex : FprIndex,
1961                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1962                                                     MVT::i32));
1963
1964   // OurReg = RegSaveArea + RegConstant
1965   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1966                                RegConstant);
1967
1968   // Floating types are 32 bytes into RegSaveArea
1969   if (VT.isFloatingPoint())
1970     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1971                          DAG.getConstant(32, MVT::i32));
1972
1973   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1974   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1975                                    VT.isInteger() ? GprIndex : FprIndex,
1976                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1977                                                    MVT::i32));
1978
1979   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1980                               VT.isInteger() ? VAListPtr : FprPtr,
1981                               MachinePointerInfo(SV),
1982                               MVT::i8, false, false, 0);
1983
1984   // determine if we should load from reg_save_area or overflow_area
1985   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1986
1987   // increase overflow_area by 4/8 if gpr/fpr > 8
1988   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1989                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1990                                           MVT::i32));
1991
1992   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1993                              OverflowAreaPlusN);
1994
1995   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1996                               OverflowAreaPtr,
1997                               MachinePointerInfo(),
1998                               MVT::i32, false, false, 0);
1999
2000   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2001                      false, false, false, 0);
2002 }
2003
2004 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2005                                        const PPCSubtarget &Subtarget) const {
2006   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2007
2008   // We have to copy the entire va_list struct:
2009   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2010   return DAG.getMemcpy(Op.getOperand(0), Op,
2011                        Op.getOperand(1), Op.getOperand(2),
2012                        DAG.getConstant(12, MVT::i32), 8, false, true,
2013                        MachinePointerInfo(), MachinePointerInfo());
2014 }
2015
2016 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2017                                                   SelectionDAG &DAG) const {
2018   return Op.getOperand(0);
2019 }
2020
2021 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2022                                                 SelectionDAG &DAG) const {
2023   SDValue Chain = Op.getOperand(0);
2024   SDValue Trmp = Op.getOperand(1); // trampoline
2025   SDValue FPtr = Op.getOperand(2); // nested function
2026   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2027   SDLoc dl(Op);
2028
2029   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2030   bool isPPC64 = (PtrVT == MVT::i64);
2031   Type *IntPtrTy =
2032     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2033                                                              *DAG.getContext());
2034
2035   TargetLowering::ArgListTy Args;
2036   TargetLowering::ArgListEntry Entry;
2037
2038   Entry.Ty = IntPtrTy;
2039   Entry.Node = Trmp; Args.push_back(Entry);
2040
2041   // TrampSize == (isPPC64 ? 48 : 40);
2042   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2043                                isPPC64 ? MVT::i64 : MVT::i32);
2044   Args.push_back(Entry);
2045
2046   Entry.Node = FPtr; Args.push_back(Entry);
2047   Entry.Node = Nest; Args.push_back(Entry);
2048
2049   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2050   TargetLowering::CallLoweringInfo CLI(DAG);
2051   CLI.setDebugLoc(dl).setChain(Chain)
2052     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2053                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2054                std::move(Args), 0);
2055
2056   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2057   return CallResult.second;
2058 }
2059
2060 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2061                                         const PPCSubtarget &Subtarget) const {
2062   MachineFunction &MF = DAG.getMachineFunction();
2063   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2064
2065   SDLoc dl(Op);
2066
2067   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2068     // vastart just stores the address of the VarArgsFrameIndex slot into the
2069     // memory location argument.
2070     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2071     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2072     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2073     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2074                         MachinePointerInfo(SV),
2075                         false, false, 0);
2076   }
2077
2078   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2079   // We suppose the given va_list is already allocated.
2080   //
2081   // typedef struct {
2082   //  char gpr;     /* index into the array of 8 GPRs
2083   //                 * stored in the register save area
2084   //                 * gpr=0 corresponds to r3,
2085   //                 * gpr=1 to r4, etc.
2086   //                 */
2087   //  char fpr;     /* index into the array of 8 FPRs
2088   //                 * stored in the register save area
2089   //                 * fpr=0 corresponds to f1,
2090   //                 * fpr=1 to f2, etc.
2091   //                 */
2092   //  char *overflow_arg_area;
2093   //                /* location on stack that holds
2094   //                 * the next overflow argument
2095   //                 */
2096   //  char *reg_save_area;
2097   //               /* where r3:r10 and f1:f8 (if saved)
2098   //                * are stored
2099   //                */
2100   // } va_list[1];
2101
2102
2103   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2104   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2105
2106
2107   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2108
2109   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2110                                             PtrVT);
2111   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2112                                  PtrVT);
2113
2114   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2115   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2116
2117   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2118   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2119
2120   uint64_t FPROffset = 1;
2121   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2122
2123   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2124
2125   // Store first byte : number of int regs
2126   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2127                                          Op.getOperand(1),
2128                                          MachinePointerInfo(SV),
2129                                          MVT::i8, false, false, 0);
2130   uint64_t nextOffset = FPROffset;
2131   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2132                                   ConstFPROffset);
2133
2134   // Store second byte : number of float regs
2135   SDValue secondStore =
2136     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2137                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2138                       false, false, 0);
2139   nextOffset += StackOffset;
2140   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2141
2142   // Store second word : arguments given on stack
2143   SDValue thirdStore =
2144     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2145                  MachinePointerInfo(SV, nextOffset),
2146                  false, false, 0);
2147   nextOffset += FrameOffset;
2148   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2149
2150   // Store third word : arguments given in registers
2151   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2152                       MachinePointerInfo(SV, nextOffset),
2153                       false, false, 0);
2154
2155 }
2156
2157 #include "PPCGenCallingConv.inc"
2158
2159 // Function whose sole purpose is to kill compiler warnings 
2160 // stemming from unused functions included from PPCGenCallingConv.inc.
2161 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2162   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2163 }
2164
2165 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2166                                       CCValAssign::LocInfo &LocInfo,
2167                                       ISD::ArgFlagsTy &ArgFlags,
2168                                       CCState &State) {
2169   return true;
2170 }
2171
2172 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2173                                              MVT &LocVT,
2174                                              CCValAssign::LocInfo &LocInfo,
2175                                              ISD::ArgFlagsTy &ArgFlags,
2176                                              CCState &State) {
2177   static const MCPhysReg ArgRegs[] = {
2178     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2179     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2180   };
2181   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2182
2183   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2184
2185   // Skip one register if the first unallocated register has an even register
2186   // number and there are still argument registers available which have not been
2187   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2188   // need to skip a register if RegNum is odd.
2189   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2190     State.AllocateReg(ArgRegs[RegNum]);
2191   }
2192
2193   // Always return false here, as this function only makes sure that the first
2194   // unallocated register has an odd register number and does not actually
2195   // allocate a register for the current argument.
2196   return false;
2197 }
2198
2199 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2200                                                MVT &LocVT,
2201                                                CCValAssign::LocInfo &LocInfo,
2202                                                ISD::ArgFlagsTy &ArgFlags,
2203                                                CCState &State) {
2204   static const MCPhysReg ArgRegs[] = {
2205     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2206     PPC::F8
2207   };
2208
2209   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2210
2211   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2212
2213   // If there is only one Floating-point register left we need to put both f64
2214   // values of a split ppc_fp128 value on the stack.
2215   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2216     State.AllocateReg(ArgRegs[RegNum]);
2217   }
2218
2219   // Always return false here, as this function only makes sure that the two f64
2220   // values a ppc_fp128 value is split into are both passed in registers or both
2221   // passed on the stack and does not actually allocate a register for the
2222   // current argument.
2223   return false;
2224 }
2225
2226 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2227 /// on Darwin.
2228 static const MCPhysReg *GetFPR() {
2229   static const MCPhysReg FPR[] = {
2230     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2231     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2232   };
2233
2234   return FPR;
2235 }
2236
2237 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2238 /// the stack.
2239 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2240                                        unsigned PtrByteSize) {
2241   unsigned ArgSize = ArgVT.getStoreSize();
2242   if (Flags.isByVal())
2243     ArgSize = Flags.getByValSize();
2244
2245   // Round up to multiples of the pointer size, except for array members,
2246   // which are always packed.
2247   if (!Flags.isInConsecutiveRegs())
2248     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2249
2250   return ArgSize;
2251 }
2252
2253 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2254 /// on the stack.
2255 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2256                                             ISD::ArgFlagsTy Flags,
2257                                             unsigned PtrByteSize) {
2258   unsigned Align = PtrByteSize;
2259
2260   // Altivec parameters are padded to a 16 byte boundary.
2261   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2262       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2263       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2264     Align = 16;
2265
2266   // ByVal parameters are aligned as requested.
2267   if (Flags.isByVal()) {
2268     unsigned BVAlign = Flags.getByValAlign();
2269     if (BVAlign > PtrByteSize) {
2270       if (BVAlign % PtrByteSize != 0)
2271           llvm_unreachable(
2272             "ByVal alignment is not a multiple of the pointer size");
2273
2274       Align = BVAlign;
2275     }
2276   }
2277
2278   // Array members are always packed to their original alignment.
2279   if (Flags.isInConsecutiveRegs()) {
2280     // If the array member was split into multiple registers, the first
2281     // needs to be aligned to the size of the full type.  (Except for
2282     // ppcf128, which is only aligned as its f64 components.)
2283     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2284       Align = OrigVT.getStoreSize();
2285     else
2286       Align = ArgVT.getStoreSize();
2287   }
2288
2289   return Align;
2290 }
2291
2292 /// CalculateStackSlotUsed - Return whether this argument will use its
2293 /// stack slot (instead of being passed in registers).  ArgOffset,
2294 /// AvailableFPRs, and AvailableVRs must hold the current argument
2295 /// position, and will be updated to account for this argument.
2296 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2297                                    ISD::ArgFlagsTy Flags,
2298                                    unsigned PtrByteSize,
2299                                    unsigned LinkageSize,
2300                                    unsigned ParamAreaSize,
2301                                    unsigned &ArgOffset,
2302                                    unsigned &AvailableFPRs,
2303                                    unsigned &AvailableVRs) {
2304   bool UseMemory = false;
2305
2306   // Respect alignment of argument on the stack.
2307   unsigned Align =
2308     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2309   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2310   // If there's no space left in the argument save area, we must
2311   // use memory (this check also catches zero-sized arguments).
2312   if (ArgOffset >= LinkageSize + ParamAreaSize)
2313     UseMemory = true;
2314
2315   // Allocate argument on the stack.
2316   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2317   if (Flags.isInConsecutiveRegsLast())
2318     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2319   // If we overran the argument save area, we must use memory
2320   // (this check catches arguments passed partially in memory)
2321   if (ArgOffset > LinkageSize + ParamAreaSize)
2322     UseMemory = true;
2323
2324   // However, if the argument is actually passed in an FPR or a VR,
2325   // we don't use memory after all.
2326   if (!Flags.isByVal()) {
2327     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2328       if (AvailableFPRs > 0) {
2329         --AvailableFPRs;
2330         return false;
2331       }
2332     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2333         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2334         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2335       if (AvailableVRs > 0) {
2336         --AvailableVRs;
2337         return false;
2338       }
2339   }
2340
2341   return UseMemory;
2342 }
2343
2344 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2345 /// ensure minimum alignment required for target.
2346 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2347                                      unsigned NumBytes) {
2348   unsigned TargetAlign =
2349       Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2350   unsigned AlignMask = TargetAlign - 1;
2351   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2352   return NumBytes;
2353 }
2354
2355 SDValue
2356 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2357                                         CallingConv::ID CallConv, bool isVarArg,
2358                                         const SmallVectorImpl<ISD::InputArg>
2359                                           &Ins,
2360                                         SDLoc dl, SelectionDAG &DAG,
2361                                         SmallVectorImpl<SDValue> &InVals)
2362                                           const {
2363   if (Subtarget.isSVR4ABI()) {
2364     if (Subtarget.isPPC64())
2365       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2366                                          dl, DAG, InVals);
2367     else
2368       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2369                                          dl, DAG, InVals);
2370   } else {
2371     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2372                                        dl, DAG, InVals);
2373   }
2374 }
2375
2376 SDValue
2377 PPCTargetLowering::LowerFormalArguments_32SVR4(
2378                                       SDValue Chain,
2379                                       CallingConv::ID CallConv, bool isVarArg,
2380                                       const SmallVectorImpl<ISD::InputArg>
2381                                         &Ins,
2382                                       SDLoc dl, SelectionDAG &DAG,
2383                                       SmallVectorImpl<SDValue> &InVals) const {
2384
2385   // 32-bit SVR4 ABI Stack Frame Layout:
2386   //              +-----------------------------------+
2387   //        +-->  |            Back chain             |
2388   //        |     +-----------------------------------+
2389   //        |     | Floating-point register save area |
2390   //        |     +-----------------------------------+
2391   //        |     |    General register save area     |
2392   //        |     +-----------------------------------+
2393   //        |     |          CR save word             |
2394   //        |     +-----------------------------------+
2395   //        |     |         VRSAVE save word          |
2396   //        |     +-----------------------------------+
2397   //        |     |         Alignment padding         |
2398   //        |     +-----------------------------------+
2399   //        |     |     Vector register save area     |
2400   //        |     +-----------------------------------+
2401   //        |     |       Local variable space        |
2402   //        |     +-----------------------------------+
2403   //        |     |        Parameter list area        |
2404   //        |     +-----------------------------------+
2405   //        |     |           LR save word            |
2406   //        |     +-----------------------------------+
2407   // SP-->  +---  |            Back chain             |
2408   //              +-----------------------------------+
2409   //
2410   // Specifications:
2411   //   System V Application Binary Interface PowerPC Processor Supplement
2412   //   AltiVec Technology Programming Interface Manual
2413
2414   MachineFunction &MF = DAG.getMachineFunction();
2415   MachineFrameInfo *MFI = MF.getFrameInfo();
2416   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2417
2418   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2419   // Potential tail calls could cause overwriting of argument stack slots.
2420   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2421                        (CallConv == CallingConv::Fast));
2422   unsigned PtrByteSize = 4;
2423
2424   // Assign locations to all of the incoming arguments.
2425   SmallVector<CCValAssign, 16> ArgLocs;
2426   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2427                  *DAG.getContext());
2428
2429   // Reserve space for the linkage area on the stack.
2430   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2431   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2432
2433   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2434
2435   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2436     CCValAssign &VA = ArgLocs[i];
2437
2438     // Arguments stored in registers.
2439     if (VA.isRegLoc()) {
2440       const TargetRegisterClass *RC;
2441       EVT ValVT = VA.getValVT();
2442
2443       switch (ValVT.getSimpleVT().SimpleTy) {
2444         default:
2445           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2446         case MVT::i1:
2447         case MVT::i32:
2448           RC = &PPC::GPRCRegClass;
2449           break;
2450         case MVT::f32:
2451           RC = &PPC::F4RCRegClass;
2452           break;
2453         case MVT::f64:
2454           if (Subtarget.hasVSX())
2455             RC = &PPC::VSFRCRegClass;
2456           else
2457             RC = &PPC::F8RCRegClass;
2458           break;
2459         case MVT::v16i8:
2460         case MVT::v8i16:
2461         case MVT::v4i32:
2462         case MVT::v4f32:
2463           RC = &PPC::VRRCRegClass;
2464           break;
2465         case MVT::v2f64:
2466         case MVT::v2i64:
2467           RC = &PPC::VSHRCRegClass;
2468           break;
2469       }
2470
2471       // Transform the arguments stored in physical registers into virtual ones.
2472       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2473       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2474                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2475
2476       if (ValVT == MVT::i1)
2477         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2478
2479       InVals.push_back(ArgValue);
2480     } else {
2481       // Argument stored in memory.
2482       assert(VA.isMemLoc());
2483
2484       unsigned ArgSize = VA.getLocVT().getStoreSize();
2485       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2486                                       isImmutable);
2487
2488       // Create load nodes to retrieve arguments from the stack.
2489       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2490       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2491                                    MachinePointerInfo(),
2492                                    false, false, false, 0));
2493     }
2494   }
2495
2496   // Assign locations to all of the incoming aggregate by value arguments.
2497   // Aggregates passed by value are stored in the local variable space of the
2498   // caller's stack frame, right above the parameter list area.
2499   SmallVector<CCValAssign, 16> ByValArgLocs;
2500   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2501                       ByValArgLocs, *DAG.getContext());
2502
2503   // Reserve stack space for the allocations in CCInfo.
2504   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2505
2506   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2507
2508   // Area that is at least reserved in the caller of this function.
2509   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2510   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2511
2512   // Set the size that is at least reserved in caller of this function.  Tail
2513   // call optimized function's reserved stack space needs to be aligned so that
2514   // taking the difference between two stack areas will result in an aligned
2515   // stack.
2516   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2517   FuncInfo->setMinReservedArea(MinReservedArea);
2518
2519   SmallVector<SDValue, 8> MemOps;
2520
2521   // If the function takes variable number of arguments, make a frame index for
2522   // the start of the first vararg value... for expansion of llvm.va_start.
2523   if (isVarArg) {
2524     static const MCPhysReg GPArgRegs[] = {
2525       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2526       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2527     };
2528     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2529
2530     static const MCPhysReg FPArgRegs[] = {
2531       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2532       PPC::F8
2533     };
2534     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2535     if (DisablePPCFloatInVariadic)
2536       NumFPArgRegs = 0;
2537
2538     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2539                                                           NumGPArgRegs));
2540     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2541                                                           NumFPArgRegs));
2542
2543     // Make room for NumGPArgRegs and NumFPArgRegs.
2544     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2545                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2546
2547     FuncInfo->setVarArgsStackOffset(
2548       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2549                              CCInfo.getNextStackOffset(), true));
2550
2551     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2552     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2553
2554     // The fixed integer arguments of a variadic function are stored to the
2555     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2556     // the result of va_next.
2557     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2558       // Get an existing live-in vreg, or add a new one.
2559       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2560       if (!VReg)
2561         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2562
2563       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2564       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2565                                    MachinePointerInfo(), false, false, 0);
2566       MemOps.push_back(Store);
2567       // Increment the address by four for the next argument to store
2568       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2569       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2570     }
2571
2572     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2573     // is set.
2574     // The double arguments are stored to the VarArgsFrameIndex
2575     // on the stack.
2576     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2577       // Get an existing live-in vreg, or add a new one.
2578       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2579       if (!VReg)
2580         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2581
2582       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2583       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2584                                    MachinePointerInfo(), false, false, 0);
2585       MemOps.push_back(Store);
2586       // Increment the address by eight for the next argument to store
2587       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2588                                          PtrVT);
2589       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2590     }
2591   }
2592
2593   if (!MemOps.empty())
2594     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2595
2596   return Chain;
2597 }
2598
2599 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2600 // value to MVT::i64 and then truncate to the correct register size.
2601 SDValue
2602 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2603                                      SelectionDAG &DAG, SDValue ArgVal,
2604                                      SDLoc dl) const {
2605   if (Flags.isSExt())
2606     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2607                          DAG.getValueType(ObjectVT));
2608   else if (Flags.isZExt())
2609     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2610                          DAG.getValueType(ObjectVT));
2611
2612   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2613 }
2614
2615 SDValue
2616 PPCTargetLowering::LowerFormalArguments_64SVR4(
2617                                       SDValue Chain,
2618                                       CallingConv::ID CallConv, bool isVarArg,
2619                                       const SmallVectorImpl<ISD::InputArg>
2620                                         &Ins,
2621                                       SDLoc dl, SelectionDAG &DAG,
2622                                       SmallVectorImpl<SDValue> &InVals) const {
2623   // TODO: add description of PPC stack frame format, or at least some docs.
2624   //
2625   bool isELFv2ABI = Subtarget.isELFv2ABI();
2626   bool isLittleEndian = Subtarget.isLittleEndian();
2627   MachineFunction &MF = DAG.getMachineFunction();
2628   MachineFrameInfo *MFI = MF.getFrameInfo();
2629   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2630
2631   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2632   // Potential tail calls could cause overwriting of argument stack slots.
2633   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2634                        (CallConv == CallingConv::Fast));
2635   unsigned PtrByteSize = 8;
2636
2637   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2638                                                           isELFv2ABI);
2639
2640   static const MCPhysReg GPR[] = {
2641     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2642     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2643   };
2644
2645   static const MCPhysReg *FPR = GetFPR();
2646
2647   static const MCPhysReg VR[] = {
2648     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2649     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2650   };
2651   static const MCPhysReg VSRH[] = {
2652     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2653     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2654   };
2655
2656   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2657   const unsigned Num_FPR_Regs = 13;
2658   const unsigned Num_VR_Regs  = array_lengthof(VR);
2659
2660   // Do a first pass over the arguments to determine whether the ABI
2661   // guarantees that our caller has allocated the parameter save area
2662   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2663   // in the ELFv2 ABI, it is true if this is a vararg function or if
2664   // any parameter is located in a stack slot.
2665
2666   bool HasParameterArea = !isELFv2ABI || isVarArg;
2667   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2668   unsigned NumBytes = LinkageSize;
2669   unsigned AvailableFPRs = Num_FPR_Regs;
2670   unsigned AvailableVRs = Num_VR_Regs;
2671   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2672     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2673                                PtrByteSize, LinkageSize, ParamAreaSize,
2674                                NumBytes, AvailableFPRs, AvailableVRs))
2675       HasParameterArea = true;
2676
2677   // Add DAG nodes to load the arguments or copy them out of registers.  On
2678   // entry to a function on PPC, the arguments start after the linkage area,
2679   // although the first ones are often in registers.
2680
2681   unsigned ArgOffset = LinkageSize;
2682   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2683   SmallVector<SDValue, 8> MemOps;
2684   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2685   unsigned CurArgIdx = 0;
2686   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2687     SDValue ArgVal;
2688     bool needsLoad = false;
2689     EVT ObjectVT = Ins[ArgNo].VT;
2690     EVT OrigVT = Ins[ArgNo].ArgVT;
2691     unsigned ObjSize = ObjectVT.getStoreSize();
2692     unsigned ArgSize = ObjSize;
2693     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2694     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2695     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2696
2697     /* Respect alignment of argument on the stack.  */
2698     unsigned Align =
2699       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2700     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2701     unsigned CurArgOffset = ArgOffset;
2702
2703     /* Compute GPR index associated with argument offset.  */
2704     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2705     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2706
2707     // FIXME the codegen can be much improved in some cases.
2708     // We do not have to keep everything in memory.
2709     if (Flags.isByVal()) {
2710       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2711       ObjSize = Flags.getByValSize();
2712       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2713       // Empty aggregate parameters do not take up registers.  Examples:
2714       //   struct { } a;
2715       //   union  { } b;
2716       //   int c[0];
2717       // etc.  However, we have to provide a place-holder in InVals, so
2718       // pretend we have an 8-byte item at the current address for that
2719       // purpose.
2720       if (!ObjSize) {
2721         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2722         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2723         InVals.push_back(FIN);
2724         continue;
2725       }
2726
2727       // Create a stack object covering all stack doublewords occupied
2728       // by the argument.  If the argument is (fully or partially) on
2729       // the stack, or if the argument is fully in registers but the
2730       // caller has allocated the parameter save anyway, we can refer
2731       // directly to the caller's stack frame.  Otherwise, create a
2732       // local copy in our own frame.
2733       int FI;
2734       if (HasParameterArea ||
2735           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2736         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2737       else
2738         FI = MFI->CreateStackObject(ArgSize, Align, false);
2739       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2740
2741       // Handle aggregates smaller than 8 bytes.
2742       if (ObjSize < PtrByteSize) {
2743         // The value of the object is its address, which differs from the
2744         // address of the enclosing doubleword on big-endian systems.
2745         SDValue Arg = FIN;
2746         if (!isLittleEndian) {
2747           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2748           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2749         }
2750         InVals.push_back(Arg);
2751
2752         if (GPR_idx != Num_GPR_Regs) {
2753           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2754           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2755           SDValue Store;
2756
2757           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2758             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2759                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2760             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2761                                       MachinePointerInfo(FuncArg),
2762                                       ObjType, false, false, 0);
2763           } else {
2764             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2765             // store the whole register as-is to the parameter save area
2766             // slot.
2767             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2768                                  MachinePointerInfo(FuncArg),
2769                                  false, false, 0);
2770           }
2771
2772           MemOps.push_back(Store);
2773         }
2774         // Whether we copied from a register or not, advance the offset
2775         // into the parameter save area by a full doubleword.
2776         ArgOffset += PtrByteSize;
2777         continue;
2778       }
2779
2780       // The value of the object is its address, which is the address of
2781       // its first stack doubleword.
2782       InVals.push_back(FIN);
2783
2784       // Store whatever pieces of the object are in registers to memory.
2785       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2786         if (GPR_idx == Num_GPR_Regs)
2787           break;
2788
2789         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2790         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2791         SDValue Addr = FIN;
2792         if (j) {
2793           SDValue Off = DAG.getConstant(j, PtrVT);
2794           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2795         }
2796         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2797                                      MachinePointerInfo(FuncArg, j),
2798                                      false, false, 0);
2799         MemOps.push_back(Store);
2800         ++GPR_idx;
2801       }
2802       ArgOffset += ArgSize;
2803       continue;
2804     }
2805
2806     switch (ObjectVT.getSimpleVT().SimpleTy) {
2807     default: llvm_unreachable("Unhandled argument type!");
2808     case MVT::i1:
2809     case MVT::i32:
2810     case MVT::i64:
2811       // These can be scalar arguments or elements of an integer array type
2812       // passed directly.  Clang may use those instead of "byval" aggregate
2813       // types to avoid forcing arguments to memory unnecessarily.
2814       if (GPR_idx != Num_GPR_Regs) {
2815         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2816         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2817
2818         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2819           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2820           // value to MVT::i64 and then truncate to the correct register size.
2821           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2822       } else {
2823         needsLoad = true;
2824         ArgSize = PtrByteSize;
2825       }
2826       ArgOffset += 8;
2827       break;
2828
2829     case MVT::f32:
2830     case MVT::f64:
2831       // These can be scalar arguments or elements of a float array type
2832       // passed directly.  The latter are used to implement ELFv2 homogenous
2833       // float aggregates.
2834       if (FPR_idx != Num_FPR_Regs) {
2835         unsigned VReg;
2836
2837         if (ObjectVT == MVT::f32)
2838           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2839         else
2840           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2841                                             &PPC::VSFRCRegClass :
2842                                             &PPC::F8RCRegClass);
2843
2844         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2845         ++FPR_idx;
2846       } else if (GPR_idx != Num_GPR_Regs) {
2847         // This can only ever happen in the presence of f32 array types,
2848         // since otherwise we never run out of FPRs before running out
2849         // of GPRs.
2850         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2851         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2852
2853         if (ObjectVT == MVT::f32) {
2854           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2855             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2856                                  DAG.getConstant(32, MVT::i32));
2857           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2858         }
2859
2860         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2861       } else {
2862         needsLoad = true;
2863       }
2864
2865       // When passing an array of floats, the array occupies consecutive
2866       // space in the argument area; only round up to the next doubleword
2867       // at the end of the array.  Otherwise, each float takes 8 bytes.
2868       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2869       ArgOffset += ArgSize;
2870       if (Flags.isInConsecutiveRegsLast())
2871         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2872       break;
2873     case MVT::v4f32:
2874     case MVT::v4i32:
2875     case MVT::v8i16:
2876     case MVT::v16i8:
2877     case MVT::v2f64:
2878     case MVT::v2i64:
2879       // These can be scalar arguments or elements of a vector array type
2880       // passed directly.  The latter are used to implement ELFv2 homogenous
2881       // vector aggregates.
2882       if (VR_idx != Num_VR_Regs) {
2883         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2884                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2885                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2886         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2887         ++VR_idx;
2888       } else {
2889         needsLoad = true;
2890       }
2891       ArgOffset += 16;
2892       break;
2893     }
2894
2895     // We need to load the argument to a virtual register if we determined
2896     // above that we ran out of physical registers of the appropriate type.
2897     if (needsLoad) {
2898       if (ObjSize < ArgSize && !isLittleEndian)
2899         CurArgOffset += ArgSize - ObjSize;
2900       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2901       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2902       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2903                            false, false, false, 0);
2904     }
2905
2906     InVals.push_back(ArgVal);
2907   }
2908
2909   // Area that is at least reserved in the caller of this function.
2910   unsigned MinReservedArea;
2911   if (HasParameterArea)
2912     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2913   else
2914     MinReservedArea = LinkageSize;
2915
2916   // Set the size that is at least reserved in caller of this function.  Tail
2917   // call optimized functions' reserved stack space needs to be aligned so that
2918   // taking the difference between two stack areas will result in an aligned
2919   // stack.
2920   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2921   FuncInfo->setMinReservedArea(MinReservedArea);
2922
2923   // If the function takes variable number of arguments, make a frame index for
2924   // the start of the first vararg value... for expansion of llvm.va_start.
2925   if (isVarArg) {
2926     int Depth = ArgOffset;
2927
2928     FuncInfo->setVarArgsFrameIndex(
2929       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2930     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2931
2932     // If this function is vararg, store any remaining integer argument regs
2933     // to their spots on the stack so that they may be loaded by deferencing the
2934     // result of va_next.
2935     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2936          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2937       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2938       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2939       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2940                                    MachinePointerInfo(), false, false, 0);
2941       MemOps.push_back(Store);
2942       // Increment the address by four for the next argument to store
2943       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2944       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2945     }
2946   }
2947
2948   if (!MemOps.empty())
2949     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2950
2951   return Chain;
2952 }
2953
2954 SDValue
2955 PPCTargetLowering::LowerFormalArguments_Darwin(
2956                                       SDValue Chain,
2957                                       CallingConv::ID CallConv, bool isVarArg,
2958                                       const SmallVectorImpl<ISD::InputArg>
2959                                         &Ins,
2960                                       SDLoc dl, SelectionDAG &DAG,
2961                                       SmallVectorImpl<SDValue> &InVals) const {
2962   // TODO: add description of PPC stack frame format, or at least some docs.
2963   //
2964   MachineFunction &MF = DAG.getMachineFunction();
2965   MachineFrameInfo *MFI = MF.getFrameInfo();
2966   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2967
2968   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2969   bool isPPC64 = PtrVT == MVT::i64;
2970   // Potential tail calls could cause overwriting of argument stack slots.
2971   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2972                        (CallConv == CallingConv::Fast));
2973   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2974
2975   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2976                                                           false);
2977   unsigned ArgOffset = LinkageSize;
2978   // Area that is at least reserved in caller of this function.
2979   unsigned MinReservedArea = ArgOffset;
2980
2981   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2982     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2983     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2984   };
2985   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2986     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2987     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2988   };
2989
2990   static const MCPhysReg *FPR = GetFPR();
2991
2992   static const MCPhysReg VR[] = {
2993     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2994     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2995   };
2996
2997   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2998   const unsigned Num_FPR_Regs = 13;
2999   const unsigned Num_VR_Regs  = array_lengthof( VR);
3000
3001   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3002
3003   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3004
3005   // In 32-bit non-varargs functions, the stack space for vectors is after the
3006   // stack space for non-vectors.  We do not use this space unless we have
3007   // too many vectors to fit in registers, something that only occurs in
3008   // constructed examples:), but we have to walk the arglist to figure
3009   // that out...for the pathological case, compute VecArgOffset as the
3010   // start of the vector parameter area.  Computing VecArgOffset is the
3011   // entire point of the following loop.
3012   unsigned VecArgOffset = ArgOffset;
3013   if (!isVarArg && !isPPC64) {
3014     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3015          ++ArgNo) {
3016       EVT ObjectVT = Ins[ArgNo].VT;
3017       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3018
3019       if (Flags.isByVal()) {
3020         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3021         unsigned ObjSize = Flags.getByValSize();
3022         unsigned ArgSize =
3023                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3024         VecArgOffset += ArgSize;
3025         continue;
3026       }
3027
3028       switch(ObjectVT.getSimpleVT().SimpleTy) {
3029       default: llvm_unreachable("Unhandled argument type!");
3030       case MVT::i1:
3031       case MVT::i32:
3032       case MVT::f32:
3033         VecArgOffset += 4;
3034         break;
3035       case MVT::i64:  // PPC64
3036       case MVT::f64:
3037         // FIXME: We are guaranteed to be !isPPC64 at this point.
3038         // Does MVT::i64 apply?
3039         VecArgOffset += 8;
3040         break;
3041       case MVT::v4f32:
3042       case MVT::v4i32:
3043       case MVT::v8i16:
3044       case MVT::v16i8:
3045         // Nothing to do, we're only looking at Nonvector args here.
3046         break;
3047       }
3048     }
3049   }
3050   // We've found where the vector parameter area in memory is.  Skip the
3051   // first 12 parameters; these don't use that memory.
3052   VecArgOffset = ((VecArgOffset+15)/16)*16;
3053   VecArgOffset += 12*16;
3054
3055   // Add DAG nodes to load the arguments or copy them out of registers.  On
3056   // entry to a function on PPC, the arguments start after the linkage area,
3057   // although the first ones are often in registers.
3058
3059   SmallVector<SDValue, 8> MemOps;
3060   unsigned nAltivecParamsAtEnd = 0;
3061   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3062   unsigned CurArgIdx = 0;
3063   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3064     SDValue ArgVal;
3065     bool needsLoad = false;
3066     EVT ObjectVT = Ins[ArgNo].VT;
3067     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3068     unsigned ArgSize = ObjSize;
3069     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3070     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3071     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3072
3073     unsigned CurArgOffset = ArgOffset;
3074
3075     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3076     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3077         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3078       if (isVarArg || isPPC64) {
3079         MinReservedArea = ((MinReservedArea+15)/16)*16;
3080         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3081                                                   Flags,
3082                                                   PtrByteSize);
3083       } else  nAltivecParamsAtEnd++;
3084     } else
3085       // Calculate min reserved area.
3086       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3087                                                 Flags,
3088                                                 PtrByteSize);
3089
3090     // FIXME the codegen can be much improved in some cases.
3091     // We do not have to keep everything in memory.
3092     if (Flags.isByVal()) {
3093       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3094       ObjSize = Flags.getByValSize();
3095       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3096       // Objects of size 1 and 2 are right justified, everything else is
3097       // left justified.  This means the memory address is adjusted forwards.
3098       if (ObjSize==1 || ObjSize==2) {
3099         CurArgOffset = CurArgOffset + (4 - ObjSize);
3100       }
3101       // The value of the object is its address.
3102       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3103       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3104       InVals.push_back(FIN);
3105       if (ObjSize==1 || ObjSize==2) {
3106         if (GPR_idx != Num_GPR_Regs) {
3107           unsigned VReg;
3108           if (isPPC64)
3109             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3110           else
3111             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3112           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3113           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3114           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3115                                             MachinePointerInfo(FuncArg),
3116                                             ObjType, false, false, 0);
3117           MemOps.push_back(Store);
3118           ++GPR_idx;
3119         }
3120
3121         ArgOffset += PtrByteSize;
3122
3123         continue;
3124       }
3125       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3126         // Store whatever pieces of the object are in registers
3127         // to memory.  ArgOffset will be the address of the beginning
3128         // of the object.
3129         if (GPR_idx != Num_GPR_Regs) {
3130           unsigned VReg;
3131           if (isPPC64)
3132             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3133           else
3134             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3135           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3136           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3137           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3138           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3139                                        MachinePointerInfo(FuncArg, j),
3140                                        false, false, 0);
3141           MemOps.push_back(Store);
3142           ++GPR_idx;
3143           ArgOffset += PtrByteSize;
3144         } else {
3145           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3146           break;
3147         }
3148       }
3149       continue;
3150     }
3151
3152     switch (ObjectVT.getSimpleVT().SimpleTy) {
3153     default: llvm_unreachable("Unhandled argument type!");
3154     case MVT::i1:
3155     case MVT::i32:
3156       if (!isPPC64) {
3157         if (GPR_idx != Num_GPR_Regs) {
3158           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3159           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3160
3161           if (ObjectVT == MVT::i1)
3162             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3163
3164           ++GPR_idx;
3165         } else {
3166           needsLoad = true;
3167           ArgSize = PtrByteSize;
3168         }
3169         // All int arguments reserve stack space in the Darwin ABI.
3170         ArgOffset += PtrByteSize;
3171         break;
3172       }
3173       // FALLTHROUGH
3174     case MVT::i64:  // PPC64
3175       if (GPR_idx != Num_GPR_Regs) {
3176         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3177         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3178
3179         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3180           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3181           // value to MVT::i64 and then truncate to the correct register size.
3182           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3183
3184         ++GPR_idx;
3185       } else {
3186         needsLoad = true;
3187         ArgSize = PtrByteSize;
3188       }
3189       // All int arguments reserve stack space in the Darwin ABI.
3190       ArgOffset += 8;
3191       break;
3192
3193     case MVT::f32:
3194     case MVT::f64:
3195       // Every 4 bytes of argument space consumes one of the GPRs available for
3196       // argument passing.
3197       if (GPR_idx != Num_GPR_Regs) {
3198         ++GPR_idx;
3199         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3200           ++GPR_idx;
3201       }
3202       if (FPR_idx != Num_FPR_Regs) {
3203         unsigned VReg;
3204
3205         if (ObjectVT == MVT::f32)
3206           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3207         else
3208           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3209
3210         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3211         ++FPR_idx;
3212       } else {
3213         needsLoad = true;
3214       }
3215
3216       // All FP arguments reserve stack space in the Darwin ABI.
3217       ArgOffset += isPPC64 ? 8 : ObjSize;
3218       break;
3219     case MVT::v4f32:
3220     case MVT::v4i32:
3221     case MVT::v8i16:
3222     case MVT::v16i8:
3223       // Note that vector arguments in registers don't reserve stack space,
3224       // except in varargs functions.
3225       if (VR_idx != Num_VR_Regs) {
3226         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3227         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3228         if (isVarArg) {
3229           while ((ArgOffset % 16) != 0) {
3230             ArgOffset += PtrByteSize;
3231             if (GPR_idx != Num_GPR_Regs)
3232               GPR_idx++;
3233           }
3234           ArgOffset += 16;
3235           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3236         }
3237         ++VR_idx;
3238       } else {
3239         if (!isVarArg && !isPPC64) {
3240           // Vectors go after all the nonvectors.
3241           CurArgOffset = VecArgOffset;
3242           VecArgOffset += 16;
3243         } else {
3244           // Vectors are aligned.
3245           ArgOffset = ((ArgOffset+15)/16)*16;
3246           CurArgOffset = ArgOffset;
3247           ArgOffset += 16;
3248         }
3249         needsLoad = true;
3250       }
3251       break;
3252     }
3253
3254     // We need to load the argument to a virtual register if we determined above
3255     // that we ran out of physical registers of the appropriate type.
3256     if (needsLoad) {
3257       int FI = MFI->CreateFixedObject(ObjSize,
3258                                       CurArgOffset + (ArgSize - ObjSize),
3259                                       isImmutable);
3260       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3261       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3262                            false, false, false, 0);
3263     }
3264
3265     InVals.push_back(ArgVal);
3266   }
3267
3268   // Allow for Altivec parameters at the end, if needed.
3269   if (nAltivecParamsAtEnd) {
3270     MinReservedArea = ((MinReservedArea+15)/16)*16;
3271     MinReservedArea += 16*nAltivecParamsAtEnd;
3272   }
3273
3274   // Area that is at least reserved in the caller of this function.
3275   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3276
3277   // Set the size that is at least reserved in caller of this function.  Tail
3278   // call optimized functions' reserved stack space needs to be aligned so that
3279   // taking the difference between two stack areas will result in an aligned
3280   // stack.
3281   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3282   FuncInfo->setMinReservedArea(MinReservedArea);
3283
3284   // If the function takes variable number of arguments, make a frame index for
3285   // the start of the first vararg value... for expansion of llvm.va_start.
3286   if (isVarArg) {
3287     int Depth = ArgOffset;
3288
3289     FuncInfo->setVarArgsFrameIndex(
3290       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3291                              Depth, true));
3292     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3293
3294     // If this function is vararg, store any remaining integer argument regs
3295     // to their spots on the stack so that they may be loaded by deferencing the
3296     // result of va_next.
3297     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3298       unsigned VReg;
3299
3300       if (isPPC64)
3301         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3302       else
3303         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3304
3305       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3306       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3307                                    MachinePointerInfo(), false, false, 0);
3308       MemOps.push_back(Store);
3309       // Increment the address by four for the next argument to store
3310       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3311       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3312     }
3313   }
3314
3315   if (!MemOps.empty())
3316     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3317
3318   return Chain;
3319 }
3320
3321 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3322 /// adjusted to accommodate the arguments for the tailcall.
3323 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3324                                    unsigned ParamSize) {
3325
3326   if (!isTailCall) return 0;
3327
3328   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3329   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3330   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3331   // Remember only if the new adjustement is bigger.
3332   if (SPDiff < FI->getTailCallSPDelta())
3333     FI->setTailCallSPDelta(SPDiff);
3334
3335   return SPDiff;
3336 }
3337
3338 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3339 /// for tail call optimization. Targets which want to do tail call
3340 /// optimization should implement this function.
3341 bool
3342 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3343                                                      CallingConv::ID CalleeCC,
3344                                                      bool isVarArg,
3345                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3346                                                      SelectionDAG& DAG) const {
3347   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3348     return false;
3349
3350   // Variable argument functions are not supported.
3351   if (isVarArg)
3352     return false;
3353
3354   MachineFunction &MF = DAG.getMachineFunction();
3355   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3356   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3357     // Functions containing by val parameters are not supported.
3358     for (unsigned i = 0; i != Ins.size(); i++) {
3359        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3360        if (Flags.isByVal()) return false;
3361     }
3362
3363     // Non-PIC/GOT tail calls are supported.
3364     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3365       return true;
3366
3367     // At the moment we can only do local tail calls (in same module, hidden
3368     // or protected) if we are generating PIC.
3369     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3370       return G->getGlobal()->hasHiddenVisibility()
3371           || G->getGlobal()->hasProtectedVisibility();
3372   }
3373
3374   return false;
3375 }
3376
3377 /// isCallCompatibleAddress - Return the immediate to use if the specified
3378 /// 32-bit value is representable in the immediate field of a BxA instruction.
3379 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3380   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3381   if (!C) return nullptr;
3382
3383   int Addr = C->getZExtValue();
3384   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3385       SignExtend32<26>(Addr) != Addr)
3386     return nullptr;  // Top 6 bits have to be sext of immediate.
3387
3388   return DAG.getConstant((int)C->getZExtValue() >> 2,
3389                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3390 }
3391
3392 namespace {
3393
3394 struct TailCallArgumentInfo {
3395   SDValue Arg;
3396   SDValue FrameIdxOp;
3397   int       FrameIdx;
3398
3399   TailCallArgumentInfo() : FrameIdx(0) {}
3400 };
3401
3402 }
3403
3404 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3405 static void
3406 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3407                                            SDValue Chain,
3408                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3409                    SmallVectorImpl<SDValue> &MemOpChains,
3410                    SDLoc dl) {
3411   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3412     SDValue Arg = TailCallArgs[i].Arg;
3413     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3414     int FI = TailCallArgs[i].FrameIdx;
3415     // Store relative to framepointer.
3416     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3417                                        MachinePointerInfo::getFixedStack(FI),
3418                                        false, false, 0));
3419   }
3420 }
3421
3422 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3423 /// the appropriate stack slot for the tail call optimized function call.
3424 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3425                                                MachineFunction &MF,
3426                                                SDValue Chain,
3427                                                SDValue OldRetAddr,
3428                                                SDValue OldFP,
3429                                                int SPDiff,
3430                                                bool isPPC64,
3431                                                bool isDarwinABI,
3432                                                SDLoc dl) {
3433   if (SPDiff) {
3434     // Calculate the new stack slot for the return address.
3435     int SlotSize = isPPC64 ? 8 : 4;
3436     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3437                                                                    isDarwinABI);
3438     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3439                                                           NewRetAddrLoc, true);
3440     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3441     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3442     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3443                          MachinePointerInfo::getFixedStack(NewRetAddr),
3444                          false, false, 0);
3445
3446     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3447     // slot as the FP is never overwritten.
3448     if (isDarwinABI) {
3449       int NewFPLoc =
3450         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3451       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3452                                                           true);
3453       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3454       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3455                            MachinePointerInfo::getFixedStack(NewFPIdx),
3456                            false, false, 0);
3457     }
3458   }
3459   return Chain;
3460 }
3461
3462 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3463 /// the position of the argument.
3464 static void
3465 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3466                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3467                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3468   int Offset = ArgOffset + SPDiff;
3469   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3470   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3471   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3472   SDValue FIN = DAG.getFrameIndex(FI, VT);
3473   TailCallArgumentInfo Info;
3474   Info.Arg = Arg;
3475   Info.FrameIdxOp = FIN;
3476   Info.FrameIdx = FI;
3477   TailCallArguments.push_back(Info);
3478 }
3479
3480 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3481 /// stack slot. Returns the chain as result and the loaded frame pointers in
3482 /// LROpOut/FPOpout. Used when tail calling.
3483 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3484                                                         int SPDiff,
3485                                                         SDValue Chain,
3486                                                         SDValue &LROpOut,
3487                                                         SDValue &FPOpOut,
3488                                                         bool isDarwinABI,
3489                                                         SDLoc dl) const {
3490   if (SPDiff) {
3491     // Load the LR and FP stack slot for later adjusting.
3492     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3493     LROpOut = getReturnAddrFrameIndex(DAG);
3494     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3495                           false, false, false, 0);
3496     Chain = SDValue(LROpOut.getNode(), 1);
3497
3498     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3499     // slot as the FP is never overwritten.
3500     if (isDarwinABI) {
3501       FPOpOut = getFramePointerFrameIndex(DAG);
3502       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3503                             false, false, false, 0);
3504       Chain = SDValue(FPOpOut.getNode(), 1);
3505     }
3506   }
3507   return Chain;
3508 }
3509
3510 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3511 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3512 /// specified by the specific parameter attribute. The copy will be passed as
3513 /// a byval function parameter.
3514 /// Sometimes what we are copying is the end of a larger object, the part that
3515 /// does not fit in registers.
3516 static SDValue
3517 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3518                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3519                           SDLoc dl) {
3520   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3521   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3522                        false, false, MachinePointerInfo(),
3523                        MachinePointerInfo());
3524 }
3525
3526 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3527 /// tail calls.
3528 static void
3529 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3530                  SDValue Arg, SDValue PtrOff, int SPDiff,
3531                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3532                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3533                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3534                  SDLoc dl) {
3535   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3536   if (!isTailCall) {
3537     if (isVector) {
3538       SDValue StackPtr;
3539       if (isPPC64)
3540         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3541       else
3542         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3543       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3544                            DAG.getConstant(ArgOffset, PtrVT));
3545     }
3546     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3547                                        MachinePointerInfo(), false, false, 0));
3548   // Calculate and remember argument location.
3549   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3550                                   TailCallArguments);
3551 }
3552
3553 static
3554 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3555                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3556                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3557                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3558   MachineFunction &MF = DAG.getMachineFunction();
3559
3560   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3561   // might overwrite each other in case of tail call optimization.
3562   SmallVector<SDValue, 8> MemOpChains2;
3563   // Do not flag preceding copytoreg stuff together with the following stuff.
3564   InFlag = SDValue();
3565   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3566                                     MemOpChains2, dl);
3567   if (!MemOpChains2.empty())
3568     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3569
3570   // Store the return address to the appropriate stack slot.
3571   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3572                                         isPPC64, isDarwinABI, dl);
3573
3574   // Emit callseq_end just before tailcall node.
3575   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3576                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3577   InFlag = Chain.getValue(1);
3578 }
3579
3580 static
3581 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3582                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3583                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3584                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3585                      const PPCSubtarget &Subtarget) {
3586
3587   bool isPPC64 = Subtarget.isPPC64();
3588   bool isSVR4ABI = Subtarget.isSVR4ABI();
3589   bool isELFv2ABI = Subtarget.isELFv2ABI();
3590
3591   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3592   NodeTys.push_back(MVT::Other);   // Returns a chain
3593   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3594
3595   unsigned CallOpc = PPCISD::CALL;
3596
3597   bool needIndirectCall = true;
3598   if (!isSVR4ABI || !isPPC64)
3599     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3600       // If this is an absolute destination address, use the munged value.
3601       Callee = SDValue(Dest, 0);
3602       needIndirectCall = false;
3603     }
3604
3605   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3606     unsigned OpFlags = 0;
3607     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3608          (Subtarget.getTargetTriple().isMacOSX() &&
3609           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3610          (G->getGlobal()->isDeclaration() ||
3611           G->getGlobal()->isWeakForLinker())) ||
3612         (Subtarget.isTargetELF() && !isPPC64 &&
3613          !G->getGlobal()->hasLocalLinkage() &&
3614          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3615       // PC-relative references to external symbols should go through $stub,
3616       // unless we're building with the leopard linker or later, which
3617       // automatically synthesizes these stubs.
3618       OpFlags = PPCII::MO_PLT_OR_STUB;
3619     }
3620
3621     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3622     // every direct call is) turn it into a TargetGlobalAddress /
3623     // TargetExternalSymbol node so that legalize doesn't hack it.
3624     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3625                                         Callee.getValueType(), 0, OpFlags);
3626     needIndirectCall = false;
3627   }
3628
3629   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3630     unsigned char OpFlags = 0;
3631
3632     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3633          (Subtarget.getTargetTriple().isMacOSX() &&
3634           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3635         (Subtarget.isTargetELF() && !isPPC64 &&
3636          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3637       // PC-relative references to external symbols should go through $stub,
3638       // unless we're building with the leopard linker or later, which
3639       // automatically synthesizes these stubs.
3640       OpFlags = PPCII::MO_PLT_OR_STUB;
3641     }
3642
3643     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3644                                          OpFlags);
3645     needIndirectCall = false;
3646   }
3647
3648   if (needIndirectCall) {
3649     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3650     // to do the call, we can't use PPCISD::CALL.
3651     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3652
3653     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3654       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3655       // entry point, but to the function descriptor (the function entry point
3656       // address is part of the function descriptor though).
3657       // The function descriptor is a three doubleword structure with the
3658       // following fields: function entry point, TOC base address and
3659       // environment pointer.
3660       // Thus for a call through a function pointer, the following actions need
3661       // to be performed:
3662       //   1. Save the TOC of the caller in the TOC save area of its stack
3663       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3664       //   2. Load the address of the function entry point from the function
3665       //      descriptor.
3666       //   3. Load the TOC of the callee from the function descriptor into r2.
3667       //   4. Load the environment pointer from the function descriptor into
3668       //      r11.
3669       //   5. Branch to the function entry point address.
3670       //   6. On return of the callee, the TOC of the caller needs to be
3671       //      restored (this is done in FinishCall()).
3672       //
3673       // All those operations are flagged together to ensure that no other
3674       // operations can be scheduled in between. E.g. without flagging the
3675       // operations together, a TOC access in the caller could be scheduled
3676       // between the load of the callee TOC and the branch to the callee, which
3677       // results in the TOC access going through the TOC of the callee instead
3678       // of going through the TOC of the caller, which leads to incorrect code.
3679
3680       // Load the address of the function entry point from the function
3681       // descriptor.
3682       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3683       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3684                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3685       Chain = LoadFuncPtr.getValue(1);
3686       InFlag = LoadFuncPtr.getValue(2);
3687
3688       // Load environment pointer into r11.
3689       // Offset of the environment pointer within the function descriptor.
3690       SDValue PtrOff = DAG.getIntPtrConstant(16);
3691
3692       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3693       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3694                                        InFlag);
3695       Chain = LoadEnvPtr.getValue(1);
3696       InFlag = LoadEnvPtr.getValue(2);
3697
3698       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3699                                         InFlag);
3700       Chain = EnvVal.getValue(0);
3701       InFlag = EnvVal.getValue(1);
3702
3703       // Load TOC of the callee into r2. We are using a target-specific load
3704       // with r2 hard coded, because the result of a target-independent load
3705       // would never go directly into r2, since r2 is a reserved register (which
3706       // prevents the register allocator from allocating it), resulting in an
3707       // additional register being allocated and an unnecessary move instruction
3708       // being generated.
3709       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3710       SDValue TOCOff = DAG.getIntPtrConstant(8);
3711       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3712       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3713                                        AddTOC, InFlag);
3714       Chain = LoadTOCPtr.getValue(0);
3715       InFlag = LoadTOCPtr.getValue(1);
3716
3717       MTCTROps[0] = Chain;
3718       MTCTROps[1] = LoadFuncPtr;
3719       MTCTROps[2] = InFlag;
3720     }
3721
3722     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3723                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3724     InFlag = Chain.getValue(1);
3725
3726     NodeTys.clear();
3727     NodeTys.push_back(MVT::Other);
3728     NodeTys.push_back(MVT::Glue);
3729     Ops.push_back(Chain);
3730     CallOpc = PPCISD::BCTRL;
3731     Callee.setNode(nullptr);
3732     // Add use of X11 (holding environment pointer)
3733     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3734       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3735     // Add CTR register as callee so a bctr can be emitted later.
3736     if (isTailCall)
3737       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3738   }
3739
3740   // If this is a direct call, pass the chain and the callee.
3741   if (Callee.getNode()) {
3742     Ops.push_back(Chain);
3743     Ops.push_back(Callee);
3744
3745     // If this is a call to __tls_get_addr, find the symbol whose address
3746     // is to be taken and add it to the list.  This will be used to 
3747     // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3748     // We find the symbol by walking the chain to the CopyFromReg, walking
3749     // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3750     // pulling the symbol from that node.
3751     if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3752       if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3753         assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3754         SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3755         SDValue TGTAddr = AddI->getOperand(1);
3756         assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3757                "Didn't find target global TLS address where we expected one");
3758         Ops.push_back(TGTAddr);
3759         CallOpc = PPCISD::CALL_TLS;
3760       }
3761   }
3762   // If this is a tail call add stack pointer delta.
3763   if (isTailCall)
3764     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3765
3766   // Add argument registers to the end of the list so that they are known live
3767   // into the call.
3768   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3769     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3770                                   RegsToPass[i].second.getValueType()));
3771
3772   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3773   if (Callee.getNode() && isELFv2ABI)
3774     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3775
3776   return CallOpc;
3777 }
3778
3779 static
3780 bool isLocalCall(const SDValue &Callee)
3781 {
3782   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3783     return !G->getGlobal()->isDeclaration() &&
3784            !G->getGlobal()->isWeakForLinker();
3785   return false;
3786 }
3787
3788 SDValue
3789 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3790                                    CallingConv::ID CallConv, bool isVarArg,
3791                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3792                                    SDLoc dl, SelectionDAG &DAG,
3793                                    SmallVectorImpl<SDValue> &InVals) const {
3794
3795   SmallVector<CCValAssign, 16> RVLocs;
3796   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3797                     *DAG.getContext());
3798   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3799
3800   // Copy all of the result registers out of their specified physreg.
3801   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3802     CCValAssign &VA = RVLocs[i];
3803     assert(VA.isRegLoc() && "Can only return in registers!");
3804
3805     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3806                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3807     Chain = Val.getValue(1);
3808     InFlag = Val.getValue(2);
3809
3810     switch (VA.getLocInfo()) {
3811     default: llvm_unreachable("Unknown loc info!");
3812     case CCValAssign::Full: break;
3813     case CCValAssign::AExt:
3814       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3815       break;
3816     case CCValAssign::ZExt:
3817       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3818                         DAG.getValueType(VA.getValVT()));
3819       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3820       break;
3821     case CCValAssign::SExt:
3822       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3823                         DAG.getValueType(VA.getValVT()));
3824       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3825       break;
3826     }
3827
3828     InVals.push_back(Val);
3829   }
3830
3831   return Chain;
3832 }
3833
3834 SDValue
3835 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3836                               bool isTailCall, bool isVarArg,
3837                               SelectionDAG &DAG,
3838                               SmallVector<std::pair<unsigned, SDValue>, 8>
3839                                 &RegsToPass,
3840                               SDValue InFlag, SDValue Chain,
3841                               SDValue &Callee,
3842                               int SPDiff, unsigned NumBytes,
3843                               const SmallVectorImpl<ISD::InputArg> &Ins,
3844                               SmallVectorImpl<SDValue> &InVals) const {
3845
3846   bool isELFv2ABI = Subtarget.isELFv2ABI();
3847   std::vector<EVT> NodeTys;
3848   SmallVector<SDValue, 8> Ops;
3849   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3850                                  isTailCall, RegsToPass, Ops, NodeTys,
3851                                  Subtarget);
3852
3853   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3854   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3855     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3856
3857   // When performing tail call optimization the callee pops its arguments off
3858   // the stack. Account for this here so these bytes can be pushed back on in
3859   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3860   int BytesCalleePops =
3861     (CallConv == CallingConv::Fast &&
3862      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3863
3864   // Add a register mask operand representing the call-preserved registers.
3865   const TargetRegisterInfo *TRI =
3866       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3867   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3868   assert(Mask && "Missing call preserved mask for calling convention");
3869   Ops.push_back(DAG.getRegisterMask(Mask));
3870
3871   if (InFlag.getNode())
3872     Ops.push_back(InFlag);
3873
3874   // Emit tail call.
3875   if (isTailCall) {
3876     assert(((Callee.getOpcode() == ISD::Register &&
3877              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3878             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3879             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3880             isa<ConstantSDNode>(Callee)) &&
3881     "Expecting an global address, external symbol, absolute value or register");
3882
3883     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3884   }
3885
3886   // Add a NOP immediately after the branch instruction when using the 64-bit
3887   // SVR4 ABI. At link time, if caller and callee are in a different module and
3888   // thus have a different TOC, the call will be replaced with a call to a stub
3889   // function which saves the current TOC, loads the TOC of the callee and
3890   // branches to the callee. The NOP will be replaced with a load instruction
3891   // which restores the TOC of the caller from the TOC save slot of the current
3892   // stack frame. If caller and callee belong to the same module (and have the
3893   // same TOC), the NOP will remain unchanged.
3894
3895   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3896     if (CallOpc == PPCISD::BCTRL) {
3897       // This is a call through a function pointer.
3898       // Restore the caller TOC from the save area into R2.
3899       // See PrepareCall() for more information about calls through function
3900       // pointers in the 64-bit SVR4 ABI.
3901       // We are using a target-specific load with r2 hard coded, because the
3902       // result of a target-independent load would never go directly into r2,
3903       // since r2 is a reserved register (which prevents the register allocator
3904       // from allocating it), resulting in an additional register being
3905       // allocated and an unnecessary move instruction being generated.
3906       CallOpc = PPCISD::BCTRL_LOAD_TOC;
3907
3908       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3909       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3910       unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3911       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3912       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3913
3914       // The address needs to go after the chain input but before the flag (or
3915       // any other variadic arguments).
3916       Ops.insert(std::next(Ops.begin()), AddTOC);
3917     } else if ((CallOpc == PPCISD::CALL) &&
3918                (!isLocalCall(Callee) ||
3919                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3920       // Otherwise insert NOP for non-local calls.
3921       CallOpc = PPCISD::CALL_NOP;
3922     } else if (CallOpc == PPCISD::CALL_TLS)
3923       // For 64-bit SVR4, TLS calls are always non-local.
3924       CallOpc = PPCISD::CALL_NOP_TLS;
3925   }
3926
3927   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3928   InFlag = Chain.getValue(1);
3929
3930   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3931                              DAG.getIntPtrConstant(BytesCalleePops, true),
3932                              InFlag, dl);
3933   if (!Ins.empty())
3934     InFlag = Chain.getValue(1);
3935
3936   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3937                          Ins, dl, DAG, InVals);
3938 }
3939
3940 SDValue
3941 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3942                              SmallVectorImpl<SDValue> &InVals) const {
3943   SelectionDAG &DAG                     = CLI.DAG;
3944   SDLoc &dl                             = CLI.DL;
3945   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3946   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3947   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3948   SDValue Chain                         = CLI.Chain;
3949   SDValue Callee                        = CLI.Callee;
3950   bool &isTailCall                      = CLI.IsTailCall;
3951   CallingConv::ID CallConv              = CLI.CallConv;
3952   bool isVarArg                         = CLI.IsVarArg;
3953
3954   if (isTailCall)
3955     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3956                                                    Ins, DAG);
3957
3958   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3959     report_fatal_error("failed to perform tail call elimination on a call "
3960                        "site marked musttail");
3961
3962   if (Subtarget.isSVR4ABI()) {
3963     if (Subtarget.isPPC64())
3964       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3965                               isTailCall, Outs, OutVals, Ins,
3966                               dl, DAG, InVals);
3967     else
3968       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3969                               isTailCall, Outs, OutVals, Ins,
3970                               dl, DAG, InVals);
3971   }
3972
3973   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3974                           isTailCall, Outs, OutVals, Ins,
3975                           dl, DAG, InVals);
3976 }
3977
3978 SDValue
3979 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3980                                     CallingConv::ID CallConv, bool isVarArg,
3981                                     bool isTailCall,
3982                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3983                                     const SmallVectorImpl<SDValue> &OutVals,
3984                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3985                                     SDLoc dl, SelectionDAG &DAG,
3986                                     SmallVectorImpl<SDValue> &InVals) const {
3987   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3988   // of the 32-bit SVR4 ABI stack frame layout.
3989
3990   assert((CallConv == CallingConv::C ||
3991           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3992
3993   unsigned PtrByteSize = 4;
3994
3995   MachineFunction &MF = DAG.getMachineFunction();
3996
3997   // Mark this function as potentially containing a function that contains a
3998   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3999   // and restoring the callers stack pointer in this functions epilog. This is
4000   // done because by tail calling the called function might overwrite the value
4001   // in this function's (MF) stack pointer stack slot 0(SP).
4002   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4003       CallConv == CallingConv::Fast)
4004     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4005
4006   // Count how many bytes are to be pushed on the stack, including the linkage
4007   // area, parameter list area and the part of the local variable space which
4008   // contains copies of aggregates which are passed by value.
4009
4010   // Assign locations to all of the outgoing arguments.
4011   SmallVector<CCValAssign, 16> ArgLocs;
4012   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4013                  *DAG.getContext());
4014
4015   // Reserve space for the linkage area on the stack.
4016   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4017                        PtrByteSize);
4018
4019   if (isVarArg) {
4020     // Handle fixed and variable vector arguments differently.
4021     // Fixed vector arguments go into registers as long as registers are
4022     // available. Variable vector arguments always go into memory.
4023     unsigned NumArgs = Outs.size();
4024
4025     for (unsigned i = 0; i != NumArgs; ++i) {
4026       MVT ArgVT = Outs[i].VT;
4027       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4028       bool Result;
4029
4030       if (Outs[i].IsFixed) {
4031         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4032                                CCInfo);
4033       } else {
4034         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4035                                       ArgFlags, CCInfo);
4036       }
4037
4038       if (Result) {
4039 #ifndef NDEBUG
4040         errs() << "Call operand #" << i << " has unhandled type "
4041              << EVT(ArgVT).getEVTString() << "\n";
4042 #endif
4043         llvm_unreachable(nullptr);
4044       }
4045     }
4046   } else {
4047     // All arguments are treated the same.
4048     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4049   }
4050
4051   // Assign locations to all of the outgoing aggregate by value arguments.
4052   SmallVector<CCValAssign, 16> ByValArgLocs;
4053   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4054                       ByValArgLocs, *DAG.getContext());
4055
4056   // Reserve stack space for the allocations in CCInfo.
4057   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4058
4059   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4060
4061   // Size of the linkage area, parameter list area and the part of the local
4062   // space variable where copies of aggregates which are passed by value are
4063   // stored.
4064   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4065
4066   // Calculate by how many bytes the stack has to be adjusted in case of tail
4067   // call optimization.
4068   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4069
4070   // Adjust the stack pointer for the new arguments...
4071   // These operations are automatically eliminated by the prolog/epilog pass
4072   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4073                                dl);
4074   SDValue CallSeqStart = Chain;
4075
4076   // Load the return address and frame pointer so it can be moved somewhere else
4077   // later.
4078   SDValue LROp, FPOp;
4079   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4080                                        dl);
4081
4082   // Set up a copy of the stack pointer for use loading and storing any
4083   // arguments that may not fit in the registers available for argument
4084   // passing.
4085   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4086
4087   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4088   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4089   SmallVector<SDValue, 8> MemOpChains;
4090
4091   bool seenFloatArg = false;
4092   // Walk the register/memloc assignments, inserting copies/loads.
4093   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4094        i != e;
4095        ++i) {
4096     CCValAssign &VA = ArgLocs[i];
4097     SDValue Arg = OutVals[i];
4098     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4099
4100     if (Flags.isByVal()) {
4101       // Argument is an aggregate which is passed by value, thus we need to
4102       // create a copy of it in the local variable space of the current stack
4103       // frame (which is the stack frame of the caller) and pass the address of
4104       // this copy to the callee.
4105       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4106       CCValAssign &ByValVA = ByValArgLocs[j++];
4107       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4108
4109       // Memory reserved in the local variable space of the callers stack frame.
4110       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4111
4112       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4113       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4114
4115       // Create a copy of the argument in the local area of the current
4116       // stack frame.
4117       SDValue MemcpyCall =
4118         CreateCopyOfByValArgument(Arg, PtrOff,
4119                                   CallSeqStart.getNode()->getOperand(0),
4120                                   Flags, DAG, dl);
4121
4122       // This must go outside the CALLSEQ_START..END.
4123       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4124                            CallSeqStart.getNode()->getOperand(1),
4125                            SDLoc(MemcpyCall));
4126       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4127                              NewCallSeqStart.getNode());
4128       Chain = CallSeqStart = NewCallSeqStart;
4129
4130       // Pass the address of the aggregate copy on the stack either in a
4131       // physical register or in the parameter list area of the current stack
4132       // frame to the callee.
4133       Arg = PtrOff;
4134     }
4135
4136     if (VA.isRegLoc()) {
4137       if (Arg.getValueType() == MVT::i1)
4138         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4139
4140       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4141       // Put argument in a physical register.
4142       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4143     } else {
4144       // Put argument in the parameter list area of the current stack frame.
4145       assert(VA.isMemLoc());
4146       unsigned LocMemOffset = VA.getLocMemOffset();
4147
4148       if (!isTailCall) {
4149         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4150         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4151
4152         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4153                                            MachinePointerInfo(),
4154                                            false, false, 0));
4155       } else {
4156         // Calculate and remember argument location.
4157         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4158                                  TailCallArguments);
4159       }
4160     }
4161   }
4162
4163   if (!MemOpChains.empty())
4164     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4165
4166   // Build a sequence of copy-to-reg nodes chained together with token chain
4167   // and flag operands which copy the outgoing args into the appropriate regs.
4168   SDValue InFlag;
4169   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4170     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4171                              RegsToPass[i].second, InFlag);
4172     InFlag = Chain.getValue(1);
4173   }
4174
4175   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4176   // registers.
4177   if (isVarArg) {
4178     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4179     SDValue Ops[] = { Chain, InFlag };
4180
4181     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4182                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4183
4184     InFlag = Chain.getValue(1);
4185   }
4186
4187   if (isTailCall)
4188     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4189                     false, TailCallArguments);
4190
4191   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4192                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4193                     Ins, InVals);
4194 }
4195
4196 // Copy an argument into memory, being careful to do this outside the
4197 // call sequence for the call to which the argument belongs.
4198 SDValue
4199 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4200                                               SDValue CallSeqStart,
4201                                               ISD::ArgFlagsTy Flags,
4202                                               SelectionDAG &DAG,
4203                                               SDLoc dl) const {
4204   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4205                         CallSeqStart.getNode()->getOperand(0),
4206                         Flags, DAG, dl);
4207   // The MEMCPY must go outside the CALLSEQ_START..END.
4208   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4209                              CallSeqStart.getNode()->getOperand(1),
4210                              SDLoc(MemcpyCall));
4211   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4212                          NewCallSeqStart.getNode());
4213   return NewCallSeqStart;
4214 }
4215
4216 SDValue
4217 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4218                                     CallingConv::ID CallConv, bool isVarArg,
4219                                     bool isTailCall,
4220                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4221                                     const SmallVectorImpl<SDValue> &OutVals,
4222                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4223                                     SDLoc dl, SelectionDAG &DAG,
4224                                     SmallVectorImpl<SDValue> &InVals) const {
4225
4226   bool isELFv2ABI = Subtarget.isELFv2ABI();
4227   bool isLittleEndian = Subtarget.isLittleEndian();
4228   unsigned NumOps = Outs.size();
4229
4230   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4231   unsigned PtrByteSize = 8;
4232
4233   MachineFunction &MF = DAG.getMachineFunction();
4234
4235   // Mark this function as potentially containing a function that contains a
4236   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4237   // and restoring the callers stack pointer in this functions epilog. This is
4238   // done because by tail calling the called function might overwrite the value
4239   // in this function's (MF) stack pointer stack slot 0(SP).
4240   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4241       CallConv == CallingConv::Fast)
4242     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4243
4244   // Count how many bytes are to be pushed on the stack, including the linkage
4245   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4246   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4247   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4248   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4249                                                           isELFv2ABI);
4250   unsigned NumBytes = LinkageSize;
4251
4252   // Add up all the space actually used.
4253   for (unsigned i = 0; i != NumOps; ++i) {
4254     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4255     EVT ArgVT = Outs[i].VT;
4256     EVT OrigVT = Outs[i].ArgVT;
4257
4258     /* Respect alignment of argument on the stack.  */
4259     unsigned Align =
4260       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4261     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4262
4263     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4264     if (Flags.isInConsecutiveRegsLast())
4265       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4266   }
4267
4268   unsigned NumBytesActuallyUsed = NumBytes;
4269
4270   // The prolog code of the callee may store up to 8 GPR argument registers to
4271   // the stack, allowing va_start to index over them in memory if its varargs.
4272   // Because we cannot tell if this is needed on the caller side, we have to
4273   // conservatively assume that it is needed.  As such, make sure we have at
4274   // least enough stack space for the caller to store the 8 GPRs.
4275   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4276   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4277
4278   // Tail call needs the stack to be aligned.
4279   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4280       CallConv == CallingConv::Fast)
4281     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4282
4283   // Calculate by how many bytes the stack has to be adjusted in case of tail
4284   // call optimization.
4285   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4286
4287   // To protect arguments on the stack from being clobbered in a tail call,
4288   // force all the loads to happen before doing any other lowering.
4289   if (isTailCall)
4290     Chain = DAG.getStackArgumentTokenFactor(Chain);
4291
4292   // Adjust the stack pointer for the new arguments...
4293   // These operations are automatically eliminated by the prolog/epilog pass
4294   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4295                                dl);
4296   SDValue CallSeqStart = Chain;
4297
4298   // Load the return address and frame pointer so it can be move somewhere else
4299   // later.
4300   SDValue LROp, FPOp;
4301   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4302                                        dl);
4303
4304   // Set up a copy of the stack pointer for use loading and storing any
4305   // arguments that may not fit in the registers available for argument
4306   // passing.
4307   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4308
4309   // Figure out which arguments are going to go in registers, and which in
4310   // memory.  Also, if this is a vararg function, floating point operations
4311   // must be stored to our stack, and loaded into integer regs as well, if
4312   // any integer regs are available for argument passing.
4313   unsigned ArgOffset = LinkageSize;
4314   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4315
4316   static const MCPhysReg GPR[] = {
4317     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4318     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4319   };
4320   static const MCPhysReg *FPR = GetFPR();
4321
4322   static const MCPhysReg VR[] = {
4323     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4324     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4325   };
4326   static const MCPhysReg VSRH[] = {
4327     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4328     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4329   };
4330
4331   const unsigned NumGPRs = array_lengthof(GPR);
4332   const unsigned NumFPRs = 13;
4333   const unsigned NumVRs  = array_lengthof(VR);
4334
4335   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4336   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4337
4338   SmallVector<SDValue, 8> MemOpChains;
4339   for (unsigned i = 0; i != NumOps; ++i) {
4340     SDValue Arg = OutVals[i];
4341     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4342     EVT ArgVT = Outs[i].VT;
4343     EVT OrigVT = Outs[i].ArgVT;
4344
4345     /* Respect alignment of argument on the stack.  */
4346     unsigned Align =
4347       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4348     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4349
4350     /* Compute GPR index associated with argument offset.  */
4351     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4352     GPR_idx = std::min(GPR_idx, NumGPRs);
4353
4354     // PtrOff will be used to store the current argument to the stack if a
4355     // register cannot be found for it.
4356     SDValue PtrOff;
4357
4358     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4359
4360     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4361
4362     // Promote integers to 64-bit values.
4363     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4364       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4365       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4366       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4367     }
4368
4369     // FIXME memcpy is used way more than necessary.  Correctness first.
4370     // Note: "by value" is code for passing a structure by value, not
4371     // basic types.
4372     if (Flags.isByVal()) {
4373       // Note: Size includes alignment padding, so
4374       //   struct x { short a; char b; }
4375       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4376       // These are the proper values we need for right-justifying the
4377       // aggregate in a parameter register.
4378       unsigned Size = Flags.getByValSize();
4379
4380       // An empty aggregate parameter takes up no storage and no
4381       // registers.
4382       if (Size == 0)
4383         continue;
4384
4385       // All aggregates smaller than 8 bytes must be passed right-justified.
4386       if (Size==1 || Size==2 || Size==4) {
4387         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4388         if (GPR_idx != NumGPRs) {
4389           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4390                                         MachinePointerInfo(), VT,
4391                                         false, false, false, 0);
4392           MemOpChains.push_back(Load.getValue(1));
4393           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4394
4395           ArgOffset += PtrByteSize;
4396           continue;
4397         }
4398       }
4399
4400       if (GPR_idx == NumGPRs && Size < 8) {
4401         SDValue AddPtr = PtrOff;
4402         if (!isLittleEndian) {
4403           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4404                                           PtrOff.getValueType());
4405           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4406         }
4407         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4408                                                           CallSeqStart,
4409                                                           Flags, DAG, dl);
4410         ArgOffset += PtrByteSize;
4411         continue;
4412       }
4413       // Copy entire object into memory.  There are cases where gcc-generated
4414       // code assumes it is there, even if it could be put entirely into
4415       // registers.  (This is not what the doc says.)
4416
4417       // FIXME: The above statement is likely due to a misunderstanding of the
4418       // documents.  All arguments must be copied into the parameter area BY
4419       // THE CALLEE in the event that the callee takes the address of any
4420       // formal argument.  That has not yet been implemented.  However, it is
4421       // reasonable to use the stack area as a staging area for the register
4422       // load.
4423
4424       // Skip this for small aggregates, as we will use the same slot for a
4425       // right-justified copy, below.
4426       if (Size >= 8)
4427         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4428                                                           CallSeqStart,
4429                                                           Flags, DAG, dl);
4430
4431       // When a register is available, pass a small aggregate right-justified.
4432       if (Size < 8 && GPR_idx != NumGPRs) {
4433         // The easiest way to get this right-justified in a register
4434         // is to copy the structure into the rightmost portion of a
4435         // local variable slot, then load the whole slot into the
4436         // register.
4437         // FIXME: The memcpy seems to produce pretty awful code for
4438         // small aggregates, particularly for packed ones.
4439         // FIXME: It would be preferable to use the slot in the
4440         // parameter save area instead of a new local variable.
4441         SDValue AddPtr = PtrOff;
4442         if (!isLittleEndian) {
4443           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4444           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4445         }
4446         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4447                                                           CallSeqStart,
4448                                                           Flags, DAG, dl);
4449
4450         // Load the slot into the register.
4451         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4452                                    MachinePointerInfo(),
4453                                    false, false, false, 0);
4454         MemOpChains.push_back(Load.getValue(1));
4455         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4456
4457         // Done with this argument.
4458         ArgOffset += PtrByteSize;
4459         continue;
4460       }
4461
4462       // For aggregates larger than PtrByteSize, copy the pieces of the
4463       // object that fit into registers from the parameter save area.
4464       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4465         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4466         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4467         if (GPR_idx != NumGPRs) {
4468           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4469                                      MachinePointerInfo(),
4470                                      false, false, false, 0);
4471           MemOpChains.push_back(Load.getValue(1));
4472           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4473           ArgOffset += PtrByteSize;
4474         } else {
4475           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4476           break;
4477         }
4478       }
4479       continue;
4480     }
4481
4482     switch (Arg.getSimpleValueType().SimpleTy) {
4483     default: llvm_unreachable("Unexpected ValueType for argument!");
4484     case MVT::i1:
4485     case MVT::i32:
4486     case MVT::i64:
4487       // These can be scalar arguments or elements of an integer array type
4488       // passed directly.  Clang may use those instead of "byval" aggregate
4489       // types to avoid forcing arguments to memory unnecessarily.
4490       if (GPR_idx != NumGPRs) {
4491         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4492       } else {
4493         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4494                          true, isTailCall, false, MemOpChains,
4495                          TailCallArguments, dl);
4496       }
4497       ArgOffset += PtrByteSize;
4498       break;
4499     case MVT::f32:
4500     case MVT::f64: {
4501       // These can be scalar arguments or elements of a float array type
4502       // passed directly.  The latter are used to implement ELFv2 homogenous
4503       // float aggregates.
4504
4505       // Named arguments go into FPRs first, and once they overflow, the
4506       // remaining arguments go into GPRs and then the parameter save area.
4507       // Unnamed arguments for vararg functions always go to GPRs and
4508       // then the parameter save area.  For now, put all arguments to vararg
4509       // routines always in both locations (FPR *and* GPR or stack slot).
4510       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4511
4512       // First load the argument into the next available FPR.
4513       if (FPR_idx != NumFPRs)
4514         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4515
4516       // Next, load the argument into GPR or stack slot if needed.
4517       if (!NeedGPROrStack)
4518         ;
4519       else if (GPR_idx != NumGPRs) {
4520         // In the non-vararg case, this can only ever happen in the
4521         // presence of f32 array types, since otherwise we never run
4522         // out of FPRs before running out of GPRs.
4523         SDValue ArgVal;
4524
4525         // Double values are always passed in a single GPR.
4526         if (Arg.getValueType() != MVT::f32) {
4527           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4528
4529         // Non-array float values are extended and passed in a GPR.
4530         } else if (!Flags.isInConsecutiveRegs()) {
4531           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4532           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4533
4534         // If we have an array of floats, we collect every odd element
4535         // together with its predecessor into one GPR.
4536         } else if (ArgOffset % PtrByteSize != 0) {
4537           SDValue Lo, Hi;
4538           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4539           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4540           if (!isLittleEndian)
4541             std::swap(Lo, Hi);
4542           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4543
4544         // The final element, if even, goes into the first half of a GPR.
4545         } else if (Flags.isInConsecutiveRegsLast()) {
4546           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4547           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4548           if (!isLittleEndian)
4549             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4550                                  DAG.getConstant(32, MVT::i32));
4551
4552         // Non-final even elements are skipped; they will be handled
4553         // together the with subsequent argument on the next go-around.
4554         } else
4555           ArgVal = SDValue();
4556
4557         if (ArgVal.getNode())
4558           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4559       } else {
4560         // Single-precision floating-point values are mapped to the
4561         // second (rightmost) word of the stack doubleword.
4562         if (Arg.getValueType() == MVT::f32 &&
4563             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4564           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4565           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4566         }
4567
4568         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4569                          true, isTailCall, false, MemOpChains,
4570                          TailCallArguments, dl);
4571       }
4572       // When passing an array of floats, the array occupies consecutive
4573       // space in the argument area; only round up to the next doubleword
4574       // at the end of the array.  Otherwise, each float takes 8 bytes.
4575       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4576                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4577       if (Flags.isInConsecutiveRegsLast())
4578         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4579       break;
4580     }
4581     case MVT::v4f32:
4582     case MVT::v4i32:
4583     case MVT::v8i16:
4584     case MVT::v16i8:
4585     case MVT::v2f64:
4586     case MVT::v2i64:
4587       // These can be scalar arguments or elements of a vector array type
4588       // passed directly.  The latter are used to implement ELFv2 homogenous
4589       // vector aggregates.
4590
4591       // For a varargs call, named arguments go into VRs or on the stack as
4592       // usual; unnamed arguments always go to the stack or the corresponding
4593       // GPRs when within range.  For now, we always put the value in both
4594       // locations (or even all three).
4595       if (isVarArg) {
4596         // We could elide this store in the case where the object fits
4597         // entirely in R registers.  Maybe later.
4598         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4599                                      MachinePointerInfo(), false, false, 0);
4600         MemOpChains.push_back(Store);
4601         if (VR_idx != NumVRs) {
4602           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4603                                      MachinePointerInfo(),
4604                                      false, false, false, 0);
4605           MemOpChains.push_back(Load.getValue(1));
4606
4607           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4608                            Arg.getSimpleValueType() == MVT::v2i64) ?
4609                           VSRH[VR_idx] : VR[VR_idx];
4610           ++VR_idx;
4611
4612           RegsToPass.push_back(std::make_pair(VReg, Load));
4613         }
4614         ArgOffset += 16;
4615         for (unsigned i=0; i<16; i+=PtrByteSize) {
4616           if (GPR_idx == NumGPRs)
4617             break;
4618           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4619                                   DAG.getConstant(i, PtrVT));
4620           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4621                                      false, false, false, 0);
4622           MemOpChains.push_back(Load.getValue(1));
4623           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4624         }
4625         break;
4626       }
4627
4628       // Non-varargs Altivec params go into VRs or on the stack.
4629       if (VR_idx != NumVRs) {
4630         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4631                          Arg.getSimpleValueType() == MVT::v2i64) ?
4632                         VSRH[VR_idx] : VR[VR_idx];
4633         ++VR_idx;
4634
4635         RegsToPass.push_back(std::make_pair(VReg, Arg));
4636       } else {
4637         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4638                          true, isTailCall, true, MemOpChains,
4639                          TailCallArguments, dl);
4640       }
4641       ArgOffset += 16;
4642       break;
4643     }
4644   }
4645
4646   assert(NumBytesActuallyUsed == ArgOffset);
4647   (void)NumBytesActuallyUsed;
4648
4649   if (!MemOpChains.empty())
4650     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4651
4652   // Check if this is an indirect call (MTCTR/BCTRL).
4653   // See PrepareCall() for more information about calls through function
4654   // pointers in the 64-bit SVR4 ABI.
4655   if (!isTailCall &&
4656       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4657       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4658     // Load r2 into a virtual register and store it to the TOC save area.
4659     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4660     // TOC save area offset.
4661     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4662     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4663     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4664     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4665                          false, false, 0);
4666     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4667     // This does not mean the MTCTR instruction must use R12; it's easier
4668     // to model this as an extra parameter, so do that.
4669     if (isELFv2ABI)
4670       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4671   }
4672
4673   // Build a sequence of copy-to-reg nodes chained together with token chain
4674   // and flag operands which copy the outgoing args into the appropriate regs.
4675   SDValue InFlag;
4676   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4677     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4678                              RegsToPass[i].second, InFlag);
4679     InFlag = Chain.getValue(1);
4680   }
4681
4682   if (isTailCall)
4683     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4684                     FPOp, true, TailCallArguments);
4685
4686   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4687                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4688                     Ins, InVals);
4689 }
4690
4691 SDValue
4692 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4693                                     CallingConv::ID CallConv, bool isVarArg,
4694                                     bool isTailCall,
4695                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4696                                     const SmallVectorImpl<SDValue> &OutVals,
4697                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4698                                     SDLoc dl, SelectionDAG &DAG,
4699                                     SmallVectorImpl<SDValue> &InVals) const {
4700
4701   unsigned NumOps = Outs.size();
4702
4703   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4704   bool isPPC64 = PtrVT == MVT::i64;
4705   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4706
4707   MachineFunction &MF = DAG.getMachineFunction();
4708
4709   // Mark this function as potentially containing a function that contains a
4710   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4711   // and restoring the callers stack pointer in this functions epilog. This is
4712   // done because by tail calling the called function might overwrite the value
4713   // in this function's (MF) stack pointer stack slot 0(SP).
4714   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4715       CallConv == CallingConv::Fast)
4716     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4717
4718   // Count how many bytes are to be pushed on the stack, including the linkage
4719   // area, and parameter passing area.  We start with 24/48 bytes, which is
4720   // prereserved space for [SP][CR][LR][3 x unused].
4721   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4722                                                           false);
4723   unsigned NumBytes = LinkageSize;
4724
4725   // Add up all the space actually used.
4726   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4727   // they all go in registers, but we must reserve stack space for them for
4728   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4729   // assigned stack space in order, with padding so Altivec parameters are
4730   // 16-byte aligned.
4731   unsigned nAltivecParamsAtEnd = 0;
4732   for (unsigned i = 0; i != NumOps; ++i) {
4733     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4734     EVT ArgVT = Outs[i].VT;
4735     // Varargs Altivec parameters are padded to a 16 byte boundary.
4736     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4737         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4738         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4739       if (!isVarArg && !isPPC64) {
4740         // Non-varargs Altivec parameters go after all the non-Altivec
4741         // parameters; handle those later so we know how much padding we need.
4742         nAltivecParamsAtEnd++;
4743         continue;
4744       }
4745       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4746       NumBytes = ((NumBytes+15)/16)*16;
4747     }
4748     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4749   }
4750
4751   // Allow for Altivec parameters at the end, if needed.
4752   if (nAltivecParamsAtEnd) {
4753     NumBytes = ((NumBytes+15)/16)*16;
4754     NumBytes += 16*nAltivecParamsAtEnd;
4755   }
4756
4757   // The prolog code of the callee may store up to 8 GPR argument registers to
4758   // the stack, allowing va_start to index over them in memory if its varargs.
4759   // Because we cannot tell if this is needed on the caller side, we have to
4760   // conservatively assume that it is needed.  As such, make sure we have at
4761   // least enough stack space for the caller to store the 8 GPRs.
4762   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4763
4764   // Tail call needs the stack to be aligned.
4765   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4766       CallConv == CallingConv::Fast)
4767     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4768
4769   // Calculate by how many bytes the stack has to be adjusted in case of tail
4770   // call optimization.
4771   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4772
4773   // To protect arguments on the stack from being clobbered in a tail call,
4774   // force all the loads to happen before doing any other lowering.
4775   if (isTailCall)
4776     Chain = DAG.getStackArgumentTokenFactor(Chain);
4777
4778   // Adjust the stack pointer for the new arguments...
4779   // These operations are automatically eliminated by the prolog/epilog pass
4780   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4781                                dl);
4782   SDValue CallSeqStart = Chain;
4783
4784   // Load the return address and frame pointer so it can be move somewhere else
4785   // later.
4786   SDValue LROp, FPOp;
4787   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4788                                        dl);
4789
4790   // Set up a copy of the stack pointer for use loading and storing any
4791   // arguments that may not fit in the registers available for argument
4792   // passing.
4793   SDValue StackPtr;
4794   if (isPPC64)
4795     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4796   else
4797     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4798
4799   // Figure out which arguments are going to go in registers, and which in
4800   // memory.  Also, if this is a vararg function, floating point operations
4801   // must be stored to our stack, and loaded into integer regs as well, if
4802   // any integer regs are available for argument passing.
4803   unsigned ArgOffset = LinkageSize;
4804   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4805
4806   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4807     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4808     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4809   };
4810   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4811     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4812     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4813   };
4814   static const MCPhysReg *FPR = GetFPR();
4815
4816   static const MCPhysReg VR[] = {
4817     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4818     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4819   };
4820   const unsigned NumGPRs = array_lengthof(GPR_32);
4821   const unsigned NumFPRs = 13;
4822   const unsigned NumVRs  = array_lengthof(VR);
4823
4824   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4825
4826   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4827   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4828
4829   SmallVector<SDValue, 8> MemOpChains;
4830   for (unsigned i = 0; i != NumOps; ++i) {
4831     SDValue Arg = OutVals[i];
4832     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4833
4834     // PtrOff will be used to store the current argument to the stack if a
4835     // register cannot be found for it.
4836     SDValue PtrOff;
4837
4838     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4839
4840     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4841
4842     // On PPC64, promote integers to 64-bit values.
4843     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4844       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4845       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4846       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4847     }
4848
4849     // FIXME memcpy is used way more than necessary.  Correctness first.
4850     // Note: "by value" is code for passing a structure by value, not
4851     // basic types.
4852     if (Flags.isByVal()) {
4853       unsigned Size = Flags.getByValSize();
4854       // Very small objects are passed right-justified.  Everything else is
4855       // passed left-justified.
4856       if (Size==1 || Size==2) {
4857         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4858         if (GPR_idx != NumGPRs) {
4859           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4860                                         MachinePointerInfo(), VT,
4861                                         false, false, false, 0);
4862           MemOpChains.push_back(Load.getValue(1));
4863           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4864
4865           ArgOffset += PtrByteSize;
4866         } else {
4867           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4868                                           PtrOff.getValueType());
4869           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4870           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4871                                                             CallSeqStart,
4872                                                             Flags, DAG, dl);
4873           ArgOffset += PtrByteSize;
4874         }
4875         continue;
4876       }
4877       // Copy entire object into memory.  There are cases where gcc-generated
4878       // code assumes it is there, even if it could be put entirely into
4879       // registers.  (This is not what the doc says.)
4880       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4881                                                         CallSeqStart,
4882                                                         Flags, DAG, dl);
4883
4884       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4885       // copy the pieces of the object that fit into registers from the
4886       // parameter save area.
4887       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4888         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4889         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4890         if (GPR_idx != NumGPRs) {
4891           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4892                                      MachinePointerInfo(),
4893                                      false, false, false, 0);
4894           MemOpChains.push_back(Load.getValue(1));
4895           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4896           ArgOffset += PtrByteSize;
4897         } else {
4898           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4899           break;
4900         }
4901       }
4902       continue;
4903     }
4904
4905     switch (Arg.getSimpleValueType().SimpleTy) {
4906     default: llvm_unreachable("Unexpected ValueType for argument!");
4907     case MVT::i1:
4908     case MVT::i32:
4909     case MVT::i64:
4910       if (GPR_idx != NumGPRs) {
4911         if (Arg.getValueType() == MVT::i1)
4912           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4913
4914         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4915       } else {
4916         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4917                          isPPC64, isTailCall, false, MemOpChains,
4918                          TailCallArguments, dl);
4919       }
4920       ArgOffset += PtrByteSize;
4921       break;
4922     case MVT::f32:
4923     case MVT::f64:
4924       if (FPR_idx != NumFPRs) {
4925         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4926
4927         if (isVarArg) {
4928           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4929                                        MachinePointerInfo(), false, false, 0);
4930           MemOpChains.push_back(Store);
4931
4932           // Float varargs are always shadowed in available integer registers
4933           if (GPR_idx != NumGPRs) {
4934             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4935                                        MachinePointerInfo(), false, false,
4936                                        false, 0);
4937             MemOpChains.push_back(Load.getValue(1));
4938             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4939           }
4940           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4941             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4942             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4943             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4944                                        MachinePointerInfo(),
4945                                        false, false, false, 0);
4946             MemOpChains.push_back(Load.getValue(1));
4947             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4948           }
4949         } else {
4950           // If we have any FPRs remaining, we may also have GPRs remaining.
4951           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4952           // GPRs.
4953           if (GPR_idx != NumGPRs)
4954             ++GPR_idx;
4955           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4956               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4957             ++GPR_idx;
4958         }
4959       } else
4960         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4961                          isPPC64, isTailCall, false, MemOpChains,
4962                          TailCallArguments, dl);
4963       if (isPPC64)
4964         ArgOffset += 8;
4965       else
4966         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4967       break;
4968     case MVT::v4f32:
4969     case MVT::v4i32:
4970     case MVT::v8i16:
4971     case MVT::v16i8:
4972       if (isVarArg) {
4973         // These go aligned on the stack, or in the corresponding R registers
4974         // when within range.  The Darwin PPC ABI doc claims they also go in
4975         // V registers; in fact gcc does this only for arguments that are
4976         // prototyped, not for those that match the ...  We do it for all
4977         // arguments, seems to work.
4978         while (ArgOffset % 16 !=0) {
4979           ArgOffset += PtrByteSize;
4980           if (GPR_idx != NumGPRs)
4981             GPR_idx++;
4982         }
4983         // We could elide this store in the case where the object fits
4984         // entirely in R registers.  Maybe later.
4985         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4986                             DAG.getConstant(ArgOffset, PtrVT));
4987         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4988                                      MachinePointerInfo(), false, false, 0);
4989         MemOpChains.push_back(Store);
4990         if (VR_idx != NumVRs) {
4991           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4992                                      MachinePointerInfo(),
4993                                      false, false, false, 0);
4994           MemOpChains.push_back(Load.getValue(1));
4995           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4996         }
4997         ArgOffset += 16;
4998         for (unsigned i=0; i<16; i+=PtrByteSize) {
4999           if (GPR_idx == NumGPRs)
5000             break;
5001           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5002                                   DAG.getConstant(i, PtrVT));
5003           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5004                                      false, false, false, 0);
5005           MemOpChains.push_back(Load.getValue(1));
5006           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5007         }
5008         break;
5009       }
5010
5011       // Non-varargs Altivec params generally go in registers, but have
5012       // stack space allocated at the end.
5013       if (VR_idx != NumVRs) {
5014         // Doesn't have GPR space allocated.
5015         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5016       } else if (nAltivecParamsAtEnd==0) {
5017         // We are emitting Altivec params in order.
5018         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5019                          isPPC64, isTailCall, true, MemOpChains,
5020                          TailCallArguments, dl);
5021         ArgOffset += 16;
5022       }
5023       break;
5024     }
5025   }
5026   // If all Altivec parameters fit in registers, as they usually do,
5027   // they get stack space following the non-Altivec parameters.  We
5028   // don't track this here because nobody below needs it.
5029   // If there are more Altivec parameters than fit in registers emit
5030   // the stores here.
5031   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5032     unsigned j = 0;
5033     // Offset is aligned; skip 1st 12 params which go in V registers.
5034     ArgOffset = ((ArgOffset+15)/16)*16;
5035     ArgOffset += 12*16;
5036     for (unsigned i = 0; i != NumOps; ++i) {
5037       SDValue Arg = OutVals[i];
5038       EVT ArgType = Outs[i].VT;
5039       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5040           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5041         if (++j > NumVRs) {
5042           SDValue PtrOff;
5043           // We are emitting Altivec params in order.
5044           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5045                            isPPC64, isTailCall, true, MemOpChains,
5046                            TailCallArguments, dl);
5047           ArgOffset += 16;
5048         }
5049       }
5050     }
5051   }
5052
5053   if (!MemOpChains.empty())
5054     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5055
5056   // On Darwin, R12 must contain the address of an indirect callee.  This does
5057   // not mean the MTCTR instruction must use R12; it's easier to model this as
5058   // an extra parameter, so do that.
5059   if (!isTailCall &&
5060       !dyn_cast<GlobalAddressSDNode>(Callee) &&
5061       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5062       !isBLACompatibleAddress(Callee, DAG))
5063     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5064                                                    PPC::R12), Callee));
5065
5066   // Build a sequence of copy-to-reg nodes chained together with token chain
5067   // and flag operands which copy the outgoing args into the appropriate regs.
5068   SDValue InFlag;
5069   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5070     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5071                              RegsToPass[i].second, InFlag);
5072     InFlag = Chain.getValue(1);
5073   }
5074
5075   if (isTailCall)
5076     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5077                     FPOp, true, TailCallArguments);
5078
5079   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5080                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5081                     Ins, InVals);
5082 }
5083
5084 bool
5085 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5086                                   MachineFunction &MF, bool isVarArg,
5087                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5088                                   LLVMContext &Context) const {
5089   SmallVector<CCValAssign, 16> RVLocs;
5090   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5091   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5092 }
5093
5094 SDValue
5095 PPCTargetLowering::LowerReturn(SDValue Chain,
5096                                CallingConv::ID CallConv, bool isVarArg,
5097                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5098                                const SmallVectorImpl<SDValue> &OutVals,
5099                                SDLoc dl, SelectionDAG &DAG) const {
5100
5101   SmallVector<CCValAssign, 16> RVLocs;
5102   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5103                  *DAG.getContext());
5104   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5105
5106   SDValue Flag;
5107   SmallVector<SDValue, 4> RetOps(1, Chain);
5108
5109   // Copy the result values into the output registers.
5110   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5111     CCValAssign &VA = RVLocs[i];
5112     assert(VA.isRegLoc() && "Can only return in registers!");
5113
5114     SDValue Arg = OutVals[i];
5115
5116     switch (VA.getLocInfo()) {
5117     default: llvm_unreachable("Unknown loc info!");
5118     case CCValAssign::Full: break;
5119     case CCValAssign::AExt:
5120       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5121       break;
5122     case CCValAssign::ZExt:
5123       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5124       break;
5125     case CCValAssign::SExt:
5126       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5127       break;
5128     }
5129
5130     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5131     Flag = Chain.getValue(1);
5132     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5133   }
5134
5135   RetOps[0] = Chain;  // Update chain.
5136
5137   // Add the flag if we have it.
5138   if (Flag.getNode())
5139     RetOps.push_back(Flag);
5140
5141   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5142 }
5143
5144 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5145                                    const PPCSubtarget &Subtarget) const {
5146   // When we pop the dynamic allocation we need to restore the SP link.
5147   SDLoc dl(Op);
5148
5149   // Get the corect type for pointers.
5150   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5151
5152   // Construct the stack pointer operand.
5153   bool isPPC64 = Subtarget.isPPC64();
5154   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5155   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5156
5157   // Get the operands for the STACKRESTORE.
5158   SDValue Chain = Op.getOperand(0);
5159   SDValue SaveSP = Op.getOperand(1);
5160
5161   // Load the old link SP.
5162   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5163                                    MachinePointerInfo(),
5164                                    false, false, false, 0);
5165
5166   // Restore the stack pointer.
5167   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5168
5169   // Store the old link SP.
5170   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5171                       false, false, 0);
5172 }
5173
5174
5175
5176 SDValue
5177 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5178   MachineFunction &MF = DAG.getMachineFunction();
5179   bool isPPC64 = Subtarget.isPPC64();
5180   bool isDarwinABI = Subtarget.isDarwinABI();
5181   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5182
5183   // Get current frame pointer save index.  The users of this index will be
5184   // primarily DYNALLOC instructions.
5185   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5186   int RASI = FI->getReturnAddrSaveIndex();
5187
5188   // If the frame pointer save index hasn't been defined yet.
5189   if (!RASI) {
5190     // Find out what the fix offset of the frame pointer save area.
5191     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5192     // Allocate the frame index for frame pointer save area.
5193     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5194     // Save the result.
5195     FI->setReturnAddrSaveIndex(RASI);
5196   }
5197   return DAG.getFrameIndex(RASI, PtrVT);
5198 }
5199
5200 SDValue
5201 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5202   MachineFunction &MF = DAG.getMachineFunction();
5203   bool isPPC64 = Subtarget.isPPC64();
5204   bool isDarwinABI = Subtarget.isDarwinABI();
5205   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5206
5207   // Get current frame pointer save index.  The users of this index will be
5208   // primarily DYNALLOC instructions.
5209   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5210   int FPSI = FI->getFramePointerSaveIndex();
5211
5212   // If the frame pointer save index hasn't been defined yet.
5213   if (!FPSI) {
5214     // Find out what the fix offset of the frame pointer save area.
5215     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5216                                                            isDarwinABI);
5217
5218     // Allocate the frame index for frame pointer save area.
5219     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5220     // Save the result.
5221     FI->setFramePointerSaveIndex(FPSI);
5222   }
5223   return DAG.getFrameIndex(FPSI, PtrVT);
5224 }
5225
5226 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5227                                          SelectionDAG &DAG,
5228                                          const PPCSubtarget &Subtarget) const {
5229   // Get the inputs.
5230   SDValue Chain = Op.getOperand(0);
5231   SDValue Size  = Op.getOperand(1);
5232   SDLoc dl(Op);
5233
5234   // Get the corect type for pointers.
5235   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5236   // Negate the size.
5237   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5238                                   DAG.getConstant(0, PtrVT), Size);
5239   // Construct a node for the frame pointer save index.
5240   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5241   // Build a DYNALLOC node.
5242   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5243   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5244   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5245 }
5246
5247 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5248                                                SelectionDAG &DAG) const {
5249   SDLoc DL(Op);
5250   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5251                      DAG.getVTList(MVT::i32, MVT::Other),
5252                      Op.getOperand(0), Op.getOperand(1));
5253 }
5254
5255 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5256                                                 SelectionDAG &DAG) const {
5257   SDLoc DL(Op);
5258   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5259                      Op.getOperand(0), Op.getOperand(1));
5260 }
5261
5262 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5263   assert(Op.getValueType() == MVT::i1 &&
5264          "Custom lowering only for i1 loads");
5265
5266   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5267
5268   SDLoc dl(Op);
5269   LoadSDNode *LD = cast<LoadSDNode>(Op);
5270
5271   SDValue Chain = LD->getChain();
5272   SDValue BasePtr = LD->getBasePtr();
5273   MachineMemOperand *MMO = LD->getMemOperand();
5274
5275   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5276                                  BasePtr, MVT::i8, MMO);
5277   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5278
5279   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5280   return DAG.getMergeValues(Ops, dl);
5281 }
5282
5283 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5284   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5285          "Custom lowering only for i1 stores");
5286
5287   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5288
5289   SDLoc dl(Op);
5290   StoreSDNode *ST = cast<StoreSDNode>(Op);
5291
5292   SDValue Chain = ST->getChain();
5293   SDValue BasePtr = ST->getBasePtr();
5294   SDValue Value = ST->getValue();
5295   MachineMemOperand *MMO = ST->getMemOperand();
5296
5297   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5298   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5299 }
5300
5301 // FIXME: Remove this once the ANDI glue bug is fixed:
5302 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5303   assert(Op.getValueType() == MVT::i1 &&
5304          "Custom lowering only for i1 results");
5305
5306   SDLoc DL(Op);
5307   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5308                      Op.getOperand(0));
5309 }
5310
5311 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5312 /// possible.
5313 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5314   // Not FP? Not a fsel.
5315   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5316       !Op.getOperand(2).getValueType().isFloatingPoint())
5317     return Op;
5318
5319   // We might be able to do better than this under some circumstances, but in
5320   // general, fsel-based lowering of select is a finite-math-only optimization.
5321   // For more information, see section F.3 of the 2.06 ISA specification.
5322   if (!DAG.getTarget().Options.NoInfsFPMath ||
5323       !DAG.getTarget().Options.NoNaNsFPMath)
5324     return Op;
5325
5326   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5327
5328   EVT ResVT = Op.getValueType();
5329   EVT CmpVT = Op.getOperand(0).getValueType();
5330   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5331   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5332   SDLoc dl(Op);
5333
5334   // If the RHS of the comparison is a 0.0, we don't need to do the
5335   // subtraction at all.
5336   SDValue Sel1;
5337   if (isFloatingPointZero(RHS))
5338     switch (CC) {
5339     default: break;       // SETUO etc aren't handled by fsel.
5340     case ISD::SETNE:
5341       std::swap(TV, FV);
5342     case ISD::SETEQ:
5343       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5344         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5345       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5346       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5347         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5348       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5349                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5350     case ISD::SETULT:
5351     case ISD::SETLT:
5352       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5353     case ISD::SETOGE:
5354     case ISD::SETGE:
5355       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5356         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5357       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5358     case ISD::SETUGT:
5359     case ISD::SETGT:
5360       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5361     case ISD::SETOLE:
5362     case ISD::SETLE:
5363       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5364         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5365       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5366                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5367     }
5368
5369   SDValue Cmp;
5370   switch (CC) {
5371   default: break;       // SETUO etc aren't handled by fsel.
5372   case ISD::SETNE:
5373     std::swap(TV, FV);
5374   case ISD::SETEQ:
5375     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5376     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5377       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5378     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5379     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5380       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5381     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5382                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5383   case ISD::SETULT:
5384   case ISD::SETLT:
5385     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5386     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5387       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5388     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5389   case ISD::SETOGE:
5390   case ISD::SETGE:
5391     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5392     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5393       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5394     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5395   case ISD::SETUGT:
5396   case ISD::SETGT:
5397     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5398     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5399       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5400     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5401   case ISD::SETOLE:
5402   case ISD::SETLE:
5403     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5404     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5405       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5406     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5407   }
5408   return Op;
5409 }
5410
5411 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5412                                                SelectionDAG &DAG,
5413                                                SDLoc dl) const {
5414   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5415   SDValue Src = Op.getOperand(0);
5416   if (Src.getValueType() == MVT::f32)
5417     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5418
5419   SDValue Tmp;
5420   switch (Op.getSimpleValueType().SimpleTy) {
5421   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5422   case MVT::i32:
5423     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5424                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5425                                                    PPCISD::FCTIDZ),
5426                       dl, MVT::f64, Src);
5427     break;
5428   case MVT::i64:
5429     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5430            "i64 FP_TO_UINT is supported only with FPCVT");
5431     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5432                                                         PPCISD::FCTIDUZ,
5433                       dl, MVT::f64, Src);
5434     break;
5435   }
5436
5437   // Convert the FP value to an int value through memory.
5438   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5439     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5440   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5441   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5442   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5443
5444   // Emit a store to the stack slot.
5445   SDValue Chain;
5446   if (i32Stack) {
5447     MachineFunction &MF = DAG.getMachineFunction();
5448     MachineMemOperand *MMO =
5449       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5450     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5451     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5452               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5453   } else
5454     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5455                          MPI, false, false, 0);
5456
5457   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5458   // add in a bias.
5459   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5460     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5461                         DAG.getConstant(4, FIPtr.getValueType()));
5462     MPI = MPI.getWithOffset(4);
5463   }
5464
5465   RLI.Chain = Chain;
5466   RLI.Ptr = FIPtr;
5467   RLI.MPI = MPI;
5468 }
5469
5470 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5471                                           SDLoc dl) const {
5472   ReuseLoadInfo RLI;
5473   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5474
5475   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5476                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5477                      RLI.Ranges);
5478 }
5479
5480 // We're trying to insert a regular store, S, and then a load, L. If the
5481 // incoming value, O, is a load, we might just be able to have our load use the
5482 // address used by O. However, we don't know if anything else will store to
5483 // that address before we can load from it. To prevent this situation, we need
5484 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5485 // the same chain operand as O, we create a token factor from the chain results
5486 // of O and L, and we replace all uses of O's chain result with that token
5487 // factor (see spliceIntoChain below for this last part).
5488 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5489                                             ReuseLoadInfo &RLI,
5490                                             SelectionDAG &DAG) const {
5491   SDLoc dl(Op);
5492   if ((Op.getOpcode() == ISD::FP_TO_UINT ||
5493        Op.getOpcode() == ISD::FP_TO_SINT) &&
5494       isOperationLegalOrCustom(Op.getOpcode(),
5495                                Op.getOperand(0).getValueType())) {
5496
5497     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5498     return true;
5499   }
5500
5501   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5502   if (!LD || !ISD::isNON_EXTLoad(LD) || LD->isVolatile() || LD->isNonTemporal())
5503     return false;
5504   if (LD->getMemoryVT() != MemVT)
5505     return false;
5506
5507   RLI.Ptr = LD->getBasePtr();
5508   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5509     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5510            "Non-pre-inc AM on PPC?");
5511     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5512                           LD->getOffset());
5513   }
5514
5515   RLI.Chain = LD->getChain();
5516   RLI.MPI = LD->getPointerInfo();
5517   RLI.IsInvariant = LD->isInvariant();
5518   RLI.Alignment = LD->getAlignment();
5519   RLI.AAInfo = LD->getAAInfo();
5520   RLI.Ranges = LD->getRanges();
5521
5522   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5523   return true;
5524 }
5525
5526 // Given the head of the old chain, ResChain, insert a token factor containing
5527 // it and NewResChain, and make users of ResChain now be users of that token
5528 // factor.
5529 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5530                                         SDValue NewResChain,
5531                                         SelectionDAG &DAG) const {
5532   if (!ResChain)
5533     return;
5534
5535   SDLoc dl(NewResChain);
5536
5537   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5538                            NewResChain, DAG.getUNDEF(MVT::Other));
5539   assert(TF.getNode() != NewResChain.getNode() &&
5540          "A new TF really is required here");
5541
5542   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5543   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5544 }
5545
5546 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5547                                           SelectionDAG &DAG) const {
5548   SDLoc dl(Op);
5549   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5550   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5551     return SDValue();
5552
5553   if (Op.getOperand(0).getValueType() == MVT::i1)
5554     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5555                        DAG.getConstantFP(1.0, Op.getValueType()),
5556                        DAG.getConstantFP(0.0, Op.getValueType()));
5557
5558   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5559          "UINT_TO_FP is supported only with FPCVT");
5560
5561   // If we have FCFIDS, then use it when converting to single-precision.
5562   // Otherwise, convert to double-precision and then round.
5563   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5564                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5565                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5566                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5567                     PPCISD::FCFIDU : PPCISD::FCFID);
5568   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5569                    MVT::f32 : MVT::f64;
5570
5571   if (Op.getOperand(0).getValueType() == MVT::i64) {
5572     SDValue SINT = Op.getOperand(0);
5573     // When converting to single-precision, we actually need to convert
5574     // to double-precision first and then round to single-precision.
5575     // To avoid double-rounding effects during that operation, we have
5576     // to prepare the input operand.  Bits that might be truncated when
5577     // converting to double-precision are replaced by a bit that won't
5578     // be lost at this stage, but is below the single-precision rounding
5579     // position.
5580     //
5581     // However, if -enable-unsafe-fp-math is in effect, accept double
5582     // rounding to avoid the extra overhead.
5583     if (Op.getValueType() == MVT::f32 &&
5584         !Subtarget.hasFPCVT() &&
5585         !DAG.getTarget().Options.UnsafeFPMath) {
5586
5587       // Twiddle input to make sure the low 11 bits are zero.  (If this
5588       // is the case, we are guaranteed the value will fit into the 53 bit
5589       // mantissa of an IEEE double-precision value without rounding.)
5590       // If any of those low 11 bits were not zero originally, make sure
5591       // bit 12 (value 2048) is set instead, so that the final rounding
5592       // to single-precision gets the correct result.
5593       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5594                                   SINT, DAG.getConstant(2047, MVT::i64));
5595       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5596                           Round, DAG.getConstant(2047, MVT::i64));
5597       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5598       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5599                           Round, DAG.getConstant(-2048, MVT::i64));
5600
5601       // However, we cannot use that value unconditionally: if the magnitude
5602       // of the input value is small, the bit-twiddling we did above might
5603       // end up visibly changing the output.  Fortunately, in that case, we
5604       // don't need to twiddle bits since the original input will convert
5605       // exactly to double-precision floating-point already.  Therefore,
5606       // construct a conditional to use the original value if the top 11
5607       // bits are all sign-bit copies, and use the rounded value computed
5608       // above otherwise.
5609       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5610                                  SINT, DAG.getConstant(53, MVT::i32));
5611       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5612                          Cond, DAG.getConstant(1, MVT::i64));
5613       Cond = DAG.getSetCC(dl, MVT::i32,
5614                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5615
5616       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5617     }
5618
5619     ReuseLoadInfo RLI;
5620     SDValue Bits;
5621
5622     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5623       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5624                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5625                          RLI.Ranges);
5626       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5627     } else
5628       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5629
5630     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5631
5632     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5633       FP = DAG.getNode(ISD::FP_ROUND, dl,
5634                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5635     return FP;
5636   }
5637
5638   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5639          "Unhandled INT_TO_FP type in custom expander!");
5640   // Since we only generate this in 64-bit mode, we can take advantage of
5641   // 64-bit registers.  In particular, sign extend the input value into the
5642   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5643   // then lfd it and fcfid it.
5644   MachineFunction &MF = DAG.getMachineFunction();
5645   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5646   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5647
5648   SDValue Ld;
5649   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5650     ReuseLoadInfo RLI;
5651     bool ReusingLoad;
5652     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5653                                             DAG))) {
5654       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5655       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5656
5657       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5658                                    MachinePointerInfo::getFixedStack(FrameIdx),
5659                                    false, false, 0);
5660
5661       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5662              "Expected an i32 store");
5663
5664       RLI.Ptr = FIdx;
5665       RLI.Chain = Store;
5666       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5667       RLI.Alignment = 4;
5668     }
5669
5670     MachineMemOperand *MMO =
5671       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5672                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5673     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5674     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5675                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5676                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5677                                  Ops, MVT::i32, MMO);
5678     if (ReusingLoad)
5679       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5680   } else {
5681     assert(Subtarget.isPPC64() &&
5682            "i32->FP without LFIWAX supported only on PPC64");
5683
5684     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5685     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5686
5687     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5688                                 Op.getOperand(0));
5689
5690     // STD the extended value into the stack slot.
5691     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5692                                  MachinePointerInfo::getFixedStack(FrameIdx),
5693                                  false, false, 0);
5694
5695     // Load the value as a double.
5696     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5697                      MachinePointerInfo::getFixedStack(FrameIdx),
5698                      false, false, false, 0);
5699   }
5700
5701   // FCFID it and return it.
5702   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5703   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5704     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5705   return FP;
5706 }
5707
5708 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5709                                             SelectionDAG &DAG) const {
5710   SDLoc dl(Op);
5711   /*
5712    The rounding mode is in bits 30:31 of FPSR, and has the following
5713    settings:
5714      00 Round to nearest
5715      01 Round to 0
5716      10 Round to +inf
5717      11 Round to -inf
5718
5719   FLT_ROUNDS, on the other hand, expects the following:
5720     -1 Undefined
5721      0 Round to 0
5722      1 Round to nearest
5723      2 Round to +inf
5724      3 Round to -inf
5725
5726   To perform the conversion, we do:
5727     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5728   */
5729
5730   MachineFunction &MF = DAG.getMachineFunction();
5731   EVT VT = Op.getValueType();
5732   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5733
5734   // Save FP Control Word to register
5735   EVT NodeTys[] = {
5736     MVT::f64,    // return register
5737     MVT::Glue    // unused in this context
5738   };
5739   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5740
5741   // Save FP register to stack slot
5742   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5743   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5744   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5745                                StackSlot, MachinePointerInfo(), false, false,0);
5746
5747   // Load FP Control Word from low 32 bits of stack slot.
5748   SDValue Four = DAG.getConstant(4, PtrVT);
5749   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5750   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5751                             false, false, false, 0);
5752
5753   // Transform as necessary
5754   SDValue CWD1 =
5755     DAG.getNode(ISD::AND, dl, MVT::i32,
5756                 CWD, DAG.getConstant(3, MVT::i32));
5757   SDValue CWD2 =
5758     DAG.getNode(ISD::SRL, dl, MVT::i32,
5759                 DAG.getNode(ISD::AND, dl, MVT::i32,
5760                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5761                                         CWD, DAG.getConstant(3, MVT::i32)),
5762                             DAG.getConstant(3, MVT::i32)),
5763                 DAG.getConstant(1, MVT::i32));
5764
5765   SDValue RetVal =
5766     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5767
5768   return DAG.getNode((VT.getSizeInBits() < 16 ?
5769                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5770 }
5771
5772 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5773   EVT VT = Op.getValueType();
5774   unsigned BitWidth = VT.getSizeInBits();
5775   SDLoc dl(Op);
5776   assert(Op.getNumOperands() == 3 &&
5777          VT == Op.getOperand(1).getValueType() &&
5778          "Unexpected SHL!");
5779
5780   // Expand into a bunch of logical ops.  Note that these ops
5781   // depend on the PPC behavior for oversized shift amounts.
5782   SDValue Lo = Op.getOperand(0);
5783   SDValue Hi = Op.getOperand(1);
5784   SDValue Amt = Op.getOperand(2);
5785   EVT AmtVT = Amt.getValueType();
5786
5787   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5788                              DAG.getConstant(BitWidth, AmtVT), Amt);
5789   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5790   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5791   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5792   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5793                              DAG.getConstant(-BitWidth, AmtVT));
5794   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5795   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5796   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5797   SDValue OutOps[] = { OutLo, OutHi };
5798   return DAG.getMergeValues(OutOps, dl);
5799 }
5800
5801 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5802   EVT VT = Op.getValueType();
5803   SDLoc dl(Op);
5804   unsigned BitWidth = VT.getSizeInBits();
5805   assert(Op.getNumOperands() == 3 &&
5806          VT == Op.getOperand(1).getValueType() &&
5807          "Unexpected SRL!");
5808
5809   // Expand into a bunch of logical ops.  Note that these ops
5810   // depend on the PPC behavior for oversized shift amounts.
5811   SDValue Lo = Op.getOperand(0);
5812   SDValue Hi = Op.getOperand(1);
5813   SDValue Amt = Op.getOperand(2);
5814   EVT AmtVT = Amt.getValueType();
5815
5816   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5817                              DAG.getConstant(BitWidth, AmtVT), Amt);
5818   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5819   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5820   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5821   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5822                              DAG.getConstant(-BitWidth, AmtVT));
5823   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5824   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5825   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5826   SDValue OutOps[] = { OutLo, OutHi };
5827   return DAG.getMergeValues(OutOps, dl);
5828 }
5829
5830 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5831   SDLoc dl(Op);
5832   EVT VT = Op.getValueType();
5833   unsigned BitWidth = VT.getSizeInBits();
5834   assert(Op.getNumOperands() == 3 &&
5835          VT == Op.getOperand(1).getValueType() &&
5836          "Unexpected SRA!");
5837
5838   // Expand into a bunch of logical ops, followed by a select_cc.
5839   SDValue Lo = Op.getOperand(0);
5840   SDValue Hi = Op.getOperand(1);
5841   SDValue Amt = Op.getOperand(2);
5842   EVT AmtVT = Amt.getValueType();
5843
5844   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5845                              DAG.getConstant(BitWidth, AmtVT), Amt);
5846   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5847   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5848   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5849   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5850                              DAG.getConstant(-BitWidth, AmtVT));
5851   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5852   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5853   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5854                                   Tmp4, Tmp6, ISD::SETLE);
5855   SDValue OutOps[] = { OutLo, OutHi };
5856   return DAG.getMergeValues(OutOps, dl);
5857 }
5858
5859 //===----------------------------------------------------------------------===//
5860 // Vector related lowering.
5861 //
5862
5863 /// BuildSplatI - Build a canonical splati of Val with an element size of
5864 /// SplatSize.  Cast the result to VT.
5865 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5866                              SelectionDAG &DAG, SDLoc dl) {
5867   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5868
5869   static const EVT VTys[] = { // canonical VT to use for each size.
5870     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5871   };
5872
5873   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5874
5875   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5876   if (Val == -1)
5877     SplatSize = 1;
5878
5879   EVT CanonicalVT = VTys[SplatSize-1];
5880
5881   // Build a canonical splat for this value.
5882   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5883   SmallVector<SDValue, 8> Ops;
5884   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5885   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5886   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5887 }
5888
5889 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5890 /// specified intrinsic ID.
5891 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5892                                 SelectionDAG &DAG, SDLoc dl,
5893                                 EVT DestVT = MVT::Other) {
5894   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5895   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5896                      DAG.getConstant(IID, MVT::i32), Op);
5897 }
5898
5899 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5900 /// specified intrinsic ID.
5901 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5902                                 SelectionDAG &DAG, SDLoc dl,
5903                                 EVT DestVT = MVT::Other) {
5904   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5905   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5906                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5907 }
5908
5909 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5910 /// specified intrinsic ID.
5911 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5912                                 SDValue Op2, SelectionDAG &DAG,
5913                                 SDLoc dl, EVT DestVT = MVT::Other) {
5914   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5915   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5916                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5917 }
5918
5919
5920 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5921 /// amount.  The result has the specified value type.
5922 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5923                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5924   // Force LHS/RHS to be the right type.
5925   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5926   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5927
5928   int Ops[16];
5929   for (unsigned i = 0; i != 16; ++i)
5930     Ops[i] = i + Amt;
5931   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5932   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5933 }
5934
5935 // If this is a case we can't handle, return null and let the default
5936 // expansion code take care of it.  If we CAN select this case, and if it
5937 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5938 // this case more efficiently than a constant pool load, lower it to the
5939 // sequence of ops that should be used.
5940 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5941                                              SelectionDAG &DAG) const {
5942   SDLoc dl(Op);
5943   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5944   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5945
5946   // Check if this is a splat of a constant value.
5947   APInt APSplatBits, APSplatUndef;
5948   unsigned SplatBitSize;
5949   bool HasAnyUndefs;
5950   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5951                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5952     return SDValue();
5953
5954   unsigned SplatBits = APSplatBits.getZExtValue();
5955   unsigned SplatUndef = APSplatUndef.getZExtValue();
5956   unsigned SplatSize = SplatBitSize / 8;
5957
5958   // First, handle single instruction cases.
5959
5960   // All zeros?
5961   if (SplatBits == 0) {
5962     // Canonicalize all zero vectors to be v4i32.
5963     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5964       SDValue Z = DAG.getConstant(0, MVT::i32);
5965       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5966       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5967     }
5968     return Op;
5969   }
5970
5971   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5972   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5973                     (32-SplatBitSize));
5974   if (SextVal >= -16 && SextVal <= 15)
5975     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5976
5977
5978   // Two instruction sequences.
5979
5980   // If this value is in the range [-32,30] and is even, use:
5981   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5982   // If this value is in the range [17,31] and is odd, use:
5983   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5984   // If this value is in the range [-31,-17] and is odd, use:
5985   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5986   // Note the last two are three-instruction sequences.
5987   if (SextVal >= -32 && SextVal <= 31) {
5988     // To avoid having these optimizations undone by constant folding,
5989     // we convert to a pseudo that will be expanded later into one of
5990     // the above forms.
5991     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5992     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5993               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5994     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5995     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5996     if (VT == Op.getValueType())
5997       return RetVal;
5998     else
5999       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6000   }
6001
6002   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6003   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6004   // for fneg/fabs.
6005   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6006     // Make -1 and vspltisw -1:
6007     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6008
6009     // Make the VSLW intrinsic, computing 0x8000_0000.
6010     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6011                                    OnesV, DAG, dl);
6012
6013     // xor by OnesV to invert it.
6014     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6015     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6016   }
6017
6018   // The remaining cases assume either big endian element order or
6019   // a splat-size that equates to the element size of the vector
6020   // to be built.  An example that doesn't work for little endian is
6021   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6022   // and a vector element size of 16 bits.  The code below will
6023   // produce the vector in big endian element order, which for little
6024   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6025
6026   // For now, just avoid these optimizations in that case.
6027   // FIXME: Develop correct optimizations for LE with mismatched
6028   // splat and element sizes.
6029
6030   if (Subtarget.isLittleEndian() &&
6031       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6032     return SDValue();
6033
6034   // Check to see if this is a wide variety of vsplti*, binop self cases.
6035   static const signed char SplatCsts[] = {
6036     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6037     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6038   };
6039
6040   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6041     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6042     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6043     int i = SplatCsts[idx];
6044
6045     // Figure out what shift amount will be used by altivec if shifted by i in
6046     // this splat size.
6047     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6048
6049     // vsplti + shl self.
6050     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6051       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6052       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6053         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6054         Intrinsic::ppc_altivec_vslw
6055       };
6056       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6057       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6058     }
6059
6060     // vsplti + srl self.
6061     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6062       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6063       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6064         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6065         Intrinsic::ppc_altivec_vsrw
6066       };
6067       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6068       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6069     }
6070
6071     // vsplti + sra self.
6072     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6073       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6074       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6075         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6076         Intrinsic::ppc_altivec_vsraw
6077       };
6078       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6079       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6080     }
6081
6082     // vsplti + rol self.
6083     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6084                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6085       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6086       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6087         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6088         Intrinsic::ppc_altivec_vrlw
6089       };
6090       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6091       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6092     }
6093
6094     // t = vsplti c, result = vsldoi t, t, 1
6095     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6096       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6097       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6098     }
6099     // t = vsplti c, result = vsldoi t, t, 2
6100     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6101       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6102       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6103     }
6104     // t = vsplti c, result = vsldoi t, t, 3
6105     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6106       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6107       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6108     }
6109   }
6110
6111   return SDValue();
6112 }
6113
6114 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6115 /// the specified operations to build the shuffle.
6116 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6117                                       SDValue RHS, SelectionDAG &DAG,
6118                                       SDLoc dl) {
6119   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6120   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6121   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6122
6123   enum {
6124     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6125     OP_VMRGHW,
6126     OP_VMRGLW,
6127     OP_VSPLTISW0,
6128     OP_VSPLTISW1,
6129     OP_VSPLTISW2,
6130     OP_VSPLTISW3,
6131     OP_VSLDOI4,
6132     OP_VSLDOI8,
6133     OP_VSLDOI12
6134   };
6135
6136   if (OpNum == OP_COPY) {
6137     if (LHSID == (1*9+2)*9+3) return LHS;
6138     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6139     return RHS;
6140   }
6141
6142   SDValue OpLHS, OpRHS;
6143   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6144   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6145
6146   int ShufIdxs[16];
6147   switch (OpNum) {
6148   default: llvm_unreachable("Unknown i32 permute!");
6149   case OP_VMRGHW:
6150     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6151     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6152     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6153     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6154     break;
6155   case OP_VMRGLW:
6156     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6157     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6158     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6159     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6160     break;
6161   case OP_VSPLTISW0:
6162     for (unsigned i = 0; i != 16; ++i)
6163       ShufIdxs[i] = (i&3)+0;
6164     break;
6165   case OP_VSPLTISW1:
6166     for (unsigned i = 0; i != 16; ++i)
6167       ShufIdxs[i] = (i&3)+4;
6168     break;
6169   case OP_VSPLTISW2:
6170     for (unsigned i = 0; i != 16; ++i)
6171       ShufIdxs[i] = (i&3)+8;
6172     break;
6173   case OP_VSPLTISW3:
6174     for (unsigned i = 0; i != 16; ++i)
6175       ShufIdxs[i] = (i&3)+12;
6176     break;
6177   case OP_VSLDOI4:
6178     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6179   case OP_VSLDOI8:
6180     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6181   case OP_VSLDOI12:
6182     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6183   }
6184   EVT VT = OpLHS.getValueType();
6185   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6186   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6187   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6188   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6189 }
6190
6191 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6192 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6193 /// return the code it can be lowered into.  Worst case, it can always be
6194 /// lowered into a vperm.
6195 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6196                                                SelectionDAG &DAG) const {
6197   SDLoc dl(Op);
6198   SDValue V1 = Op.getOperand(0);
6199   SDValue V2 = Op.getOperand(1);
6200   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6201   EVT VT = Op.getValueType();
6202   bool isLittleEndian = Subtarget.isLittleEndian();
6203
6204   // Cases that are handled by instructions that take permute immediates
6205   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6206   // selected by the instruction selector.
6207   if (V2.getOpcode() == ISD::UNDEF) {
6208     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6209         PPC::isSplatShuffleMask(SVOp, 2) ||
6210         PPC::isSplatShuffleMask(SVOp, 4) ||
6211         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6212         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6213         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6214         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6215         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6216         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6217         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6218         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6219         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6220       return Op;
6221     }
6222   }
6223
6224   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6225   // and produce a fixed permutation.  If any of these match, do not lower to
6226   // VPERM.
6227   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6228   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6229       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6230       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6231       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6232       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6233       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6234       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6235       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6236       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6237     return Op;
6238
6239   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6240   // perfect shuffle table to emit an optimal matching sequence.
6241   ArrayRef<int> PermMask = SVOp->getMask();
6242
6243   unsigned PFIndexes[4];
6244   bool isFourElementShuffle = true;
6245   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6246     unsigned EltNo = 8;   // Start out undef.
6247     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6248       if (PermMask[i*4+j] < 0)
6249         continue;   // Undef, ignore it.
6250
6251       unsigned ByteSource = PermMask[i*4+j];
6252       if ((ByteSource & 3) != j) {
6253         isFourElementShuffle = false;
6254         break;
6255       }
6256
6257       if (EltNo == 8) {
6258         EltNo = ByteSource/4;
6259       } else if (EltNo != ByteSource/4) {
6260         isFourElementShuffle = false;
6261         break;
6262       }
6263     }
6264     PFIndexes[i] = EltNo;
6265   }
6266
6267   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6268   // perfect shuffle vector to determine if it is cost effective to do this as
6269   // discrete instructions, or whether we should use a vperm.
6270   // For now, we skip this for little endian until such time as we have a
6271   // little-endian perfect shuffle table.
6272   if (isFourElementShuffle && !isLittleEndian) {
6273     // Compute the index in the perfect shuffle table.
6274     unsigned PFTableIndex =
6275       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6276
6277     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6278     unsigned Cost  = (PFEntry >> 30);
6279
6280     // Determining when to avoid vperm is tricky.  Many things affect the cost
6281     // of vperm, particularly how many times the perm mask needs to be computed.
6282     // For example, if the perm mask can be hoisted out of a loop or is already
6283     // used (perhaps because there are multiple permutes with the same shuffle
6284     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6285     // the loop requires an extra register.
6286     //
6287     // As a compromise, we only emit discrete instructions if the shuffle can be
6288     // generated in 3 or fewer operations.  When we have loop information
6289     // available, if this block is within a loop, we should avoid using vperm
6290     // for 3-operation perms and use a constant pool load instead.
6291     if (Cost < 3)
6292       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6293   }
6294
6295   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6296   // vector that will get spilled to the constant pool.
6297   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6298
6299   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6300   // that it is in input element units, not in bytes.  Convert now.
6301
6302   // For little endian, the order of the input vectors is reversed, and
6303   // the permutation mask is complemented with respect to 31.  This is
6304   // necessary to produce proper semantics with the big-endian-biased vperm
6305   // instruction.
6306   EVT EltVT = V1.getValueType().getVectorElementType();
6307   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6308
6309   SmallVector<SDValue, 16> ResultMask;
6310   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6311     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6312
6313     for (unsigned j = 0; j != BytesPerElement; ++j)
6314       if (isLittleEndian)
6315         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6316                                              MVT::i32));
6317       else
6318         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6319                                              MVT::i32));
6320   }
6321
6322   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6323                                   ResultMask);
6324   if (isLittleEndian)
6325     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6326                        V2, V1, VPermMask);
6327   else
6328     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6329                        V1, V2, VPermMask);
6330 }
6331
6332 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6333 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6334 /// information about the intrinsic.
6335 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6336                                   bool &isDot) {
6337   unsigned IntrinsicID =
6338     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6339   CompareOpc = -1;
6340   isDot = false;
6341   switch (IntrinsicID) {
6342   default: return false;
6343     // Comparison predicates.
6344   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6345   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6346   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6347   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6348   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6349   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6350   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6351   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6352   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6353   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6354   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6355   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6356   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6357
6358     // Normal Comparisons.
6359   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6360   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6361   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6362   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6363   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6364   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6365   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6366   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6367   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6368   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6369   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6370   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6371   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6372   }
6373   return true;
6374 }
6375
6376 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6377 /// lower, do it, otherwise return null.
6378 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6379                                                    SelectionDAG &DAG) const {
6380   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6381   // opcode number of the comparison.
6382   SDLoc dl(Op);
6383   int CompareOpc;
6384   bool isDot;
6385   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6386     return SDValue();    // Don't custom lower most intrinsics.
6387
6388   // If this is a non-dot comparison, make the VCMP node and we are done.
6389   if (!isDot) {
6390     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6391                               Op.getOperand(1), Op.getOperand(2),
6392                               DAG.getConstant(CompareOpc, MVT::i32));
6393     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6394   }
6395
6396   // Create the PPCISD altivec 'dot' comparison node.
6397   SDValue Ops[] = {
6398     Op.getOperand(2),  // LHS
6399     Op.getOperand(3),  // RHS
6400     DAG.getConstant(CompareOpc, MVT::i32)
6401   };
6402   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6403   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6404
6405   // Now that we have the comparison, emit a copy from the CR to a GPR.
6406   // This is flagged to the above dot comparison.
6407   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6408                                 DAG.getRegister(PPC::CR6, MVT::i32),
6409                                 CompNode.getValue(1));
6410
6411   // Unpack the result based on how the target uses it.
6412   unsigned BitNo;   // Bit # of CR6.
6413   bool InvertBit;   // Invert result?
6414   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6415   default:  // Can't happen, don't crash on invalid number though.
6416   case 0:   // Return the value of the EQ bit of CR6.
6417     BitNo = 0; InvertBit = false;
6418     break;
6419   case 1:   // Return the inverted value of the EQ bit of CR6.
6420     BitNo = 0; InvertBit = true;
6421     break;
6422   case 2:   // Return the value of the LT bit of CR6.
6423     BitNo = 2; InvertBit = false;
6424     break;
6425   case 3:   // Return the inverted value of the LT bit of CR6.
6426     BitNo = 2; InvertBit = true;
6427     break;
6428   }
6429
6430   // Shift the bit into the low position.
6431   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6432                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6433   // Isolate the bit.
6434   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6435                       DAG.getConstant(1, MVT::i32));
6436
6437   // If we are supposed to, toggle the bit.
6438   if (InvertBit)
6439     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6440                         DAG.getConstant(1, MVT::i32));
6441   return Flags;
6442 }
6443
6444 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6445                                                   SelectionDAG &DAG) const {
6446   SDLoc dl(Op);
6447   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6448   // instructions), but for smaller types, we need to first extend up to v2i32
6449   // before doing going farther.
6450   if (Op.getValueType() == MVT::v2i64) {
6451     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6452     if (ExtVT != MVT::v2i32) {
6453       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6454       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6455                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6456                                         ExtVT.getVectorElementType(), 4)));
6457       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6458       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6459                        DAG.getValueType(MVT::v2i32));
6460     }
6461
6462     return Op;
6463   }
6464
6465   return SDValue();
6466 }
6467
6468 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6469                                                    SelectionDAG &DAG) const {
6470   SDLoc dl(Op);
6471   // Create a stack slot that is 16-byte aligned.
6472   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6473   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6474   EVT PtrVT = getPointerTy();
6475   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6476
6477   // Store the input value into Value#0 of the stack slot.
6478   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6479                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6480                                false, false, 0);
6481   // Load it out.
6482   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6483                      false, false, false, 0);
6484 }
6485
6486 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6487   SDLoc dl(Op);
6488   if (Op.getValueType() == MVT::v4i32) {
6489     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6490
6491     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6492     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6493
6494     SDValue RHSSwap =   // = vrlw RHS, 16
6495       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6496
6497     // Shrinkify inputs to v8i16.
6498     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6499     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6500     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6501
6502     // Low parts multiplied together, generating 32-bit results (we ignore the
6503     // top parts).
6504     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6505                                         LHS, RHS, DAG, dl, MVT::v4i32);
6506
6507     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6508                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6509     // Shift the high parts up 16 bits.
6510     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6511                               Neg16, DAG, dl);
6512     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6513   } else if (Op.getValueType() == MVT::v8i16) {
6514     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6515
6516     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6517
6518     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6519                             LHS, RHS, Zero, DAG, dl);
6520   } else if (Op.getValueType() == MVT::v16i8) {
6521     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6522     bool isLittleEndian = Subtarget.isLittleEndian();
6523
6524     // Multiply the even 8-bit parts, producing 16-bit sums.
6525     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6526                                            LHS, RHS, DAG, dl, MVT::v8i16);
6527     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6528
6529     // Multiply the odd 8-bit parts, producing 16-bit sums.
6530     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6531                                           LHS, RHS, DAG, dl, MVT::v8i16);
6532     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6533
6534     // Merge the results together.  Because vmuleub and vmuloub are
6535     // instructions with a big-endian bias, we must reverse the
6536     // element numbering and reverse the meaning of "odd" and "even"
6537     // when generating little endian code.
6538     int Ops[16];
6539     for (unsigned i = 0; i != 8; ++i) {
6540       if (isLittleEndian) {
6541         Ops[i*2  ] = 2*i;
6542         Ops[i*2+1] = 2*i+16;
6543       } else {
6544         Ops[i*2  ] = 2*i+1;
6545         Ops[i*2+1] = 2*i+1+16;
6546       }
6547     }
6548     if (isLittleEndian)
6549       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6550     else
6551       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6552   } else {
6553     llvm_unreachable("Unknown mul to lower!");
6554   }
6555 }
6556
6557 /// LowerOperation - Provide custom lowering hooks for some operations.
6558 ///
6559 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6560   switch (Op.getOpcode()) {
6561   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6562   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6563   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6564   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6565   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6566   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6567   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6568   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6569   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6570   case ISD::VASTART:
6571     return LowerVASTART(Op, DAG, Subtarget);
6572
6573   case ISD::VAARG:
6574     return LowerVAARG(Op, DAG, Subtarget);
6575
6576   case ISD::VACOPY:
6577     return LowerVACOPY(Op, DAG, Subtarget);
6578
6579   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6580   case ISD::DYNAMIC_STACKALLOC:
6581     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6582
6583   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6584   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6585
6586   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6587   case ISD::STORE:              return LowerSTORE(Op, DAG);
6588   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6589   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6590   case ISD::FP_TO_UINT:
6591   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6592                                                       SDLoc(Op));
6593   case ISD::UINT_TO_FP:
6594   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6595   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6596
6597   // Lower 64-bit shifts.
6598   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6599   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6600   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6601
6602   // Vector-related lowering.
6603   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6604   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6605   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6606   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6607   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6608   case ISD::MUL:                return LowerMUL(Op, DAG);
6609
6610   // For counter-based loop handling.
6611   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6612
6613   // Frame & Return address.
6614   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6615   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6616   }
6617 }
6618
6619 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6620                                            SmallVectorImpl<SDValue>&Results,
6621                                            SelectionDAG &DAG) const {
6622   const TargetMachine &TM = getTargetMachine();
6623   SDLoc dl(N);
6624   switch (N->getOpcode()) {
6625   default:
6626     llvm_unreachable("Do not know how to custom type legalize this operation!");
6627   case ISD::READCYCLECOUNTER: {
6628     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6629     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6630
6631     Results.push_back(RTB);
6632     Results.push_back(RTB.getValue(1));
6633     Results.push_back(RTB.getValue(2));
6634     break;
6635   }
6636   case ISD::INTRINSIC_W_CHAIN: {
6637     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6638         Intrinsic::ppc_is_decremented_ctr_nonzero)
6639       break;
6640
6641     assert(N->getValueType(0) == MVT::i1 &&
6642            "Unexpected result type for CTR decrement intrinsic");
6643     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6644     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6645     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6646                                  N->getOperand(1)); 
6647
6648     Results.push_back(NewInt);
6649     Results.push_back(NewInt.getValue(1));
6650     break;
6651   }
6652   case ISD::VAARG: {
6653     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6654         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6655       return;
6656
6657     EVT VT = N->getValueType(0);
6658
6659     if (VT == MVT::i64) {
6660       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6661
6662       Results.push_back(NewNode);
6663       Results.push_back(NewNode.getValue(1));
6664     }
6665     return;
6666   }
6667   case ISD::FP_ROUND_INREG: {
6668     assert(N->getValueType(0) == MVT::ppcf128);
6669     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6670     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6671                              MVT::f64, N->getOperand(0),
6672                              DAG.getIntPtrConstant(0));
6673     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6674                              MVT::f64, N->getOperand(0),
6675                              DAG.getIntPtrConstant(1));
6676
6677     // Add the two halves of the long double in round-to-zero mode.
6678     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6679
6680     // We know the low half is about to be thrown away, so just use something
6681     // convenient.
6682     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6683                                 FPreg, FPreg));
6684     return;
6685   }
6686   case ISD::FP_TO_SINT:
6687     // LowerFP_TO_INT() can only handle f32 and f64.
6688     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6689       return;
6690     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6691     return;
6692   }
6693 }
6694
6695
6696 //===----------------------------------------------------------------------===//
6697 //  Other Lowering Code
6698 //===----------------------------------------------------------------------===//
6699
6700 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6701   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6702   Function *Func = Intrinsic::getDeclaration(M, Id);
6703   return Builder.CreateCall(Func);
6704 }
6705
6706 // The mappings for emitLeading/TrailingFence is taken from
6707 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6708 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6709                                          AtomicOrdering Ord, bool IsStore,
6710                                          bool IsLoad) const {
6711   if (Ord == SequentiallyConsistent)
6712     return callIntrinsic(Builder, Intrinsic::ppc_sync);
6713   else if (isAtLeastRelease(Ord))
6714     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6715   else
6716     return nullptr;
6717 }
6718
6719 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6720                                           AtomicOrdering Ord, bool IsStore,
6721                                           bool IsLoad) const {
6722   if (IsLoad && isAtLeastAcquire(Ord))
6723     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6724   // FIXME: this is too conservative, a dependent branch + isync is enough.
6725   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6726   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6727   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6728   else
6729     return nullptr;
6730 }
6731
6732 MachineBasicBlock *
6733 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6734                                     bool is64bit, unsigned BinOpcode) const {
6735   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6736   const TargetInstrInfo *TII =
6737       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6738
6739   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6740   MachineFunction *F = BB->getParent();
6741   MachineFunction::iterator It = BB;
6742   ++It;
6743
6744   unsigned dest = MI->getOperand(0).getReg();
6745   unsigned ptrA = MI->getOperand(1).getReg();
6746   unsigned ptrB = MI->getOperand(2).getReg();
6747   unsigned incr = MI->getOperand(3).getReg();
6748   DebugLoc dl = MI->getDebugLoc();
6749
6750   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6751   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6752   F->insert(It, loopMBB);
6753   F->insert(It, exitMBB);
6754   exitMBB->splice(exitMBB->begin(), BB,
6755                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6756   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6757
6758   MachineRegisterInfo &RegInfo = F->getRegInfo();
6759   unsigned TmpReg = (!BinOpcode) ? incr :
6760     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6761                                            : &PPC::GPRCRegClass);
6762
6763   //  thisMBB:
6764   //   ...
6765   //   fallthrough --> loopMBB
6766   BB->addSuccessor(loopMBB);
6767
6768   //  loopMBB:
6769   //   l[wd]arx dest, ptr
6770   //   add r0, dest, incr
6771   //   st[wd]cx. r0, ptr
6772   //   bne- loopMBB
6773   //   fallthrough --> exitMBB
6774   BB = loopMBB;
6775   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6776     .addReg(ptrA).addReg(ptrB);
6777   if (BinOpcode)
6778     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6779   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6780     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6781   BuildMI(BB, dl, TII->get(PPC::BCC))
6782     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6783   BB->addSuccessor(loopMBB);
6784   BB->addSuccessor(exitMBB);
6785
6786   //  exitMBB:
6787   //   ...
6788   BB = exitMBB;
6789   return BB;
6790 }
6791
6792 MachineBasicBlock *
6793 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6794                                             MachineBasicBlock *BB,
6795                                             bool is8bit,    // operation
6796                                             unsigned BinOpcode) const {
6797   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6798   const TargetInstrInfo *TII =
6799       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6800   // In 64 bit mode we have to use 64 bits for addresses, even though the
6801   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6802   // registers without caring whether they're 32 or 64, but here we're
6803   // doing actual arithmetic on the addresses.
6804   bool is64bit = Subtarget.isPPC64();
6805   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6806
6807   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6808   MachineFunction *F = BB->getParent();
6809   MachineFunction::iterator It = BB;
6810   ++It;
6811
6812   unsigned dest = MI->getOperand(0).getReg();
6813   unsigned ptrA = MI->getOperand(1).getReg();
6814   unsigned ptrB = MI->getOperand(2).getReg();
6815   unsigned incr = MI->getOperand(3).getReg();
6816   DebugLoc dl = MI->getDebugLoc();
6817
6818   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6819   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6820   F->insert(It, loopMBB);
6821   F->insert(It, exitMBB);
6822   exitMBB->splice(exitMBB->begin(), BB,
6823                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6824   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6825
6826   MachineRegisterInfo &RegInfo = F->getRegInfo();
6827   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6828                                           : &PPC::GPRCRegClass;
6829   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6830   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6831   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6832   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6833   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6834   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6835   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6836   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6837   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6838   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6839   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6840   unsigned Ptr1Reg;
6841   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6842
6843   //  thisMBB:
6844   //   ...
6845   //   fallthrough --> loopMBB
6846   BB->addSuccessor(loopMBB);
6847
6848   // The 4-byte load must be aligned, while a char or short may be
6849   // anywhere in the word.  Hence all this nasty bookkeeping code.
6850   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6851   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6852   //   xori shift, shift1, 24 [16]
6853   //   rlwinm ptr, ptr1, 0, 0, 29
6854   //   slw incr2, incr, shift
6855   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6856   //   slw mask, mask2, shift
6857   //  loopMBB:
6858   //   lwarx tmpDest, ptr
6859   //   add tmp, tmpDest, incr2
6860   //   andc tmp2, tmpDest, mask
6861   //   and tmp3, tmp, mask
6862   //   or tmp4, tmp3, tmp2
6863   //   stwcx. tmp4, ptr
6864   //   bne- loopMBB
6865   //   fallthrough --> exitMBB
6866   //   srw dest, tmpDest, shift
6867   if (ptrA != ZeroReg) {
6868     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6869     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6870       .addReg(ptrA).addReg(ptrB);
6871   } else {
6872     Ptr1Reg = ptrB;
6873   }
6874   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6875       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6876   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6877       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6878   if (is64bit)
6879     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6880       .addReg(Ptr1Reg).addImm(0).addImm(61);
6881   else
6882     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6883       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6884   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6885       .addReg(incr).addReg(ShiftReg);
6886   if (is8bit)
6887     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6888   else {
6889     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6890     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6891   }
6892   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6893       .addReg(Mask2Reg).addReg(ShiftReg);
6894
6895   BB = loopMBB;
6896   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6897     .addReg(ZeroReg).addReg(PtrReg);
6898   if (BinOpcode)
6899     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6900       .addReg(Incr2Reg).addReg(TmpDestReg);
6901   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6902     .addReg(TmpDestReg).addReg(MaskReg);
6903   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6904     .addReg(TmpReg).addReg(MaskReg);
6905   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6906     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6907   BuildMI(BB, dl, TII->get(PPC::STWCX))
6908     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6909   BuildMI(BB, dl, TII->get(PPC::BCC))
6910     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6911   BB->addSuccessor(loopMBB);
6912   BB->addSuccessor(exitMBB);
6913
6914   //  exitMBB:
6915   //   ...
6916   BB = exitMBB;
6917   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6918     .addReg(ShiftReg);
6919   return BB;
6920 }
6921
6922 llvm::MachineBasicBlock*
6923 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6924                                     MachineBasicBlock *MBB) const {
6925   DebugLoc DL = MI->getDebugLoc();
6926   const TargetInstrInfo *TII =
6927       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6928
6929   MachineFunction *MF = MBB->getParent();
6930   MachineRegisterInfo &MRI = MF->getRegInfo();
6931
6932   const BasicBlock *BB = MBB->getBasicBlock();
6933   MachineFunction::iterator I = MBB;
6934   ++I;
6935
6936   // Memory Reference
6937   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6938   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6939
6940   unsigned DstReg = MI->getOperand(0).getReg();
6941   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6942   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6943   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6944   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6945
6946   MVT PVT = getPointerTy();
6947   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6948          "Invalid Pointer Size!");
6949   // For v = setjmp(buf), we generate
6950   //
6951   // thisMBB:
6952   //  SjLjSetup mainMBB
6953   //  bl mainMBB
6954   //  v_restore = 1
6955   //  b sinkMBB
6956   //
6957   // mainMBB:
6958   //  buf[LabelOffset] = LR
6959   //  v_main = 0
6960   //
6961   // sinkMBB:
6962   //  v = phi(main, restore)
6963   //
6964
6965   MachineBasicBlock *thisMBB = MBB;
6966   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6967   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6968   MF->insert(I, mainMBB);
6969   MF->insert(I, sinkMBB);
6970
6971   MachineInstrBuilder MIB;
6972
6973   // Transfer the remainder of BB and its successor edges to sinkMBB.
6974   sinkMBB->splice(sinkMBB->begin(), MBB,
6975                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6976   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6977
6978   // Note that the structure of the jmp_buf used here is not compatible
6979   // with that used by libc, and is not designed to be. Specifically, it
6980   // stores only those 'reserved' registers that LLVM does not otherwise
6981   // understand how to spill. Also, by convention, by the time this
6982   // intrinsic is called, Clang has already stored the frame address in the
6983   // first slot of the buffer and stack address in the third. Following the
6984   // X86 target code, we'll store the jump address in the second slot. We also
6985   // need to save the TOC pointer (R2) to handle jumps between shared
6986   // libraries, and that will be stored in the fourth slot. The thread
6987   // identifier (R13) is not affected.
6988
6989   // thisMBB:
6990   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6991   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6992   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6993
6994   // Prepare IP either in reg.
6995   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6996   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6997   unsigned BufReg = MI->getOperand(1).getReg();
6998
6999   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7000     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7001             .addReg(PPC::X2)
7002             .addImm(TOCOffset)
7003             .addReg(BufReg);
7004     MIB.setMemRefs(MMOBegin, MMOEnd);
7005   }
7006
7007   // Naked functions never have a base pointer, and so we use r1. For all
7008   // other functions, this decision must be delayed until during PEI.
7009   unsigned BaseReg;
7010   if (MF->getFunction()->getAttributes().hasAttribute(
7011           AttributeSet::FunctionIndex, Attribute::Naked))
7012     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7013   else
7014     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7015
7016   MIB = BuildMI(*thisMBB, MI, DL,
7017                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7018           .addReg(BaseReg)
7019           .addImm(BPOffset)
7020           .addReg(BufReg);
7021   MIB.setMemRefs(MMOBegin, MMOEnd);
7022
7023   // Setup
7024   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7025   const PPCRegisterInfo *TRI =
7026       getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
7027   MIB.addRegMask(TRI->getNoPreservedMask());
7028
7029   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7030
7031   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7032           .addMBB(mainMBB);
7033   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7034
7035   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7036   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7037
7038   // mainMBB:
7039   //  mainDstReg = 0
7040   MIB = BuildMI(mainMBB, DL,
7041     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7042
7043   // Store IP
7044   if (Subtarget.isPPC64()) {
7045     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7046             .addReg(LabelReg)
7047             .addImm(LabelOffset)
7048             .addReg(BufReg);
7049   } else {
7050     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7051             .addReg(LabelReg)
7052             .addImm(LabelOffset)
7053             .addReg(BufReg);
7054   }
7055
7056   MIB.setMemRefs(MMOBegin, MMOEnd);
7057
7058   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7059   mainMBB->addSuccessor(sinkMBB);
7060
7061   // sinkMBB:
7062   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7063           TII->get(PPC::PHI), DstReg)
7064     .addReg(mainDstReg).addMBB(mainMBB)
7065     .addReg(restoreDstReg).addMBB(thisMBB);
7066
7067   MI->eraseFromParent();
7068   return sinkMBB;
7069 }
7070
7071 MachineBasicBlock *
7072 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7073                                      MachineBasicBlock *MBB) const {
7074   DebugLoc DL = MI->getDebugLoc();
7075   const TargetInstrInfo *TII =
7076       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7077
7078   MachineFunction *MF = MBB->getParent();
7079   MachineRegisterInfo &MRI = MF->getRegInfo();
7080
7081   // Memory Reference
7082   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7083   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7084
7085   MVT PVT = getPointerTy();
7086   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7087          "Invalid Pointer Size!");
7088
7089   const TargetRegisterClass *RC =
7090     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7091   unsigned Tmp = MRI.createVirtualRegister(RC);
7092   // Since FP is only updated here but NOT referenced, it's treated as GPR.
7093   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7094   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7095   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
7096                   (Subtarget.isSVR4ABI() &&
7097                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
7098                      PPC::R29 : PPC::R30);
7099
7100   MachineInstrBuilder MIB;
7101
7102   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7103   const int64_t SPOffset    = 2 * PVT.getStoreSize();
7104   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7105   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7106
7107   unsigned BufReg = MI->getOperand(0).getReg();
7108
7109   // Reload FP (the jumped-to function may not have had a
7110   // frame pointer, and if so, then its r31 will be restored
7111   // as necessary).
7112   if (PVT == MVT::i64) {
7113     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7114             .addImm(0)
7115             .addReg(BufReg);
7116   } else {
7117     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7118             .addImm(0)
7119             .addReg(BufReg);
7120   }
7121   MIB.setMemRefs(MMOBegin, MMOEnd);
7122
7123   // Reload IP
7124   if (PVT == MVT::i64) {
7125     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7126             .addImm(LabelOffset)
7127             .addReg(BufReg);
7128   } else {
7129     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7130             .addImm(LabelOffset)
7131             .addReg(BufReg);
7132   }
7133   MIB.setMemRefs(MMOBegin, MMOEnd);
7134
7135   // Reload SP
7136   if (PVT == MVT::i64) {
7137     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7138             .addImm(SPOffset)
7139             .addReg(BufReg);
7140   } else {
7141     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7142             .addImm(SPOffset)
7143             .addReg(BufReg);
7144   }
7145   MIB.setMemRefs(MMOBegin, MMOEnd);
7146
7147   // Reload BP
7148   if (PVT == MVT::i64) {
7149     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7150             .addImm(BPOffset)
7151             .addReg(BufReg);
7152   } else {
7153     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7154             .addImm(BPOffset)
7155             .addReg(BufReg);
7156   }
7157   MIB.setMemRefs(MMOBegin, MMOEnd);
7158
7159   // Reload TOC
7160   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7161     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7162             .addImm(TOCOffset)
7163             .addReg(BufReg);
7164
7165     MIB.setMemRefs(MMOBegin, MMOEnd);
7166   }
7167
7168   // Jump
7169   BuildMI(*MBB, MI, DL,
7170           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7171   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7172
7173   MI->eraseFromParent();
7174   return MBB;
7175 }
7176
7177 MachineBasicBlock *
7178 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7179                                                MachineBasicBlock *BB) const {
7180   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7181       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7182     return emitEHSjLjSetJmp(MI, BB);
7183   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7184              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7185     return emitEHSjLjLongJmp(MI, BB);
7186   }
7187
7188   const TargetInstrInfo *TII =
7189       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7190
7191   // To "insert" these instructions we actually have to insert their
7192   // control-flow patterns.
7193   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7194   MachineFunction::iterator It = BB;
7195   ++It;
7196
7197   MachineFunction *F = BB->getParent();
7198
7199   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7200                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
7201                                  MI->getOpcode() == PPC::SELECT_I4 ||
7202                                  MI->getOpcode() == PPC::SELECT_I8)) {
7203     SmallVector<MachineOperand, 2> Cond;
7204     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7205         MI->getOpcode() == PPC::SELECT_CC_I8)
7206       Cond.push_back(MI->getOperand(4));
7207     else
7208       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7209     Cond.push_back(MI->getOperand(1));
7210
7211     DebugLoc dl = MI->getDebugLoc();
7212     const TargetInstrInfo *TII =
7213         getTargetMachine().getSubtargetImpl()->getInstrInfo();
7214     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7215                       Cond, MI->getOperand(2).getReg(),
7216                       MI->getOperand(3).getReg());
7217   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7218              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7219              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7220              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7221              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7222              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7223              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7224              MI->getOpcode() == PPC::SELECT_I4 ||
7225              MI->getOpcode() == PPC::SELECT_I8 ||
7226              MI->getOpcode() == PPC::SELECT_F4 ||
7227              MI->getOpcode() == PPC::SELECT_F8 ||
7228              MI->getOpcode() == PPC::SELECT_VRRC ||
7229              MI->getOpcode() == PPC::SELECT_VSFRC ||
7230              MI->getOpcode() == PPC::SELECT_VSRC) {
7231     // The incoming instruction knows the destination vreg to set, the
7232     // condition code register to branch on, the true/false values to
7233     // select between, and a branch opcode to use.
7234
7235     //  thisMBB:
7236     //  ...
7237     //   TrueVal = ...
7238     //   cmpTY ccX, r1, r2
7239     //   bCC copy1MBB
7240     //   fallthrough --> copy0MBB
7241     MachineBasicBlock *thisMBB = BB;
7242     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7243     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7244     DebugLoc dl = MI->getDebugLoc();
7245     F->insert(It, copy0MBB);
7246     F->insert(It, sinkMBB);
7247
7248     // Transfer the remainder of BB and its successor edges to sinkMBB.
7249     sinkMBB->splice(sinkMBB->begin(), BB,
7250                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7251     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7252
7253     // Next, add the true and fallthrough blocks as its successors.
7254     BB->addSuccessor(copy0MBB);
7255     BB->addSuccessor(sinkMBB);
7256
7257     if (MI->getOpcode() == PPC::SELECT_I4 ||
7258         MI->getOpcode() == PPC::SELECT_I8 ||
7259         MI->getOpcode() == PPC::SELECT_F4 ||
7260         MI->getOpcode() == PPC::SELECT_F8 ||
7261         MI->getOpcode() == PPC::SELECT_VRRC ||
7262         MI->getOpcode() == PPC::SELECT_VSFRC ||
7263         MI->getOpcode() == PPC::SELECT_VSRC) {
7264       BuildMI(BB, dl, TII->get(PPC::BC))
7265         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7266     } else {
7267       unsigned SelectPred = MI->getOperand(4).getImm();
7268       BuildMI(BB, dl, TII->get(PPC::BCC))
7269         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7270     }
7271
7272     //  copy0MBB:
7273     //   %FalseValue = ...
7274     //   # fallthrough to sinkMBB
7275     BB = copy0MBB;
7276
7277     // Update machine-CFG edges
7278     BB->addSuccessor(sinkMBB);
7279
7280     //  sinkMBB:
7281     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7282     //  ...
7283     BB = sinkMBB;
7284     BuildMI(*BB, BB->begin(), dl,
7285             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7286       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7287       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7288   } else if (MI->getOpcode() == PPC::ReadTB) {
7289     // To read the 64-bit time-base register on a 32-bit target, we read the
7290     // two halves. Should the counter have wrapped while it was being read, we
7291     // need to try again.
7292     // ...
7293     // readLoop:
7294     // mfspr Rx,TBU # load from TBU
7295     // mfspr Ry,TB  # load from TB
7296     // mfspr Rz,TBU # load from TBU
7297     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
7298     // bne readLoop   # branch if they're not equal
7299     // ...
7300
7301     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7302     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7303     DebugLoc dl = MI->getDebugLoc();
7304     F->insert(It, readMBB);
7305     F->insert(It, sinkMBB);
7306
7307     // Transfer the remainder of BB and its successor edges to sinkMBB.
7308     sinkMBB->splice(sinkMBB->begin(), BB,
7309                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7310     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7311
7312     BB->addSuccessor(readMBB);
7313     BB = readMBB;
7314
7315     MachineRegisterInfo &RegInfo = F->getRegInfo();
7316     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7317     unsigned LoReg = MI->getOperand(0).getReg();
7318     unsigned HiReg = MI->getOperand(1).getReg();
7319
7320     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7321     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7322     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7323
7324     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7325
7326     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7327       .addReg(HiReg).addReg(ReadAgainReg);
7328     BuildMI(BB, dl, TII->get(PPC::BCC))
7329       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7330
7331     BB->addSuccessor(readMBB);
7332     BB->addSuccessor(sinkMBB);
7333   }
7334   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7335     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7336   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7337     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7338   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7339     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7340   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7341     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7342
7343   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7344     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7345   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7346     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7347   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7348     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7349   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7350     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7351
7352   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7353     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7354   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7355     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7356   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7357     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7358   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7359     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7360
7361   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7362     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7363   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7364     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7365   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7366     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7367   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7368     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7369
7370   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7371     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7372   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7373     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7374   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7375     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7376   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7377     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7378
7379   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7380     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7381   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7382     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7383   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7384     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7385   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7386     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7387
7388   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7389     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7390   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7391     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7392   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7393     BB = EmitAtomicBinary(MI, BB, false, 0);
7394   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7395     BB = EmitAtomicBinary(MI, BB, true, 0);
7396
7397   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7398            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7399     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7400
7401     unsigned dest   = MI->getOperand(0).getReg();
7402     unsigned ptrA   = MI->getOperand(1).getReg();
7403     unsigned ptrB   = MI->getOperand(2).getReg();
7404     unsigned oldval = MI->getOperand(3).getReg();
7405     unsigned newval = MI->getOperand(4).getReg();
7406     DebugLoc dl     = MI->getDebugLoc();
7407
7408     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7409     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7410     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7411     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7412     F->insert(It, loop1MBB);
7413     F->insert(It, loop2MBB);
7414     F->insert(It, midMBB);
7415     F->insert(It, exitMBB);
7416     exitMBB->splice(exitMBB->begin(), BB,
7417                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7418     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7419
7420     //  thisMBB:
7421     //   ...
7422     //   fallthrough --> loopMBB
7423     BB->addSuccessor(loop1MBB);
7424
7425     // loop1MBB:
7426     //   l[wd]arx dest, ptr
7427     //   cmp[wd] dest, oldval
7428     //   bne- midMBB
7429     // loop2MBB:
7430     //   st[wd]cx. newval, ptr
7431     //   bne- loopMBB
7432     //   b exitBB
7433     // midMBB:
7434     //   st[wd]cx. dest, ptr
7435     // exitBB:
7436     BB = loop1MBB;
7437     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7438       .addReg(ptrA).addReg(ptrB);
7439     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7440       .addReg(oldval).addReg(dest);
7441     BuildMI(BB, dl, TII->get(PPC::BCC))
7442       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7443     BB->addSuccessor(loop2MBB);
7444     BB->addSuccessor(midMBB);
7445
7446     BB = loop2MBB;
7447     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7448       .addReg(newval).addReg(ptrA).addReg(ptrB);
7449     BuildMI(BB, dl, TII->get(PPC::BCC))
7450       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7451     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7452     BB->addSuccessor(loop1MBB);
7453     BB->addSuccessor(exitMBB);
7454
7455     BB = midMBB;
7456     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7457       .addReg(dest).addReg(ptrA).addReg(ptrB);
7458     BB->addSuccessor(exitMBB);
7459
7460     //  exitMBB:
7461     //   ...
7462     BB = exitMBB;
7463   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7464              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7465     // We must use 64-bit registers for addresses when targeting 64-bit,
7466     // since we're actually doing arithmetic on them.  Other registers
7467     // can be 32-bit.
7468     bool is64bit = Subtarget.isPPC64();
7469     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7470
7471     unsigned dest   = MI->getOperand(0).getReg();
7472     unsigned ptrA   = MI->getOperand(1).getReg();
7473     unsigned ptrB   = MI->getOperand(2).getReg();
7474     unsigned oldval = MI->getOperand(3).getReg();
7475     unsigned newval = MI->getOperand(4).getReg();
7476     DebugLoc dl     = MI->getDebugLoc();
7477
7478     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7479     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7480     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7481     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7482     F->insert(It, loop1MBB);
7483     F->insert(It, loop2MBB);
7484     F->insert(It, midMBB);
7485     F->insert(It, exitMBB);
7486     exitMBB->splice(exitMBB->begin(), BB,
7487                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7488     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7489
7490     MachineRegisterInfo &RegInfo = F->getRegInfo();
7491     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7492                                             : &PPC::GPRCRegClass;
7493     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7494     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7495     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7496     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7497     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7498     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7499     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7500     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7501     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7502     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7503     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7504     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7505     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7506     unsigned Ptr1Reg;
7507     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7508     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7509     //  thisMBB:
7510     //   ...
7511     //   fallthrough --> loopMBB
7512     BB->addSuccessor(loop1MBB);
7513
7514     // The 4-byte load must be aligned, while a char or short may be
7515     // anywhere in the word.  Hence all this nasty bookkeeping code.
7516     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7517     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7518     //   xori shift, shift1, 24 [16]
7519     //   rlwinm ptr, ptr1, 0, 0, 29
7520     //   slw newval2, newval, shift
7521     //   slw oldval2, oldval,shift
7522     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7523     //   slw mask, mask2, shift
7524     //   and newval3, newval2, mask
7525     //   and oldval3, oldval2, mask
7526     // loop1MBB:
7527     //   lwarx tmpDest, ptr
7528     //   and tmp, tmpDest, mask
7529     //   cmpw tmp, oldval3
7530     //   bne- midMBB
7531     // loop2MBB:
7532     //   andc tmp2, tmpDest, mask
7533     //   or tmp4, tmp2, newval3
7534     //   stwcx. tmp4, ptr
7535     //   bne- loop1MBB
7536     //   b exitBB
7537     // midMBB:
7538     //   stwcx. tmpDest, ptr
7539     // exitBB:
7540     //   srw dest, tmpDest, shift
7541     if (ptrA != ZeroReg) {
7542       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7543       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7544         .addReg(ptrA).addReg(ptrB);
7545     } else {
7546       Ptr1Reg = ptrB;
7547     }
7548     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7549         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7550     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7551         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7552     if (is64bit)
7553       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7554         .addReg(Ptr1Reg).addImm(0).addImm(61);
7555     else
7556       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7557         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7558     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7559         .addReg(newval).addReg(ShiftReg);
7560     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7561         .addReg(oldval).addReg(ShiftReg);
7562     if (is8bit)
7563       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7564     else {
7565       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7566       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7567         .addReg(Mask3Reg).addImm(65535);
7568     }
7569     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7570         .addReg(Mask2Reg).addReg(ShiftReg);
7571     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7572         .addReg(NewVal2Reg).addReg(MaskReg);
7573     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7574         .addReg(OldVal2Reg).addReg(MaskReg);
7575
7576     BB = loop1MBB;
7577     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7578         .addReg(ZeroReg).addReg(PtrReg);
7579     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7580         .addReg(TmpDestReg).addReg(MaskReg);
7581     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7582         .addReg(TmpReg).addReg(OldVal3Reg);
7583     BuildMI(BB, dl, TII->get(PPC::BCC))
7584         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7585     BB->addSuccessor(loop2MBB);
7586     BB->addSuccessor(midMBB);
7587
7588     BB = loop2MBB;
7589     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7590         .addReg(TmpDestReg).addReg(MaskReg);
7591     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7592         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7593     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7594         .addReg(ZeroReg).addReg(PtrReg);
7595     BuildMI(BB, dl, TII->get(PPC::BCC))
7596       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7597     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7598     BB->addSuccessor(loop1MBB);
7599     BB->addSuccessor(exitMBB);
7600
7601     BB = midMBB;
7602     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7603       .addReg(ZeroReg).addReg(PtrReg);
7604     BB->addSuccessor(exitMBB);
7605
7606     //  exitMBB:
7607     //   ...
7608     BB = exitMBB;
7609     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7610       .addReg(ShiftReg);
7611   } else if (MI->getOpcode() == PPC::FADDrtz) {
7612     // This pseudo performs an FADD with rounding mode temporarily forced
7613     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7614     // is not modeled at the SelectionDAG level.
7615     unsigned Dest = MI->getOperand(0).getReg();
7616     unsigned Src1 = MI->getOperand(1).getReg();
7617     unsigned Src2 = MI->getOperand(2).getReg();
7618     DebugLoc dl   = MI->getDebugLoc();
7619
7620     MachineRegisterInfo &RegInfo = F->getRegInfo();
7621     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7622
7623     // Save FPSCR value.
7624     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7625
7626     // Set rounding mode to round-to-zero.
7627     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7628     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7629
7630     // Perform addition.
7631     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7632
7633     // Restore FPSCR value.
7634     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7635   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7636              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7637              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7638              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7639     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7640                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7641                       PPC::ANDIo8 : PPC::ANDIo;
7642     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7643                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7644
7645     MachineRegisterInfo &RegInfo = F->getRegInfo();
7646     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7647                                                   &PPC::GPRCRegClass :
7648                                                   &PPC::G8RCRegClass);
7649
7650     DebugLoc dl   = MI->getDebugLoc();
7651     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7652       .addReg(MI->getOperand(1).getReg()).addImm(1);
7653     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7654             MI->getOperand(0).getReg())
7655       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7656   } else {
7657     llvm_unreachable("Unexpected instr type to insert");
7658   }
7659
7660   MI->eraseFromParent();   // The pseudo instruction is gone now.
7661   return BB;
7662 }
7663
7664 //===----------------------------------------------------------------------===//
7665 // Target Optimization Hooks
7666 //===----------------------------------------------------------------------===//
7667
7668 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7669                                             DAGCombinerInfo &DCI,
7670                                             unsigned &RefinementSteps,
7671                                             bool &UseOneConstNR) const {
7672   EVT VT = Operand.getValueType();
7673   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7674       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7675       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7676       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7677     // Convergence is quadratic, so we essentially double the number of digits
7678     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7679     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7680     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7681     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7682     if (VT.getScalarType() == MVT::f64)
7683       ++RefinementSteps;
7684     UseOneConstNR = true;
7685     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7686   }
7687   return SDValue();
7688 }
7689
7690 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7691                                             DAGCombinerInfo &DCI,
7692                                             unsigned &RefinementSteps) const {
7693   EVT VT = Operand.getValueType();
7694   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7695       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7696       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7697       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7698     // Convergence is quadratic, so we essentially double the number of digits
7699     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7700     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7701     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7702     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7703     if (VT.getScalarType() == MVT::f64)
7704       ++RefinementSteps;
7705     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7706   }
7707   return SDValue();
7708 }
7709
7710 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7711   // Note: This functionality is used only when unsafe-fp-math is enabled, and
7712   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7713   // enabled for division), this functionality is redundant with the default
7714   // combiner logic (once the division -> reciprocal/multiply transformation
7715   // has taken place). As a result, this matters more for older cores than for
7716   // newer ones.
7717
7718   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7719   // reciprocal if there are two or more FDIVs (for embedded cores with only
7720   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7721   switch (Subtarget.getDarwinDirective()) {
7722   default:
7723     return NumUsers > 2;
7724   case PPC::DIR_440:
7725   case PPC::DIR_A2:
7726   case PPC::DIR_E500mc:
7727   case PPC::DIR_E5500:
7728     return NumUsers > 1;
7729   }
7730 }
7731
7732 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7733                             unsigned Bytes, int Dist,
7734                             SelectionDAG &DAG) {
7735   if (VT.getSizeInBits() / 8 != Bytes)
7736     return false;
7737
7738   SDValue BaseLoc = Base->getBasePtr();
7739   if (Loc.getOpcode() == ISD::FrameIndex) {
7740     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7741       return false;
7742     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7743     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7744     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7745     int FS  = MFI->getObjectSize(FI);
7746     int BFS = MFI->getObjectSize(BFI);
7747     if (FS != BFS || FS != (int)Bytes) return false;
7748     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7749   }
7750
7751   // Handle X+C
7752   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7753       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7754     return true;
7755
7756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7757   const GlobalValue *GV1 = nullptr;
7758   const GlobalValue *GV2 = nullptr;
7759   int64_t Offset1 = 0;
7760   int64_t Offset2 = 0;
7761   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7762   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7763   if (isGA1 && isGA2 && GV1 == GV2)
7764     return Offset1 == (Offset2 + Dist*Bytes);
7765   return false;
7766 }
7767
7768 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7769 // not enforce equality of the chain operands.
7770 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7771                             unsigned Bytes, int Dist,
7772                             SelectionDAG &DAG) {
7773   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7774     EVT VT = LS->getMemoryVT();
7775     SDValue Loc = LS->getBasePtr();
7776     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7777   }
7778
7779   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7780     EVT VT;
7781     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7782     default: return false;
7783     case Intrinsic::ppc_altivec_lvx:
7784     case Intrinsic::ppc_altivec_lvxl:
7785     case Intrinsic::ppc_vsx_lxvw4x:
7786       VT = MVT::v4i32;
7787       break;
7788     case Intrinsic::ppc_vsx_lxvd2x:
7789       VT = MVT::v2f64;
7790       break;
7791     case Intrinsic::ppc_altivec_lvebx:
7792       VT = MVT::i8;
7793       break;
7794     case Intrinsic::ppc_altivec_lvehx:
7795       VT = MVT::i16;
7796       break;
7797     case Intrinsic::ppc_altivec_lvewx:
7798       VT = MVT::i32;
7799       break;
7800     }
7801
7802     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7803   }
7804
7805   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7806     EVT VT;
7807     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7808     default: return false;
7809     case Intrinsic::ppc_altivec_stvx:
7810     case Intrinsic::ppc_altivec_stvxl:
7811     case Intrinsic::ppc_vsx_stxvw4x:
7812       VT = MVT::v4i32;
7813       break;
7814     case Intrinsic::ppc_vsx_stxvd2x:
7815       VT = MVT::v2f64;
7816       break;
7817     case Intrinsic::ppc_altivec_stvebx:
7818       VT = MVT::i8;
7819       break;
7820     case Intrinsic::ppc_altivec_stvehx:
7821       VT = MVT::i16;
7822       break;
7823     case Intrinsic::ppc_altivec_stvewx:
7824       VT = MVT::i32;
7825       break;
7826     }
7827
7828     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7829   }
7830
7831   return false;
7832 }
7833
7834 // Return true is there is a nearyby consecutive load to the one provided
7835 // (regardless of alignment). We search up and down the chain, looking though
7836 // token factors and other loads (but nothing else). As a result, a true result
7837 // indicates that it is safe to create a new consecutive load adjacent to the
7838 // load provided.
7839 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7840   SDValue Chain = LD->getChain();
7841   EVT VT = LD->getMemoryVT();
7842
7843   SmallSet<SDNode *, 16> LoadRoots;
7844   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7845   SmallSet<SDNode *, 16> Visited;
7846
7847   // First, search up the chain, branching to follow all token-factor operands.
7848   // If we find a consecutive load, then we're done, otherwise, record all
7849   // nodes just above the top-level loads and token factors.
7850   while (!Queue.empty()) {
7851     SDNode *ChainNext = Queue.pop_back_val();
7852     if (!Visited.insert(ChainNext).second)
7853       continue;
7854
7855     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7856       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7857         return true;
7858
7859       if (!Visited.count(ChainLD->getChain().getNode()))
7860         Queue.push_back(ChainLD->getChain().getNode());
7861     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7862       for (const SDUse &O : ChainNext->ops())
7863         if (!Visited.count(O.getNode()))
7864           Queue.push_back(O.getNode());
7865     } else
7866       LoadRoots.insert(ChainNext);
7867   }
7868
7869   // Second, search down the chain, starting from the top-level nodes recorded
7870   // in the first phase. These top-level nodes are the nodes just above all
7871   // loads and token factors. Starting with their uses, recursively look though
7872   // all loads (just the chain uses) and token factors to find a consecutive
7873   // load.
7874   Visited.clear();
7875   Queue.clear();
7876
7877   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7878        IE = LoadRoots.end(); I != IE; ++I) {
7879     Queue.push_back(*I);
7880        
7881     while (!Queue.empty()) {
7882       SDNode *LoadRoot = Queue.pop_back_val();
7883       if (!Visited.insert(LoadRoot).second)
7884         continue;
7885
7886       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7887         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7888           return true;
7889
7890       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7891            UE = LoadRoot->use_end(); UI != UE; ++UI)
7892         if (((isa<MemSDNode>(*UI) &&
7893             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7894             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7895           Queue.push_back(*UI);
7896     }
7897   }
7898
7899   return false;
7900 }
7901
7902 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7903                                                   DAGCombinerInfo &DCI) const {
7904   SelectionDAG &DAG = DCI.DAG;
7905   SDLoc dl(N);
7906
7907   assert(Subtarget.useCRBits() &&
7908          "Expecting to be tracking CR bits");
7909   // If we're tracking CR bits, we need to be careful that we don't have:
7910   //   trunc(binary-ops(zext(x), zext(y)))
7911   // or
7912   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7913   // such that we're unnecessarily moving things into GPRs when it would be
7914   // better to keep them in CR bits.
7915
7916   // Note that trunc here can be an actual i1 trunc, or can be the effective
7917   // truncation that comes from a setcc or select_cc.
7918   if (N->getOpcode() == ISD::TRUNCATE &&
7919       N->getValueType(0) != MVT::i1)
7920     return SDValue();
7921
7922   if (N->getOperand(0).getValueType() != MVT::i32 &&
7923       N->getOperand(0).getValueType() != MVT::i64)
7924     return SDValue();
7925
7926   if (N->getOpcode() == ISD::SETCC ||
7927       N->getOpcode() == ISD::SELECT_CC) {
7928     // If we're looking at a comparison, then we need to make sure that the
7929     // high bits (all except for the first) don't matter the result.
7930     ISD::CondCode CC =
7931       cast<CondCodeSDNode>(N->getOperand(
7932         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7933     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7934
7935     if (ISD::isSignedIntSetCC(CC)) {
7936       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7937           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7938         return SDValue();
7939     } else if (ISD::isUnsignedIntSetCC(CC)) {
7940       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7941                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7942           !DAG.MaskedValueIsZero(N->getOperand(1),
7943                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7944         return SDValue();
7945     } else {
7946       // This is neither a signed nor an unsigned comparison, just make sure
7947       // that the high bits are equal.
7948       APInt Op1Zero, Op1One;
7949       APInt Op2Zero, Op2One;
7950       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7951       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7952
7953       // We don't really care about what is known about the first bit (if
7954       // anything), so clear it in all masks prior to comparing them.
7955       Op1Zero.clearBit(0); Op1One.clearBit(0);
7956       Op2Zero.clearBit(0); Op2One.clearBit(0);
7957
7958       if (Op1Zero != Op2Zero || Op1One != Op2One)
7959         return SDValue();
7960     }
7961   }
7962
7963   // We now know that the higher-order bits are irrelevant, we just need to
7964   // make sure that all of the intermediate operations are bit operations, and
7965   // all inputs are extensions.
7966   if (N->getOperand(0).getOpcode() != ISD::AND &&
7967       N->getOperand(0).getOpcode() != ISD::OR  &&
7968       N->getOperand(0).getOpcode() != ISD::XOR &&
7969       N->getOperand(0).getOpcode() != ISD::SELECT &&
7970       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7971       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7972       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7973       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7974       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7975     return SDValue();
7976
7977   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7978       N->getOperand(1).getOpcode() != ISD::AND &&
7979       N->getOperand(1).getOpcode() != ISD::OR  &&
7980       N->getOperand(1).getOpcode() != ISD::XOR &&
7981       N->getOperand(1).getOpcode() != ISD::SELECT &&
7982       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7983       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7984       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7985       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7986       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7987     return SDValue();
7988
7989   SmallVector<SDValue, 4> Inputs;
7990   SmallVector<SDValue, 8> BinOps, PromOps;
7991   SmallPtrSet<SDNode *, 16> Visited;
7992
7993   for (unsigned i = 0; i < 2; ++i) {
7994     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7995           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7996           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7997           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7998         isa<ConstantSDNode>(N->getOperand(i)))
7999       Inputs.push_back(N->getOperand(i));
8000     else
8001       BinOps.push_back(N->getOperand(i));
8002
8003     if (N->getOpcode() == ISD::TRUNCATE)
8004       break;
8005   }
8006
8007   // Visit all inputs, collect all binary operations (and, or, xor and
8008   // select) that are all fed by extensions. 
8009   while (!BinOps.empty()) {
8010     SDValue BinOp = BinOps.back();
8011     BinOps.pop_back();
8012
8013     if (!Visited.insert(BinOp.getNode()).second)
8014       continue;
8015
8016     PromOps.push_back(BinOp);
8017
8018     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8019       // The condition of the select is not promoted.
8020       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8021         continue;
8022       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8023         continue;
8024
8025       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8026             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8027             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8028            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8029           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8030         Inputs.push_back(BinOp.getOperand(i)); 
8031       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8032                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8033                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8034                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8035                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8036                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8037                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8038                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8039                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8040         BinOps.push_back(BinOp.getOperand(i));
8041       } else {
8042         // We have an input that is not an extension or another binary
8043         // operation; we'll abort this transformation.
8044         return SDValue();
8045       }
8046     }
8047   }
8048
8049   // Make sure that this is a self-contained cluster of operations (which
8050   // is not quite the same thing as saying that everything has only one
8051   // use).
8052   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8053     if (isa<ConstantSDNode>(Inputs[i]))
8054       continue;
8055
8056     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8057                               UE = Inputs[i].getNode()->use_end();
8058          UI != UE; ++UI) {
8059       SDNode *User = *UI;
8060       if (User != N && !Visited.count(User))
8061         return SDValue();
8062
8063       // Make sure that we're not going to promote the non-output-value
8064       // operand(s) or SELECT or SELECT_CC.
8065       // FIXME: Although we could sometimes handle this, and it does occur in
8066       // practice that one of the condition inputs to the select is also one of
8067       // the outputs, we currently can't deal with this.
8068       if (User->getOpcode() == ISD::SELECT) {
8069         if (User->getOperand(0) == Inputs[i])
8070           return SDValue();
8071       } else if (User->getOpcode() == ISD::SELECT_CC) {
8072         if (User->getOperand(0) == Inputs[i] ||
8073             User->getOperand(1) == Inputs[i])
8074           return SDValue();
8075       }
8076     }
8077   }
8078
8079   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8080     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8081                               UE = PromOps[i].getNode()->use_end();
8082          UI != UE; ++UI) {
8083       SDNode *User = *UI;
8084       if (User != N && !Visited.count(User))
8085         return SDValue();
8086
8087       // Make sure that we're not going to promote the non-output-value
8088       // operand(s) or SELECT or SELECT_CC.
8089       // FIXME: Although we could sometimes handle this, and it does occur in
8090       // practice that one of the condition inputs to the select is also one of
8091       // the outputs, we currently can't deal with this.
8092       if (User->getOpcode() == ISD::SELECT) {
8093         if (User->getOperand(0) == PromOps[i])
8094           return SDValue();
8095       } else if (User->getOpcode() == ISD::SELECT_CC) {
8096         if (User->getOperand(0) == PromOps[i] ||
8097             User->getOperand(1) == PromOps[i])
8098           return SDValue();
8099       }
8100     }
8101   }
8102
8103   // Replace all inputs with the extension operand.
8104   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8105     // Constants may have users outside the cluster of to-be-promoted nodes,
8106     // and so we need to replace those as we do the promotions.
8107     if (isa<ConstantSDNode>(Inputs[i]))
8108       continue;
8109     else
8110       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
8111   }
8112
8113   // Replace all operations (these are all the same, but have a different
8114   // (i1) return type). DAG.getNode will validate that the types of
8115   // a binary operator match, so go through the list in reverse so that
8116   // we've likely promoted both operands first. Any intermediate truncations or
8117   // extensions disappear.
8118   while (!PromOps.empty()) {
8119     SDValue PromOp = PromOps.back();
8120     PromOps.pop_back();
8121
8122     if (PromOp.getOpcode() == ISD::TRUNCATE ||
8123         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8124         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8125         PromOp.getOpcode() == ISD::ANY_EXTEND) {
8126       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8127           PromOp.getOperand(0).getValueType() != MVT::i1) {
8128         // The operand is not yet ready (see comment below).
8129         PromOps.insert(PromOps.begin(), PromOp);
8130         continue;
8131       }
8132
8133       SDValue RepValue = PromOp.getOperand(0);
8134       if (isa<ConstantSDNode>(RepValue))
8135         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8136
8137       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8138       continue;
8139     }
8140
8141     unsigned C;
8142     switch (PromOp.getOpcode()) {
8143     default:             C = 0; break;
8144     case ISD::SELECT:    C = 1; break;
8145     case ISD::SELECT_CC: C = 2; break;
8146     }
8147
8148     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8149          PromOp.getOperand(C).getValueType() != MVT::i1) ||
8150         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8151          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8152       // The to-be-promoted operands of this node have not yet been
8153       // promoted (this should be rare because we're going through the
8154       // list backward, but if one of the operands has several users in
8155       // this cluster of to-be-promoted nodes, it is possible).
8156       PromOps.insert(PromOps.begin(), PromOp);
8157       continue;
8158     }
8159
8160     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8161                                 PromOp.getNode()->op_end());
8162
8163     // If there are any constant inputs, make sure they're replaced now.
8164     for (unsigned i = 0; i < 2; ++i)
8165       if (isa<ConstantSDNode>(Ops[C+i]))
8166         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8167
8168     DAG.ReplaceAllUsesOfValueWith(PromOp,
8169       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8170   }
8171
8172   // Now we're left with the initial truncation itself.
8173   if (N->getOpcode() == ISD::TRUNCATE)
8174     return N->getOperand(0);
8175
8176   // Otherwise, this is a comparison. The operands to be compared have just
8177   // changed type (to i1), but everything else is the same.
8178   return SDValue(N, 0);
8179 }
8180
8181 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8182                                                   DAGCombinerInfo &DCI) const {
8183   SelectionDAG &DAG = DCI.DAG;
8184   SDLoc dl(N);
8185
8186   // If we're tracking CR bits, we need to be careful that we don't have:
8187   //   zext(binary-ops(trunc(x), trunc(y)))
8188   // or
8189   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8190   // such that we're unnecessarily moving things into CR bits that can more
8191   // efficiently stay in GPRs. Note that if we're not certain that the high
8192   // bits are set as required by the final extension, we still may need to do
8193   // some masking to get the proper behavior.
8194
8195   // This same functionality is important on PPC64 when dealing with
8196   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8197   // the return values of functions. Because it is so similar, it is handled
8198   // here as well.
8199
8200   if (N->getValueType(0) != MVT::i32 &&
8201       N->getValueType(0) != MVT::i64)
8202     return SDValue();
8203
8204   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8205         Subtarget.useCRBits()) ||
8206        (N->getOperand(0).getValueType() == MVT::i32 &&
8207         Subtarget.isPPC64())))
8208     return SDValue();
8209
8210   if (N->getOperand(0).getOpcode() != ISD::AND &&
8211       N->getOperand(0).getOpcode() != ISD::OR  &&
8212       N->getOperand(0).getOpcode() != ISD::XOR &&
8213       N->getOperand(0).getOpcode() != ISD::SELECT &&
8214       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8215     return SDValue();
8216
8217   SmallVector<SDValue, 4> Inputs;
8218   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8219   SmallPtrSet<SDNode *, 16> Visited;
8220
8221   // Visit all inputs, collect all binary operations (and, or, xor and
8222   // select) that are all fed by truncations. 
8223   while (!BinOps.empty()) {
8224     SDValue BinOp = BinOps.back();
8225     BinOps.pop_back();
8226
8227     if (!Visited.insert(BinOp.getNode()).second)
8228       continue;
8229
8230     PromOps.push_back(BinOp);
8231
8232     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8233       // The condition of the select is not promoted.
8234       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8235         continue;
8236       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8237         continue;
8238
8239       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8240           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8241         Inputs.push_back(BinOp.getOperand(i)); 
8242       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8243                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8244                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8245                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8246                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8247         BinOps.push_back(BinOp.getOperand(i));
8248       } else {
8249         // We have an input that is not a truncation or another binary
8250         // operation; we'll abort this transformation.
8251         return SDValue();
8252       }
8253     }
8254   }
8255
8256   // The operands of a select that must be truncated when the select is
8257   // promoted because the operand is actually part of the to-be-promoted set.
8258   DenseMap<SDNode *, EVT> SelectTruncOp[2];
8259
8260   // Make sure that this is a self-contained cluster of operations (which
8261   // is not quite the same thing as saying that everything has only one
8262   // use).
8263   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8264     if (isa<ConstantSDNode>(Inputs[i]))
8265       continue;
8266
8267     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8268                               UE = Inputs[i].getNode()->use_end();
8269          UI != UE; ++UI) {
8270       SDNode *User = *UI;
8271       if (User != N && !Visited.count(User))
8272         return SDValue();
8273
8274       // If we're going to promote the non-output-value operand(s) or SELECT or
8275       // SELECT_CC, record them for truncation.
8276       if (User->getOpcode() == ISD::SELECT) {
8277         if (User->getOperand(0) == Inputs[i])
8278           SelectTruncOp[0].insert(std::make_pair(User,
8279                                     User->getOperand(0).getValueType()));
8280       } else if (User->getOpcode() == ISD::SELECT_CC) {
8281         if (User->getOperand(0) == Inputs[i])
8282           SelectTruncOp[0].insert(std::make_pair(User,
8283                                     User->getOperand(0).getValueType()));
8284         if (User->getOperand(1) == Inputs[i])
8285           SelectTruncOp[1].insert(std::make_pair(User,
8286                                     User->getOperand(1).getValueType()));
8287       }
8288     }
8289   }
8290
8291   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8292     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8293                               UE = PromOps[i].getNode()->use_end();
8294          UI != UE; ++UI) {
8295       SDNode *User = *UI;
8296       if (User != N && !Visited.count(User))
8297         return SDValue();
8298
8299       // If we're going to promote the non-output-value operand(s) or SELECT or
8300       // SELECT_CC, record them for truncation.
8301       if (User->getOpcode() == ISD::SELECT) {
8302         if (User->getOperand(0) == PromOps[i])
8303           SelectTruncOp[0].insert(std::make_pair(User,
8304                                     User->getOperand(0).getValueType()));
8305       } else if (User->getOpcode() == ISD::SELECT_CC) {
8306         if (User->getOperand(0) == PromOps[i])
8307           SelectTruncOp[0].insert(std::make_pair(User,
8308                                     User->getOperand(0).getValueType()));
8309         if (User->getOperand(1) == PromOps[i])
8310           SelectTruncOp[1].insert(std::make_pair(User,
8311                                     User->getOperand(1).getValueType()));
8312       }
8313     }
8314   }
8315
8316   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8317   bool ReallyNeedsExt = false;
8318   if (N->getOpcode() != ISD::ANY_EXTEND) {
8319     // If all of the inputs are not already sign/zero extended, then
8320     // we'll still need to do that at the end.
8321     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8322       if (isa<ConstantSDNode>(Inputs[i]))
8323         continue;
8324
8325       unsigned OpBits =
8326         Inputs[i].getOperand(0).getValueSizeInBits();
8327       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8328
8329       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8330            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8331                                   APInt::getHighBitsSet(OpBits,
8332                                                         OpBits-PromBits))) ||
8333           (N->getOpcode() == ISD::SIGN_EXTEND &&
8334            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8335              (OpBits-(PromBits-1)))) {
8336         ReallyNeedsExt = true;
8337         break;
8338       }
8339     }
8340   }
8341
8342   // Replace all inputs, either with the truncation operand, or a
8343   // truncation or extension to the final output type.
8344   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8345     // Constant inputs need to be replaced with the to-be-promoted nodes that
8346     // use them because they might have users outside of the cluster of
8347     // promoted nodes.
8348     if (isa<ConstantSDNode>(Inputs[i]))
8349       continue;
8350
8351     SDValue InSrc = Inputs[i].getOperand(0);
8352     if (Inputs[i].getValueType() == N->getValueType(0))
8353       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8354     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8355       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8356         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8357     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8358       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8359         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8360     else
8361       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8362         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8363   }
8364
8365   // Replace all operations (these are all the same, but have a different
8366   // (promoted) return type). DAG.getNode will validate that the types of
8367   // a binary operator match, so go through the list in reverse so that
8368   // we've likely promoted both operands first.
8369   while (!PromOps.empty()) {
8370     SDValue PromOp = PromOps.back();
8371     PromOps.pop_back();
8372
8373     unsigned C;
8374     switch (PromOp.getOpcode()) {
8375     default:             C = 0; break;
8376     case ISD::SELECT:    C = 1; break;
8377     case ISD::SELECT_CC: C = 2; break;
8378     }
8379
8380     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8381          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8382         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8383          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8384       // The to-be-promoted operands of this node have not yet been
8385       // promoted (this should be rare because we're going through the
8386       // list backward, but if one of the operands has several users in
8387       // this cluster of to-be-promoted nodes, it is possible).
8388       PromOps.insert(PromOps.begin(), PromOp);
8389       continue;
8390     }
8391
8392     // For SELECT and SELECT_CC nodes, we do a similar check for any
8393     // to-be-promoted comparison inputs.
8394     if (PromOp.getOpcode() == ISD::SELECT ||
8395         PromOp.getOpcode() == ISD::SELECT_CC) {
8396       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8397            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8398           (SelectTruncOp[1].count(PromOp.getNode()) &&
8399            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8400         PromOps.insert(PromOps.begin(), PromOp);
8401         continue;
8402       }
8403     }
8404
8405     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8406                                 PromOp.getNode()->op_end());
8407
8408     // If this node has constant inputs, then they'll need to be promoted here.
8409     for (unsigned i = 0; i < 2; ++i) {
8410       if (!isa<ConstantSDNode>(Ops[C+i]))
8411         continue;
8412       if (Ops[C+i].getValueType() == N->getValueType(0))
8413         continue;
8414
8415       if (N->getOpcode() == ISD::SIGN_EXTEND)
8416         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8417       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8418         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8419       else
8420         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8421     }
8422
8423     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8424     // truncate them again to the original value type.
8425     if (PromOp.getOpcode() == ISD::SELECT ||
8426         PromOp.getOpcode() == ISD::SELECT_CC) {
8427       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8428       if (SI0 != SelectTruncOp[0].end())
8429         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8430       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8431       if (SI1 != SelectTruncOp[1].end())
8432         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8433     }
8434
8435     DAG.ReplaceAllUsesOfValueWith(PromOp,
8436       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8437   }
8438
8439   // Now we're left with the initial extension itself.
8440   if (!ReallyNeedsExt)
8441     return N->getOperand(0);
8442
8443   // To zero extend, just mask off everything except for the first bit (in the
8444   // i1 case).
8445   if (N->getOpcode() == ISD::ZERO_EXTEND)
8446     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8447                        DAG.getConstant(APInt::getLowBitsSet(
8448                                          N->getValueSizeInBits(0), PromBits),
8449                                        N->getValueType(0)));
8450
8451   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8452          "Invalid extension type");
8453   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8454   SDValue ShiftCst =
8455     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8456   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8457                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8458                                  N->getOperand(0), ShiftCst), ShiftCst);
8459 }
8460
8461 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8462                                               DAGCombinerInfo &DCI) const {
8463   assert((N->getOpcode() == ISD::SINT_TO_FP ||
8464           N->getOpcode() == ISD::UINT_TO_FP) &&
8465          "Need an int -> FP conversion node here");
8466
8467   if (!Subtarget.has64BitSupport())
8468     return SDValue();
8469
8470   SelectionDAG &DAG = DCI.DAG;
8471   SDLoc dl(N);
8472   SDValue Op(N, 0);
8473
8474   // Don't handle ppc_fp128 here or i1 conversions.
8475   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8476     return SDValue();
8477   if (Op.getOperand(0).getValueType() == MVT::i1)
8478     return SDValue();
8479
8480   // For i32 intermediate values, unfortunately, the conversion functions
8481   // leave the upper 32 bits of the value are undefined. Within the set of
8482   // scalar instructions, we have no method for zero- or sign-extending the
8483   // value. Thus, we cannot handle i32 intermediate values here.
8484   if (Op.getOperand(0).getValueType() == MVT::i32)
8485     return SDValue();
8486
8487   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8488          "UINT_TO_FP is supported only with FPCVT");
8489
8490   // If we have FCFIDS, then use it when converting to single-precision.
8491   // Otherwise, convert to double-precision and then round.
8492   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8493                    (Op.getOpcode() == ISD::UINT_TO_FP ?
8494                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
8495                    (Op.getOpcode() == ISD::UINT_TO_FP ?
8496                     PPCISD::FCFIDU : PPCISD::FCFID);
8497   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8498                    MVT::f32 : MVT::f64;
8499
8500   // If we're converting from a float, to an int, and back to a float again,
8501   // then we don't need the store/load pair at all.
8502   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8503        Subtarget.hasFPCVT()) ||
8504       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8505     SDValue Src = Op.getOperand(0).getOperand(0);
8506     if (Src.getValueType() == MVT::f32) {
8507       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8508       DCI.AddToWorklist(Src.getNode());
8509     }
8510
8511     unsigned FCTOp =
8512       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8513                                                         PPCISD::FCTIDUZ;
8514
8515     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8516     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8517
8518     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8519       FP = DAG.getNode(ISD::FP_ROUND, dl,
8520                        MVT::f32, FP, DAG.getIntPtrConstant(0));
8521       DCI.AddToWorklist(FP.getNode());
8522     }
8523
8524     return FP;
8525   }
8526
8527   return SDValue();
8528 }
8529
8530 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8531 // builtins) into loads with swaps.
8532 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8533                                               DAGCombinerInfo &DCI) const {
8534   SelectionDAG &DAG = DCI.DAG;
8535   SDLoc dl(N);
8536   SDValue Chain;
8537   SDValue Base;
8538   MachineMemOperand *MMO;
8539
8540   switch (N->getOpcode()) {
8541   default:
8542     llvm_unreachable("Unexpected opcode for little endian VSX load");
8543   case ISD::LOAD: {
8544     LoadSDNode *LD = cast<LoadSDNode>(N);
8545     Chain = LD->getChain();
8546     Base = LD->getBasePtr();
8547     MMO = LD->getMemOperand();
8548     // If the MMO suggests this isn't a load of a full vector, leave
8549     // things alone.  For a built-in, we have to make the change for
8550     // correctness, so if there is a size problem that will be a bug.
8551     if (MMO->getSize() < 16)
8552       return SDValue();
8553     break;
8554   }
8555   case ISD::INTRINSIC_W_CHAIN: {
8556     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8557     Chain = Intrin->getChain();
8558     Base = Intrin->getBasePtr();
8559     MMO = Intrin->getMemOperand();
8560     break;
8561   }
8562   }
8563
8564   MVT VecTy = N->getValueType(0).getSimpleVT();
8565   SDValue LoadOps[] = { Chain, Base };
8566   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8567                                          DAG.getVTList(VecTy, MVT::Other),
8568                                          LoadOps, VecTy, MMO);
8569   DCI.AddToWorklist(Load.getNode());
8570   Chain = Load.getValue(1);
8571   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8572                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8573   DCI.AddToWorklist(Swap.getNode());
8574   return Swap;
8575 }
8576
8577 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8578 // builtins) into stores with swaps.
8579 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8580                                                DAGCombinerInfo &DCI) const {
8581   SelectionDAG &DAG = DCI.DAG;
8582   SDLoc dl(N);
8583   SDValue Chain;
8584   SDValue Base;
8585   unsigned SrcOpnd;
8586   MachineMemOperand *MMO;
8587
8588   switch (N->getOpcode()) {
8589   default:
8590     llvm_unreachable("Unexpected opcode for little endian VSX store");
8591   case ISD::STORE: {
8592     StoreSDNode *ST = cast<StoreSDNode>(N);
8593     Chain = ST->getChain();
8594     Base = ST->getBasePtr();
8595     MMO = ST->getMemOperand();
8596     SrcOpnd = 1;
8597     // If the MMO suggests this isn't a store of a full vector, leave
8598     // things alone.  For a built-in, we have to make the change for
8599     // correctness, so if there is a size problem that will be a bug.
8600     if (MMO->getSize() < 16)
8601       return SDValue();
8602     break;
8603   }
8604   case ISD::INTRINSIC_VOID: {
8605     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8606     Chain = Intrin->getChain();
8607     // Intrin->getBasePtr() oddly does not get what we want.
8608     Base = Intrin->getOperand(3);
8609     MMO = Intrin->getMemOperand();
8610     SrcOpnd = 2;
8611     break;
8612   }
8613   }
8614
8615   SDValue Src = N->getOperand(SrcOpnd);
8616   MVT VecTy = Src.getValueType().getSimpleVT();
8617   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8618                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8619   DCI.AddToWorklist(Swap.getNode());
8620   Chain = Swap.getValue(1);
8621   SDValue StoreOps[] = { Chain, Swap, Base };
8622   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8623                                           DAG.getVTList(MVT::Other),
8624                                           StoreOps, VecTy, MMO);
8625   DCI.AddToWorklist(Store.getNode());
8626   return Store;
8627 }
8628
8629 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8630                                              DAGCombinerInfo &DCI) const {
8631   const TargetMachine &TM = getTargetMachine();
8632   SelectionDAG &DAG = DCI.DAG;
8633   SDLoc dl(N);
8634   switch (N->getOpcode()) {
8635   default: break;
8636   case PPCISD::SHL:
8637     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8638       if (C->isNullValue())   // 0 << V -> 0.
8639         return N->getOperand(0);
8640     }
8641     break;
8642   case PPCISD::SRL:
8643     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8644       if (C->isNullValue())   // 0 >>u V -> 0.
8645         return N->getOperand(0);
8646     }
8647     break;
8648   case PPCISD::SRA:
8649     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8650       if (C->isNullValue() ||   //  0 >>s V -> 0.
8651           C->isAllOnesValue())    // -1 >>s V -> -1.
8652         return N->getOperand(0);
8653     }
8654     break;
8655   case ISD::SIGN_EXTEND:
8656   case ISD::ZERO_EXTEND:
8657   case ISD::ANY_EXTEND: 
8658     return DAGCombineExtBoolTrunc(N, DCI);
8659   case ISD::TRUNCATE:
8660   case ISD::SETCC:
8661   case ISD::SELECT_CC:
8662     return DAGCombineTruncBoolExt(N, DCI);
8663   case ISD::SINT_TO_FP:
8664   case ISD::UINT_TO_FP:
8665     return combineFPToIntToFP(N, DCI);
8666   case ISD::STORE: {
8667     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8668     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8669         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8670         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8671         N->getOperand(1).getValueType() == MVT::i32 &&
8672         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8673       SDValue Val = N->getOperand(1).getOperand(0);
8674       if (Val.getValueType() == MVT::f32) {
8675         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8676         DCI.AddToWorklist(Val.getNode());
8677       }
8678       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8679       DCI.AddToWorklist(Val.getNode());
8680
8681       SDValue Ops[] = {
8682         N->getOperand(0), Val, N->getOperand(2),
8683         DAG.getValueType(N->getOperand(1).getValueType())
8684       };
8685
8686       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8687               DAG.getVTList(MVT::Other), Ops,
8688               cast<StoreSDNode>(N)->getMemoryVT(),
8689               cast<StoreSDNode>(N)->getMemOperand());
8690       DCI.AddToWorklist(Val.getNode());
8691       return Val;
8692     }
8693
8694     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8695     if (cast<StoreSDNode>(N)->isUnindexed() &&
8696         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8697         N->getOperand(1).getNode()->hasOneUse() &&
8698         (N->getOperand(1).getValueType() == MVT::i32 ||
8699          N->getOperand(1).getValueType() == MVT::i16 ||
8700          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8701           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8702           N->getOperand(1).getValueType() == MVT::i64))) {
8703       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8704       // Do an any-extend to 32-bits if this is a half-word input.
8705       if (BSwapOp.getValueType() == MVT::i16)
8706         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8707
8708       SDValue Ops[] = {
8709         N->getOperand(0), BSwapOp, N->getOperand(2),
8710         DAG.getValueType(N->getOperand(1).getValueType())
8711       };
8712       return
8713         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8714                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8715                                 cast<StoreSDNode>(N)->getMemOperand());
8716     }
8717
8718     // For little endian, VSX stores require generating xxswapd/lxvd2x.
8719     EVT VT = N->getOperand(1).getValueType();
8720     if (VT.isSimple()) {
8721       MVT StoreVT = VT.getSimpleVT();
8722       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8723           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8724           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8725            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8726         return expandVSXStoreForLE(N, DCI);
8727     }
8728     break;
8729   }
8730   case ISD::LOAD: {
8731     LoadSDNode *LD = cast<LoadSDNode>(N);
8732     EVT VT = LD->getValueType(0);
8733
8734     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8735     if (VT.isSimple()) {
8736       MVT LoadVT = VT.getSimpleVT();
8737       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8738           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8739           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8740            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8741         return expandVSXLoadForLE(N, DCI);
8742     }
8743
8744     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8745     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8746     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8747         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8748         // P8 and later hardware should just use LOAD.
8749         !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8750         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8751          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8752         LD->getAlignment() < ABIAlignment) {
8753       // This is a type-legal unaligned Altivec load.
8754       SDValue Chain = LD->getChain();
8755       SDValue Ptr = LD->getBasePtr();
8756       bool isLittleEndian = Subtarget.isLittleEndian();
8757
8758       // This implements the loading of unaligned vectors as described in
8759       // the venerable Apple Velocity Engine overview. Specifically:
8760       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8761       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8762       //
8763       // The general idea is to expand a sequence of one or more unaligned
8764       // loads into an alignment-based permutation-control instruction (lvsl
8765       // or lvsr), a series of regular vector loads (which always truncate
8766       // their input address to an aligned address), and a series of
8767       // permutations.  The results of these permutations are the requested
8768       // loaded values.  The trick is that the last "extra" load is not taken
8769       // from the address you might suspect (sizeof(vector) bytes after the
8770       // last requested load), but rather sizeof(vector) - 1 bytes after the
8771       // last requested vector. The point of this is to avoid a page fault if
8772       // the base address happened to be aligned. This works because if the
8773       // base address is aligned, then adding less than a full vector length
8774       // will cause the last vector in the sequence to be (re)loaded.
8775       // Otherwise, the next vector will be fetched as you might suspect was
8776       // necessary.
8777
8778       // We might be able to reuse the permutation generation from
8779       // a different base address offset from this one by an aligned amount.
8780       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8781       // optimization later.
8782       Intrinsic::ID Intr = (isLittleEndian ?
8783                             Intrinsic::ppc_altivec_lvsr :
8784                             Intrinsic::ppc_altivec_lvsl);
8785       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8786
8787       // Create the new MMO for the new base load. It is like the original MMO,
8788       // but represents an area in memory almost twice the vector size centered
8789       // on the original address. If the address is unaligned, we might start
8790       // reading up to (sizeof(vector)-1) bytes below the address of the
8791       // original unaligned load.
8792       MachineFunction &MF = DAG.getMachineFunction();
8793       MachineMemOperand *BaseMMO =
8794         MF.getMachineMemOperand(LD->getMemOperand(),
8795                                 -LD->getMemoryVT().getStoreSize()+1,
8796                                 2*LD->getMemoryVT().getStoreSize()-1);
8797
8798       // Create the new base load.
8799       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8800                                                getPointerTy());
8801       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8802       SDValue BaseLoad =
8803         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8804                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8805                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8806
8807       // Note that the value of IncOffset (which is provided to the next
8808       // load's pointer info offset value, and thus used to calculate the
8809       // alignment), and the value of IncValue (which is actually used to
8810       // increment the pointer value) are different! This is because we
8811       // require the next load to appear to be aligned, even though it
8812       // is actually offset from the base pointer by a lesser amount.
8813       int IncOffset = VT.getSizeInBits() / 8;
8814       int IncValue = IncOffset;
8815
8816       // Walk (both up and down) the chain looking for another load at the real
8817       // (aligned) offset (the alignment of the other load does not matter in
8818       // this case). If found, then do not use the offset reduction trick, as
8819       // that will prevent the loads from being later combined (as they would
8820       // otherwise be duplicates).
8821       if (!findConsecutiveLoad(LD, DAG))
8822         --IncValue;
8823
8824       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8825       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8826
8827       MachineMemOperand *ExtraMMO =
8828         MF.getMachineMemOperand(LD->getMemOperand(),
8829                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
8830       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8831       SDValue ExtraLoad =
8832         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8833                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8834                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8835
8836       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8837         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8838
8839       // Because vperm has a big-endian bias, we must reverse the order
8840       // of the input vectors and complement the permute control vector
8841       // when generating little endian code.  We have already handled the
8842       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8843       // and ExtraLoad here.
8844       SDValue Perm;
8845       if (isLittleEndian)
8846         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8847                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8848       else
8849         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8850                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8851
8852       if (VT != MVT::v4i32)
8853         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8854
8855       // The output of the permutation is our loaded result, the TokenFactor is
8856       // our new chain.
8857       DCI.CombineTo(N, Perm, TF);
8858       return SDValue(N, 0);
8859     }
8860     }
8861     break;
8862   case ISD::INTRINSIC_WO_CHAIN: {
8863     bool isLittleEndian = Subtarget.isLittleEndian();
8864     Intrinsic::ID Intr = (isLittleEndian ?
8865                           Intrinsic::ppc_altivec_lvsr :
8866                           Intrinsic::ppc_altivec_lvsl);
8867     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8868         N->getOperand(1)->getOpcode() == ISD::ADD) {
8869       SDValue Add = N->getOperand(1);
8870
8871       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8872             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8873               Add.getValueType().getScalarType().getSizeInBits()))) {
8874         SDNode *BasePtr = Add->getOperand(0).getNode();
8875         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8876              UE = BasePtr->use_end(); UI != UE; ++UI) {
8877           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8878               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8879                 Intr) {
8880             // We've found another LVSL/LVSR, and this address is an aligned
8881             // multiple of that one. The results will be the same, so use the
8882             // one we've just found instead.
8883
8884             return SDValue(*UI, 0);
8885           }
8886         }
8887       }
8888     }
8889     }
8890
8891     break;
8892   case ISD::INTRINSIC_W_CHAIN: {
8893     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8894     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8895         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8896       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8897       default:
8898         break;
8899       case Intrinsic::ppc_vsx_lxvw4x:
8900       case Intrinsic::ppc_vsx_lxvd2x:
8901         return expandVSXLoadForLE(N, DCI);
8902       }
8903     }
8904     break;
8905   }
8906   case ISD::INTRINSIC_VOID: {
8907     // For little endian, VSX stores require generating xxswapd/stxvd2x.
8908     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8909         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8910       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8911       default:
8912         break;
8913       case Intrinsic::ppc_vsx_stxvw4x:
8914       case Intrinsic::ppc_vsx_stxvd2x:
8915         return expandVSXStoreForLE(N, DCI);
8916       }
8917     }
8918     break;
8919   }
8920   case ISD::BSWAP:
8921     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8922     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8923         N->getOperand(0).hasOneUse() &&
8924         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8925          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8926           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8927           N->getValueType(0) == MVT::i64))) {
8928       SDValue Load = N->getOperand(0);
8929       LoadSDNode *LD = cast<LoadSDNode>(Load);
8930       // Create the byte-swapping load.
8931       SDValue Ops[] = {
8932         LD->getChain(),    // Chain
8933         LD->getBasePtr(),  // Ptr
8934         DAG.getValueType(N->getValueType(0)) // VT
8935       };
8936       SDValue BSLoad =
8937         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8938                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8939                                               MVT::i64 : MVT::i32, MVT::Other),
8940                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8941
8942       // If this is an i16 load, insert the truncate.
8943       SDValue ResVal = BSLoad;
8944       if (N->getValueType(0) == MVT::i16)
8945         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8946
8947       // First, combine the bswap away.  This makes the value produced by the
8948       // load dead.
8949       DCI.CombineTo(N, ResVal);
8950
8951       // Next, combine the load away, we give it a bogus result value but a real
8952       // chain result.  The result value is dead because the bswap is dead.
8953       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8954
8955       // Return N so it doesn't get rechecked!
8956       return SDValue(N, 0);
8957     }
8958
8959     break;
8960   case PPCISD::VCMP: {
8961     // If a VCMPo node already exists with exactly the same operands as this
8962     // node, use its result instead of this node (VCMPo computes both a CR6 and
8963     // a normal output).
8964     //
8965     if (!N->getOperand(0).hasOneUse() &&
8966         !N->getOperand(1).hasOneUse() &&
8967         !N->getOperand(2).hasOneUse()) {
8968
8969       // Scan all of the users of the LHS, looking for VCMPo's that match.
8970       SDNode *VCMPoNode = nullptr;
8971
8972       SDNode *LHSN = N->getOperand(0).getNode();
8973       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8974            UI != E; ++UI)
8975         if (UI->getOpcode() == PPCISD::VCMPo &&
8976             UI->getOperand(1) == N->getOperand(1) &&
8977             UI->getOperand(2) == N->getOperand(2) &&
8978             UI->getOperand(0) == N->getOperand(0)) {
8979           VCMPoNode = *UI;
8980           break;
8981         }
8982
8983       // If there is no VCMPo node, or if the flag value has a single use, don't
8984       // transform this.
8985       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8986         break;
8987
8988       // Look at the (necessarily single) use of the flag value.  If it has a
8989       // chain, this transformation is more complex.  Note that multiple things
8990       // could use the value result, which we should ignore.
8991       SDNode *FlagUser = nullptr;
8992       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8993            FlagUser == nullptr; ++UI) {
8994         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8995         SDNode *User = *UI;
8996         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8997           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8998             FlagUser = User;
8999             break;
9000           }
9001         }
9002       }
9003
9004       // If the user is a MFOCRF instruction, we know this is safe.
9005       // Otherwise we give up for right now.
9006       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9007         return SDValue(VCMPoNode, 0);
9008     }
9009     break;
9010   }
9011   case ISD::BRCOND: {
9012     SDValue Cond = N->getOperand(1);
9013     SDValue Target = N->getOperand(2);
9014  
9015     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9016         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9017           Intrinsic::ppc_is_decremented_ctr_nonzero) {
9018
9019       // We now need to make the intrinsic dead (it cannot be instruction
9020       // selected).
9021       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9022       assert(Cond.getNode()->hasOneUse() &&
9023              "Counter decrement has more than one use");
9024
9025       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9026                          N->getOperand(0), Target);
9027     }
9028   }
9029   break;
9030   case ISD::BR_CC: {
9031     // If this is a branch on an altivec predicate comparison, lower this so
9032     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
9033     // lowering is done pre-legalize, because the legalizer lowers the predicate
9034     // compare down to code that is difficult to reassemble.
9035     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9036     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9037
9038     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9039     // value. If so, pass-through the AND to get to the intrinsic.
9040     if (LHS.getOpcode() == ISD::AND &&
9041         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9042         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9043           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9044         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9045         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9046           isZero())
9047       LHS = LHS.getOperand(0);
9048
9049     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9050         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9051           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9052         isa<ConstantSDNode>(RHS)) {
9053       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9054              "Counter decrement comparison is not EQ or NE");
9055
9056       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9057       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9058                     (CC == ISD::SETNE && !Val);
9059
9060       // We now need to make the intrinsic dead (it cannot be instruction
9061       // selected).
9062       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9063       assert(LHS.getNode()->hasOneUse() &&
9064              "Counter decrement has more than one use");
9065
9066       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9067                          N->getOperand(0), N->getOperand(4));
9068     }
9069
9070     int CompareOpc;
9071     bool isDot;
9072
9073     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9074         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9075         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9076       assert(isDot && "Can't compare against a vector result!");
9077
9078       // If this is a comparison against something other than 0/1, then we know
9079       // that the condition is never/always true.
9080       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9081       if (Val != 0 && Val != 1) {
9082         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
9083           return N->getOperand(0);
9084         // Always !=, turn it into an unconditional branch.
9085         return DAG.getNode(ISD::BR, dl, MVT::Other,
9086                            N->getOperand(0), N->getOperand(4));
9087       }
9088
9089       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9090
9091       // Create the PPCISD altivec 'dot' comparison node.
9092       SDValue Ops[] = {
9093         LHS.getOperand(2),  // LHS of compare
9094         LHS.getOperand(3),  // RHS of compare
9095         DAG.getConstant(CompareOpc, MVT::i32)
9096       };
9097       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9098       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9099
9100       // Unpack the result based on how the target uses it.
9101       PPC::Predicate CompOpc;
9102       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9103       default:  // Can't happen, don't crash on invalid number though.
9104       case 0:   // Branch on the value of the EQ bit of CR6.
9105         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9106         break;
9107       case 1:   // Branch on the inverted value of the EQ bit of CR6.
9108         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9109         break;
9110       case 2:   // Branch on the value of the LT bit of CR6.
9111         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9112         break;
9113       case 3:   // Branch on the inverted value of the LT bit of CR6.
9114         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9115         break;
9116       }
9117
9118       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9119                          DAG.getConstant(CompOpc, MVT::i32),
9120                          DAG.getRegister(PPC::CR6, MVT::i32),
9121                          N->getOperand(4), CompNode.getValue(1));
9122     }
9123     break;
9124   }
9125   }
9126
9127   return SDValue();
9128 }
9129
9130 SDValue
9131 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9132                                   SelectionDAG &DAG,
9133                                   std::vector<SDNode *> *Created) const {
9134   // fold (sdiv X, pow2)
9135   EVT VT = N->getValueType(0);
9136   if (VT == MVT::i64 && !Subtarget.isPPC64())
9137     return SDValue();
9138   if ((VT != MVT::i32 && VT != MVT::i64) ||
9139       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9140     return SDValue();
9141
9142   SDLoc DL(N);
9143   SDValue N0 = N->getOperand(0);
9144
9145   bool IsNegPow2 = (-Divisor).isPowerOf2();
9146   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9147   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9148
9149   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9150   if (Created)
9151     Created->push_back(Op.getNode());
9152
9153   if (IsNegPow2) {
9154     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9155     if (Created)
9156       Created->push_back(Op.getNode());
9157   }
9158
9159   return Op;
9160 }
9161
9162 //===----------------------------------------------------------------------===//
9163 // Inline Assembly Support
9164 //===----------------------------------------------------------------------===//
9165
9166 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9167                                                       APInt &KnownZero,
9168                                                       APInt &KnownOne,
9169                                                       const SelectionDAG &DAG,
9170                                                       unsigned Depth) const {
9171   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9172   switch (Op.getOpcode()) {
9173   default: break;
9174   case PPCISD::LBRX: {
9175     // lhbrx is known to have the top bits cleared out.
9176     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9177       KnownZero = 0xFFFF0000;
9178     break;
9179   }
9180   case ISD::INTRINSIC_WO_CHAIN: {
9181     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9182     default: break;
9183     case Intrinsic::ppc_altivec_vcmpbfp_p:
9184     case Intrinsic::ppc_altivec_vcmpeqfp_p:
9185     case Intrinsic::ppc_altivec_vcmpequb_p:
9186     case Intrinsic::ppc_altivec_vcmpequh_p:
9187     case Intrinsic::ppc_altivec_vcmpequw_p:
9188     case Intrinsic::ppc_altivec_vcmpgefp_p:
9189     case Intrinsic::ppc_altivec_vcmpgtfp_p:
9190     case Intrinsic::ppc_altivec_vcmpgtsb_p:
9191     case Intrinsic::ppc_altivec_vcmpgtsh_p:
9192     case Intrinsic::ppc_altivec_vcmpgtsw_p:
9193     case Intrinsic::ppc_altivec_vcmpgtub_p:
9194     case Intrinsic::ppc_altivec_vcmpgtuh_p:
9195     case Intrinsic::ppc_altivec_vcmpgtuw_p:
9196       KnownZero = ~1U;  // All bits but the low one are known to be zero.
9197       break;
9198     }
9199   }
9200   }
9201 }
9202
9203 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9204   switch (Subtarget.getDarwinDirective()) {
9205   default: break;
9206   case PPC::DIR_970:
9207   case PPC::DIR_PWR4:
9208   case PPC::DIR_PWR5:
9209   case PPC::DIR_PWR5X:
9210   case PPC::DIR_PWR6:
9211   case PPC::DIR_PWR6X:
9212   case PPC::DIR_PWR7:
9213   case PPC::DIR_PWR8: {
9214     if (!ML)
9215       break;
9216
9217     const PPCInstrInfo *TII =
9218       static_cast<const PPCInstrInfo *>(getTargetMachine().getSubtargetImpl()->
9219                                           getInstrInfo());
9220
9221     // For small loops (between 5 and 8 instructions), align to a 32-byte
9222     // boundary so that the entire loop fits in one instruction-cache line.
9223     uint64_t LoopSize = 0;
9224     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9225       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9226         LoopSize += TII->GetInstSizeInBytes(J);
9227
9228     if (LoopSize > 16 && LoopSize <= 32)
9229       return 5;
9230
9231     break;
9232   }
9233   }
9234
9235   return TargetLowering::getPrefLoopAlignment(ML);
9236 }
9237
9238 /// getConstraintType - Given a constraint, return the type of
9239 /// constraint it is for this target.
9240 PPCTargetLowering::ConstraintType
9241 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9242   if (Constraint.size() == 1) {
9243     switch (Constraint[0]) {
9244     default: break;
9245     case 'b':
9246     case 'r':
9247     case 'f':
9248     case 'v':
9249     case 'y':
9250       return C_RegisterClass;
9251     case 'Z':
9252       // FIXME: While Z does indicate a memory constraint, it specifically
9253       // indicates an r+r address (used in conjunction with the 'y' modifier
9254       // in the replacement string). Currently, we're forcing the base
9255       // register to be r0 in the asm printer (which is interpreted as zero)
9256       // and forming the complete address in the second register. This is
9257       // suboptimal.
9258       return C_Memory;
9259     }
9260   } else if (Constraint == "wc") { // individual CR bits.
9261     return C_RegisterClass;
9262   } else if (Constraint == "wa" || Constraint == "wd" ||
9263              Constraint == "wf" || Constraint == "ws") {
9264     return C_RegisterClass; // VSX registers.
9265   }
9266   return TargetLowering::getConstraintType(Constraint);
9267 }
9268
9269 /// Examine constraint type and operand type and determine a weight value.
9270 /// This object must already have been set up with the operand type
9271 /// and the current alternative constraint selected.
9272 TargetLowering::ConstraintWeight
9273 PPCTargetLowering::getSingleConstraintMatchWeight(
9274     AsmOperandInfo &info, const char *constraint) const {
9275   ConstraintWeight weight = CW_Invalid;
9276   Value *CallOperandVal = info.CallOperandVal;
9277     // If we don't have a value, we can't do a match,
9278     // but allow it at the lowest weight.
9279   if (!CallOperandVal)
9280     return CW_Default;
9281   Type *type = CallOperandVal->getType();
9282
9283   // Look at the constraint type.
9284   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9285     return CW_Register; // an individual CR bit.
9286   else if ((StringRef(constraint) == "wa" ||
9287             StringRef(constraint) == "wd" ||
9288             StringRef(constraint) == "wf") &&
9289            type->isVectorTy())
9290     return CW_Register;
9291   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9292     return CW_Register;
9293
9294   switch (*constraint) {
9295   default:
9296     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9297     break;
9298   case 'b':
9299     if (type->isIntegerTy())
9300       weight = CW_Register;
9301     break;
9302   case 'f':
9303     if (type->isFloatTy())
9304       weight = CW_Register;
9305     break;
9306   case 'd':
9307     if (type->isDoubleTy())
9308       weight = CW_Register;
9309     break;
9310   case 'v':
9311     if (type->isVectorTy())
9312       weight = CW_Register;
9313     break;
9314   case 'y':
9315     weight = CW_Register;
9316     break;
9317   case 'Z':
9318     weight = CW_Memory;
9319     break;
9320   }
9321   return weight;
9322 }
9323
9324 std::pair<unsigned, const TargetRegisterClass*>
9325 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9326                                                 MVT VT) const {
9327   if (Constraint.size() == 1) {
9328     // GCC RS6000 Constraint Letters
9329     switch (Constraint[0]) {
9330     case 'b':   // R1-R31
9331       if (VT == MVT::i64 && Subtarget.isPPC64())
9332         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9333       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9334     case 'r':   // R0-R31
9335       if (VT == MVT::i64 && Subtarget.isPPC64())
9336         return std::make_pair(0U, &PPC::G8RCRegClass);
9337       return std::make_pair(0U, &PPC::GPRCRegClass);
9338     case 'f':
9339       if (VT == MVT::f32 || VT == MVT::i32)
9340         return std::make_pair(0U, &PPC::F4RCRegClass);
9341       if (VT == MVT::f64 || VT == MVT::i64)
9342         return std::make_pair(0U, &PPC::F8RCRegClass);
9343       break;
9344     case 'v':
9345       return std::make_pair(0U, &PPC::VRRCRegClass);
9346     case 'y':   // crrc
9347       return std::make_pair(0U, &PPC::CRRCRegClass);
9348     }
9349   } else if (Constraint == "wc") { // an individual CR bit.
9350     return std::make_pair(0U, &PPC::CRBITRCRegClass);
9351   } else if (Constraint == "wa" || Constraint == "wd" ||
9352              Constraint == "wf") {
9353     return std::make_pair(0U, &PPC::VSRCRegClass);
9354   } else if (Constraint == "ws") {
9355     return std::make_pair(0U, &PPC::VSFRCRegClass);
9356   }
9357
9358   std::pair<unsigned, const TargetRegisterClass*> R =
9359     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9360
9361   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9362   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9363   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9364   // register.
9365   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9366   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9367   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9368       PPC::GPRCRegClass.contains(R.first)) {
9369     const TargetRegisterInfo *TRI =
9370         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
9371     return std::make_pair(TRI->getMatchingSuperReg(R.first,
9372                             PPC::sub_32, &PPC::G8RCRegClass),
9373                           &PPC::G8RCRegClass);
9374   }
9375
9376   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9377   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9378     R.first = PPC::CR0;
9379     R.second = &PPC::CRRCRegClass;
9380   }
9381
9382   return R;
9383 }
9384
9385
9386 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9387 /// vector.  If it is invalid, don't add anything to Ops.
9388 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9389                                                      std::string &Constraint,
9390                                                      std::vector<SDValue>&Ops,
9391                                                      SelectionDAG &DAG) const {
9392   SDValue Result;
9393
9394   // Only support length 1 constraints.
9395   if (Constraint.length() > 1) return;
9396
9397   char Letter = Constraint[0];
9398   switch (Letter) {
9399   default: break;
9400   case 'I':
9401   case 'J':
9402   case 'K':
9403   case 'L':
9404   case 'M':
9405   case 'N':
9406   case 'O':
9407   case 'P': {
9408     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9409     if (!CST) return; // Must be an immediate to match.
9410     int64_t Value = CST->getSExtValue();
9411     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9412                          // numbers are printed as such.
9413     switch (Letter) {
9414     default: llvm_unreachable("Unknown constraint letter!");
9415     case 'I':  // "I" is a signed 16-bit constant.
9416       if (isInt<16>(Value))
9417         Result = DAG.getTargetConstant(Value, TCVT);
9418       break;
9419     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9420       if (isShiftedUInt<16, 16>(Value))
9421         Result = DAG.getTargetConstant(Value, TCVT);
9422       break;
9423     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9424       if (isShiftedInt<16, 16>(Value))
9425         Result = DAG.getTargetConstant(Value, TCVT);
9426       break;
9427     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9428       if (isUInt<16>(Value))
9429         Result = DAG.getTargetConstant(Value, TCVT);
9430       break;
9431     case 'M':  // "M" is a constant that is greater than 31.
9432       if (Value > 31)
9433         Result = DAG.getTargetConstant(Value, TCVT);
9434       break;
9435     case 'N':  // "N" is a positive constant that is an exact power of two.
9436       if (Value > 0 && isPowerOf2_64(Value))
9437         Result = DAG.getTargetConstant(Value, TCVT);
9438       break;
9439     case 'O':  // "O" is the constant zero.
9440       if (Value == 0)
9441         Result = DAG.getTargetConstant(Value, TCVT);
9442       break;
9443     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9444       if (isInt<16>(-Value))
9445         Result = DAG.getTargetConstant(Value, TCVT);
9446       break;
9447     }
9448     break;
9449   }
9450   }
9451
9452   if (Result.getNode()) {
9453     Ops.push_back(Result);
9454     return;
9455   }
9456
9457   // Handle standard constraint letters.
9458   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9459 }
9460
9461 // isLegalAddressingMode - Return true if the addressing mode represented
9462 // by AM is legal for this target, for a load/store of the specified type.
9463 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9464                                               Type *Ty) const {
9465   // FIXME: PPC does not allow r+i addressing modes for vectors!
9466
9467   // PPC allows a sign-extended 16-bit immediate field.
9468   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9469     return false;
9470
9471   // No global is ever allowed as a base.
9472   if (AM.BaseGV)
9473     return false;
9474
9475   // PPC only support r+r,
9476   switch (AM.Scale) {
9477   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9478     break;
9479   case 1:
9480     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9481       return false;
9482     // Otherwise we have r+r or r+i.
9483     break;
9484   case 2:
9485     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9486       return false;
9487     // Allow 2*r as r+r.
9488     break;
9489   default:
9490     // No other scales are supported.
9491     return false;
9492   }
9493
9494   return true;
9495 }
9496
9497 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9498                                            SelectionDAG &DAG) const {
9499   MachineFunction &MF = DAG.getMachineFunction();
9500   MachineFrameInfo *MFI = MF.getFrameInfo();
9501   MFI->setReturnAddressIsTaken(true);
9502
9503   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9504     return SDValue();
9505
9506   SDLoc dl(Op);
9507   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9508
9509   // Make sure the function does not optimize away the store of the RA to
9510   // the stack.
9511   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9512   FuncInfo->setLRStoreRequired();
9513   bool isPPC64 = Subtarget.isPPC64();
9514   bool isDarwinABI = Subtarget.isDarwinABI();
9515
9516   if (Depth > 0) {
9517     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9518     SDValue Offset =
9519
9520       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9521                       isPPC64? MVT::i64 : MVT::i32);
9522     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9523                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9524                                    FrameAddr, Offset),
9525                        MachinePointerInfo(), false, false, false, 0);
9526   }
9527
9528   // Just load the return address off the stack.
9529   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9530   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9531                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9532 }
9533
9534 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9535                                           SelectionDAG &DAG) const {
9536   SDLoc dl(Op);
9537   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9538
9539   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9540   bool isPPC64 = PtrVT == MVT::i64;
9541
9542   MachineFunction &MF = DAG.getMachineFunction();
9543   MachineFrameInfo *MFI = MF.getFrameInfo();
9544   MFI->setFrameAddressIsTaken(true);
9545
9546   // Naked functions never have a frame pointer, and so we use r1. For all
9547   // other functions, this decision must be delayed until during PEI.
9548   unsigned FrameReg;
9549   if (MF.getFunction()->getAttributes().hasAttribute(
9550         AttributeSet::FunctionIndex, Attribute::Naked))
9551     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9552   else
9553     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9554
9555   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9556                                          PtrVT);
9557   while (Depth--)
9558     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9559                             FrameAddr, MachinePointerInfo(), false, false,
9560                             false, 0);
9561   return FrameAddr;
9562 }
9563
9564 // FIXME? Maybe this could be a TableGen attribute on some registers and
9565 // this table could be generated automatically from RegInfo.
9566 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9567                                               EVT VT) const {
9568   bool isPPC64 = Subtarget.isPPC64();
9569   bool isDarwinABI = Subtarget.isDarwinABI();
9570
9571   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9572       (!isPPC64 && VT != MVT::i32))
9573     report_fatal_error("Invalid register global variable type");
9574
9575   bool is64Bit = isPPC64 && VT == MVT::i64;
9576   unsigned Reg = StringSwitch<unsigned>(RegName)
9577                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9578                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9579                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9580                                   (is64Bit ? PPC::X13 : PPC::R13))
9581                    .Default(0);
9582
9583   if (Reg)
9584     return Reg;
9585   report_fatal_error("Invalid register name global variable");
9586 }
9587
9588 bool
9589 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9590   // The PowerPC target isn't yet aware of offsets.
9591   return false;
9592 }
9593
9594 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9595                                            const CallInst &I,
9596                                            unsigned Intrinsic) const {
9597
9598   switch (Intrinsic) {
9599   case Intrinsic::ppc_altivec_lvx:
9600   case Intrinsic::ppc_altivec_lvxl:
9601   case Intrinsic::ppc_altivec_lvebx:
9602   case Intrinsic::ppc_altivec_lvehx:
9603   case Intrinsic::ppc_altivec_lvewx:
9604   case Intrinsic::ppc_vsx_lxvd2x:
9605   case Intrinsic::ppc_vsx_lxvw4x: {
9606     EVT VT;
9607     switch (Intrinsic) {
9608     case Intrinsic::ppc_altivec_lvebx:
9609       VT = MVT::i8;
9610       break;
9611     case Intrinsic::ppc_altivec_lvehx:
9612       VT = MVT::i16;
9613       break;
9614     case Intrinsic::ppc_altivec_lvewx:
9615       VT = MVT::i32;
9616       break;
9617     case Intrinsic::ppc_vsx_lxvd2x:
9618       VT = MVT::v2f64;
9619       break;
9620     default:
9621       VT = MVT::v4i32;
9622       break;
9623     }
9624
9625     Info.opc = ISD::INTRINSIC_W_CHAIN;
9626     Info.memVT = VT;
9627     Info.ptrVal = I.getArgOperand(0);
9628     Info.offset = -VT.getStoreSize()+1;
9629     Info.size = 2*VT.getStoreSize()-1;
9630     Info.align = 1;
9631     Info.vol = false;
9632     Info.readMem = true;
9633     Info.writeMem = false;
9634     return true;
9635   }
9636   case Intrinsic::ppc_altivec_stvx:
9637   case Intrinsic::ppc_altivec_stvxl:
9638   case Intrinsic::ppc_altivec_stvebx:
9639   case Intrinsic::ppc_altivec_stvehx:
9640   case Intrinsic::ppc_altivec_stvewx:
9641   case Intrinsic::ppc_vsx_stxvd2x:
9642   case Intrinsic::ppc_vsx_stxvw4x: {
9643     EVT VT;
9644     switch (Intrinsic) {
9645     case Intrinsic::ppc_altivec_stvebx:
9646       VT = MVT::i8;
9647       break;
9648     case Intrinsic::ppc_altivec_stvehx:
9649       VT = MVT::i16;
9650       break;
9651     case Intrinsic::ppc_altivec_stvewx:
9652       VT = MVT::i32;
9653       break;
9654     case Intrinsic::ppc_vsx_stxvd2x:
9655       VT = MVT::v2f64;
9656       break;
9657     default:
9658       VT = MVT::v4i32;
9659       break;
9660     }
9661
9662     Info.opc = ISD::INTRINSIC_VOID;
9663     Info.memVT = VT;
9664     Info.ptrVal = I.getArgOperand(1);
9665     Info.offset = -VT.getStoreSize()+1;
9666     Info.size = 2*VT.getStoreSize()-1;
9667     Info.align = 1;
9668     Info.vol = false;
9669     Info.readMem = false;
9670     Info.writeMem = true;
9671     return true;
9672   }
9673   default:
9674     break;
9675   }
9676
9677   return false;
9678 }
9679
9680 /// getOptimalMemOpType - Returns the target specific optimal type for load
9681 /// and store operations as a result of memset, memcpy, and memmove
9682 /// lowering. If DstAlign is zero that means it's safe to destination
9683 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9684 /// means there isn't a need to check it against alignment requirement,
9685 /// probably because the source does not need to be loaded. If 'IsMemset' is
9686 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9687 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9688 /// source is constant so it does not need to be loaded.
9689 /// It returns EVT::Other if the type should be determined using generic
9690 /// target-independent logic.
9691 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9692                                            unsigned DstAlign, unsigned SrcAlign,
9693                                            bool IsMemset, bool ZeroMemset,
9694                                            bool MemcpyStrSrc,
9695                                            MachineFunction &MF) const {
9696   if (Subtarget.isPPC64()) {
9697     return MVT::i64;
9698   } else {
9699     return MVT::i32;
9700   }
9701 }
9702
9703 /// \brief Returns true if it is beneficial to convert a load of a constant
9704 /// to just the constant itself.
9705 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9706                                                           Type *Ty) const {
9707   assert(Ty->isIntegerTy());
9708
9709   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9710   if (BitSize == 0 || BitSize > 64)
9711     return false;
9712   return true;
9713 }
9714
9715 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9716   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9717     return false;
9718   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9719   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9720   return NumBits1 == 64 && NumBits2 == 32;
9721 }
9722
9723 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9724   if (!VT1.isInteger() || !VT2.isInteger())
9725     return false;
9726   unsigned NumBits1 = VT1.getSizeInBits();
9727   unsigned NumBits2 = VT2.getSizeInBits();
9728   return NumBits1 == 64 && NumBits2 == 32;
9729 }
9730
9731 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9732   return isInt<16>(Imm) || isUInt<16>(Imm);
9733 }
9734
9735 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9736   return isInt<16>(Imm) || isUInt<16>(Imm);
9737 }
9738
9739 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9740                                                        unsigned,
9741                                                        unsigned,
9742                                                        bool *Fast) const {
9743   if (DisablePPCUnaligned)
9744     return false;
9745
9746   // PowerPC supports unaligned memory access for simple non-vector types.
9747   // Although accessing unaligned addresses is not as efficient as accessing
9748   // aligned addresses, it is generally more efficient than manual expansion,
9749   // and generally only traps for software emulation when crossing page
9750   // boundaries.
9751
9752   if (!VT.isSimple())
9753     return false;
9754
9755   if (VT.getSimpleVT().isVector()) {
9756     if (Subtarget.hasVSX()) {
9757       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9758           VT != MVT::v4f32 && VT != MVT::v4i32)
9759         return false;
9760     } else {
9761       return false;
9762     }
9763   }
9764
9765   if (VT == MVT::ppcf128)
9766     return false;
9767
9768   if (Fast)
9769     *Fast = true;
9770
9771   return true;
9772 }
9773
9774 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9775   VT = VT.getScalarType();
9776
9777   if (!VT.isSimple())
9778     return false;
9779
9780   switch (VT.getSimpleVT().SimpleTy) {
9781   case MVT::f32:
9782   case MVT::f64:
9783     return true;
9784   default:
9785     break;
9786   }
9787
9788   return false;
9789 }
9790
9791 bool
9792 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9793                      EVT VT , unsigned DefinedValues) const {
9794   if (VT == MVT::v2i64)
9795     return false;
9796
9797   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9798 }
9799
9800 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9801   if (DisableILPPref || Subtarget.enableMachineScheduler())
9802     return TargetLowering::getSchedulingPreference(N);
9803
9804   return Sched::ILP;
9805 }
9806
9807 // Create a fast isel object.
9808 FastISel *
9809 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9810                                   const TargetLibraryInfo *LibInfo) const {
9811   return PPC::createFastISel(FuncInfo, LibInfo);
9812 }