[PowerPC] Generate pre-increment floating-point ld/st instructions
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
59
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61                                      const PPCSubtarget &STI)
62     : TargetLowering(TM), Subtarget(STI) {
63   // Use _setjmp/_longjmp instead of setjmp/longjmp.
64   setUseUnderscoreSetJmp(true);
65   setUseUnderscoreLongJmp(true);
66
67   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68   // arguments are at least 4/8 bytes aligned.
69   bool isPPC64 = Subtarget.isPPC64();
70   setMinStackArgumentAlignment(isPPC64 ? 8:4);
71
72   // Set up the register classes.
73   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76
77   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78   for (MVT VT : MVT::integer_valuetypes()) {
79     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
81   }
82
83   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84
85   // PowerPC has pre-inc load and store's.
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
100
101   if (Subtarget.useCRBits()) {
102     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103
104     if (isPPC64 || Subtarget.hasFPCVT()) {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107                          isPPC64 ? MVT::i64 : MVT::i32);
108       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
110                          isPPC64 ? MVT::i64 : MVT::i32);
111     } else {
112       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
114     }
115
116     // PowerPC does not support direct load / store of condition registers
117     setOperationAction(ISD::LOAD, MVT::i1, Custom);
118     setOperationAction(ISD::STORE, MVT::i1, Custom);
119
120     // FIXME: Remove this once the ANDI glue bug is fixed:
121     if (ANDIGlueBug)
122       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123
124     for (MVT VT : MVT::integer_valuetypes()) {
125       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127       setTruncStoreAction(VT, MVT::i1, Expand);
128     }
129
130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131   }
132
133   // This is used in the ppcf128->int sequence.  Note it has different semantics
134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
136
137   // We do not currently implement these libm ops for PowerPC.
138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
144
145   // PowerPC has no SREM/UREM instructions
146   setOperationAction(ISD::SREM, MVT::i32, Expand);
147   setOperationAction(ISD::UREM, MVT::i32, Expand);
148   setOperationAction(ISD::SREM, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
160
161   // We don't support sin/cos/sqrt/fmod/pow
162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165   setOperationAction(ISD::FREM , MVT::f64, Expand);
166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171   setOperationAction(ISD::FREM , MVT::f32, Expand);
172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
174
175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
176
177   // If we're enabling GP optimizations, use hardware square root
178   if (!Subtarget.hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
180         Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185         Subtarget.hasFRES()))
186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
187
188   if (Subtarget.hasFCPSGN()) {
189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
191   } else {
192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194   }
195
196   if (Subtarget.hasFPRND()) {
197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
201
202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
206   }
207
208   // PowerPC does not have BSWAP, CTPOP or CTTZ
209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
217
218   if (Subtarget.hasPOPCNTD()) {
219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
221   } else {
222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
224   }
225
226   // PowerPC does not have ROTR
227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
229
230   if (!Subtarget.useCRBits()) {
231     // PowerPC does not have Select
232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
236   }
237
238   // PowerPC wants to turn select_cc of FP into fsel when possible.
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241
242   // PowerPC wants to optimize integer setcc a bit
243   if (!Subtarget.useCRBits())
244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
245
246   // PowerPC does not have BRCOND which requires SetCC
247   if (!Subtarget.useCRBits())
248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
249
250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
251
252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254
255   // PowerPC does not have [U|S]INT_TO_FP
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
258
259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
263
264   // We cannot sextinreg(i1).  Expand to shifts.
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
266
267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269   // support continuation, user-level threading, and etc.. As a result, no
270   // other SjLj exception interfaces are implemented and please don't build
271   // your own exception handling based on them.
272   // LLVM/Clang supports zero-cost DWARF exception handling.
273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
275
276   // We want to legalize GlobalAddress and ConstantPool nodes into the
277   // appropriate instructions to materialize the address.
278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
288
289   // TRAP is legal.
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291
292   // TRAMPOLINE is custom lowered.
293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298
299   if (Subtarget.isSVR4ABI()) {
300     if (isPPC64) {
301       // VAARG always uses double-word chunks, so promote anything smaller.
302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
311     } else {
312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
315     }
316   } else
317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
318
319   if (Subtarget.isSVR4ABI() && !isPPC64)
320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
322   else
323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
324
325   // Use the default implementation.
326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
331
332   // We want to custom lower some of our intrinsics.
333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
334
335   // To handle counter-based loop conditions.
336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
337
338   // Comparisons that require checking two conditions.
339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
351
352   if (Subtarget.has64BitSupport()) {
353     // They also have instructions for converting between i64 and fp.
354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
359     // We cannot do this with Promote because i64 is not a legal type.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361
362     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364   } else {
365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367   }
368
369   // With the instructions enabled under FPCVT, we can do everything.
370   if (Subtarget.hasFPCVT()) {
371     if (Subtarget.has64BitSupport()) {
372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376     }
377
378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382   }
383
384   if (Subtarget.use64BitRegs()) {
385     // 64-bit PowerPC implementations can support i64 types directly
386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389     // 64-bit PowerPC wants to expand i128 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
393   } else {
394     // 32-bit PowerPC wants to expand i64 shifts itself.
395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398   }
399
400   if (Subtarget.hasAltivec()) {
401     // First set operation action for all vector types to expand. Then we
402     // will selectively turn on ones that can be effectively codegen'd.
403     for (MVT VT : MVT::vector_valuetypes()) {
404       // add/sub are legal for all supported vector VT's.
405       setOperationAction(ISD::ADD , VT, Legal);
406       setOperationAction(ISD::SUB , VT, Legal);
407
408       // Vector instructions introduced in P8
409       if (Subtarget.hasP8Altivec()) {
410         setOperationAction(ISD::CTPOP, VT, Legal);
411         setOperationAction(ISD::CTLZ, VT, Legal);
412       }
413       else {
414         setOperationAction(ISD::CTPOP, VT, Expand);
415         setOperationAction(ISD::CTLZ, VT, Expand);
416       }
417
418       // We promote all shuffles to v16i8.
419       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
421
422       // We promote all non-typed operations to v4i32.
423       setOperationAction(ISD::AND   , VT, Promote);
424       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
425       setOperationAction(ISD::OR    , VT, Promote);
426       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
427       setOperationAction(ISD::XOR   , VT, Promote);
428       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
429       setOperationAction(ISD::LOAD  , VT, Promote);
430       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
431       setOperationAction(ISD::SELECT, VT, Promote);
432       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433       setOperationAction(ISD::STORE, VT, Promote);
434       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
435
436       // No other operations are legal.
437       setOperationAction(ISD::MUL , VT, Expand);
438       setOperationAction(ISD::SDIV, VT, Expand);
439       setOperationAction(ISD::SREM, VT, Expand);
440       setOperationAction(ISD::UDIV, VT, Expand);
441       setOperationAction(ISD::UREM, VT, Expand);
442       setOperationAction(ISD::FDIV, VT, Expand);
443       setOperationAction(ISD::FREM, VT, Expand);
444       setOperationAction(ISD::FNEG, VT, Expand);
445       setOperationAction(ISD::FSQRT, VT, Expand);
446       setOperationAction(ISD::FLOG, VT, Expand);
447       setOperationAction(ISD::FLOG10, VT, Expand);
448       setOperationAction(ISD::FLOG2, VT, Expand);
449       setOperationAction(ISD::FEXP, VT, Expand);
450       setOperationAction(ISD::FEXP2, VT, Expand);
451       setOperationAction(ISD::FSIN, VT, Expand);
452       setOperationAction(ISD::FCOS, VT, Expand);
453       setOperationAction(ISD::FABS, VT, Expand);
454       setOperationAction(ISD::FPOWI, VT, Expand);
455       setOperationAction(ISD::FFLOOR, VT, Expand);
456       setOperationAction(ISD::FCEIL,  VT, Expand);
457       setOperationAction(ISD::FTRUNC, VT, Expand);
458       setOperationAction(ISD::FRINT,  VT, Expand);
459       setOperationAction(ISD::FNEARBYINT, VT, Expand);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463       setOperationAction(ISD::MULHU, VT, Expand);
464       setOperationAction(ISD::MULHS, VT, Expand);
465       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467       setOperationAction(ISD::UDIVREM, VT, Expand);
468       setOperationAction(ISD::SDIVREM, VT, Expand);
469       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470       setOperationAction(ISD::FPOW, VT, Expand);
471       setOperationAction(ISD::BSWAP, VT, Expand);
472       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473       setOperationAction(ISD::CTTZ, VT, Expand);
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475       setOperationAction(ISD::VSELECT, VT, Expand);
476       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
477
478       for (MVT InnerVT : MVT::vector_valuetypes()) {
479         setTruncStoreAction(VT, InnerVT, Expand);
480         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
483       }
484     }
485
486     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487     // with merges, splats, etc.
488     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
489
490     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
491     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
492     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
493     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
494     setOperationAction(ISD::SELECT, MVT::v4i32,
495                        Subtarget.useCRBits() ? Legal : Expand);
496     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
505
506     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
510
511     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
513
514     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
517     }
518
519     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
522
523     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
524     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
525
526     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
527     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
528     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
529     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
530
531     // Altivec does not contain unordered floating-point compare instructions
532     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
533     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
534     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
535     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536
537     if (Subtarget.hasVSX()) {
538       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
540
541       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548
549       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
551
552       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
554
555       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
560
561       // Share the Altivec comparison restrictions.
562       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
565       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
566
567       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
568       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
569
570       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
571
572       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
573
574       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
575       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
576
577       // VSX v2i64 only supports non-arithmetic operations.
578       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
579       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
580
581       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
582       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
583       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
584
585       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
586
587       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
588       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
589       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
590       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
591
592       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
593
594       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
595       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
596       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
597       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
598
599       // Vector operation legalization checks the result type of
600       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
601       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
602       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
603       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
604       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
605
606       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
607     }
608
609     if (Subtarget.hasP8Altivec()) 
610       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
611   }
612
613   if (Subtarget.has64BitSupport())
614     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
615
616   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
617
618   if (!isPPC64) {
619     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
620     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
621   }
622
623   setBooleanContents(ZeroOrOneBooleanContent);
624   // Altivec instructions set fields to all zeros or all ones.
625   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
626
627   if (!isPPC64) {
628     // These libcalls are not available in 32-bit.
629     setLibcallName(RTLIB::SHL_I128, nullptr);
630     setLibcallName(RTLIB::SRL_I128, nullptr);
631     setLibcallName(RTLIB::SRA_I128, nullptr);
632   }
633
634   if (isPPC64) {
635     setStackPointerRegisterToSaveRestore(PPC::X1);
636     setExceptionPointerRegister(PPC::X3);
637     setExceptionSelectorRegister(PPC::X4);
638   } else {
639     setStackPointerRegisterToSaveRestore(PPC::R1);
640     setExceptionPointerRegister(PPC::R3);
641     setExceptionSelectorRegister(PPC::R4);
642   }
643
644   // We have target-specific dag combine patterns for the following nodes:
645   setTargetDAGCombine(ISD::SINT_TO_FP);
646   if (Subtarget.hasFPCVT())
647     setTargetDAGCombine(ISD::UINT_TO_FP);
648   setTargetDAGCombine(ISD::LOAD);
649   setTargetDAGCombine(ISD::STORE);
650   setTargetDAGCombine(ISD::BR_CC);
651   if (Subtarget.useCRBits())
652     setTargetDAGCombine(ISD::BRCOND);
653   setTargetDAGCombine(ISD::BSWAP);
654   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
655   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
656   setTargetDAGCombine(ISD::INTRINSIC_VOID);
657
658   setTargetDAGCombine(ISD::SIGN_EXTEND);
659   setTargetDAGCombine(ISD::ZERO_EXTEND);
660   setTargetDAGCombine(ISD::ANY_EXTEND);
661
662   if (Subtarget.useCRBits()) {
663     setTargetDAGCombine(ISD::TRUNCATE);
664     setTargetDAGCombine(ISD::SETCC);
665     setTargetDAGCombine(ISD::SELECT_CC);
666   }
667
668   // Use reciprocal estimates.
669   if (TM.Options.UnsafeFPMath) {
670     setTargetDAGCombine(ISD::FDIV);
671     setTargetDAGCombine(ISD::FSQRT);
672   }
673
674   // Darwin long double math library functions have $LDBL128 appended.
675   if (Subtarget.isDarwin()) {
676     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
677     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
678     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
679     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
680     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
681     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
682     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
683     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
684     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
685     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
686   }
687
688   // With 32 condition bits, we don't need to sink (and duplicate) compares
689   // aggressively in CodeGenPrep.
690   if (Subtarget.useCRBits())
691     setHasMultipleConditionRegisters();
692
693   setMinFunctionAlignment(2);
694   if (Subtarget.isDarwin())
695     setPrefFunctionAlignment(4);
696
697   switch (Subtarget.getDarwinDirective()) {
698   default: break;
699   case PPC::DIR_970:
700   case PPC::DIR_A2:
701   case PPC::DIR_E500mc:
702   case PPC::DIR_E5500:
703   case PPC::DIR_PWR4:
704   case PPC::DIR_PWR5:
705   case PPC::DIR_PWR5X:
706   case PPC::DIR_PWR6:
707   case PPC::DIR_PWR6X:
708   case PPC::DIR_PWR7:
709   case PPC::DIR_PWR8:
710     setPrefFunctionAlignment(4);
711     setPrefLoopAlignment(4);
712     break;
713   }
714
715   setInsertFencesForAtomic(true);
716
717   if (Subtarget.enableMachineScheduler())
718     setSchedulingPreference(Sched::Source);
719   else
720     setSchedulingPreference(Sched::Hybrid);
721
722   computeRegisterProperties();
723
724   // The Freescale cores do better with aggressive inlining of memcpy and
725   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
726   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
727       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
728     MaxStoresPerMemset = 32;
729     MaxStoresPerMemsetOptSize = 16;
730     MaxStoresPerMemcpy = 32;
731     MaxStoresPerMemcpyOptSize = 8;
732     MaxStoresPerMemmove = 32;
733     MaxStoresPerMemmoveOptSize = 8;
734   }
735 }
736
737 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
738 /// the desired ByVal argument alignment.
739 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
740                              unsigned MaxMaxAlign) {
741   if (MaxAlign == MaxMaxAlign)
742     return;
743   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
744     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
745       MaxAlign = 32;
746     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
747       MaxAlign = 16;
748   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
749     unsigned EltAlign = 0;
750     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
751     if (EltAlign > MaxAlign)
752       MaxAlign = EltAlign;
753   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
754     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
755       unsigned EltAlign = 0;
756       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
757       if (EltAlign > MaxAlign)
758         MaxAlign = EltAlign;
759       if (MaxAlign == MaxMaxAlign)
760         break;
761     }
762   }
763 }
764
765 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
766 /// function arguments in the caller parameter area.
767 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
768   // Darwin passes everything on 4 byte boundary.
769   if (Subtarget.isDarwin())
770     return 4;
771
772   // 16byte and wider vectors are passed on 16byte boundary.
773   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
774   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
775   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
776     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
777   return Align;
778 }
779
780 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
781   switch (Opcode) {
782   default: return nullptr;
783   case PPCISD::FSEL:            return "PPCISD::FSEL";
784   case PPCISD::FCFID:           return "PPCISD::FCFID";
785   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
786   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
787   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
788   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
789   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
790   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
791   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
792   case PPCISD::FRE:             return "PPCISD::FRE";
793   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
794   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
795   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
796   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
797   case PPCISD::VPERM:           return "PPCISD::VPERM";
798   case PPCISD::CMPB:            return "PPCISD::CMPB";
799   case PPCISD::Hi:              return "PPCISD::Hi";
800   case PPCISD::Lo:              return "PPCISD::Lo";
801   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
802   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
803   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
804   case PPCISD::SRL:             return "PPCISD::SRL";
805   case PPCISD::SRA:             return "PPCISD::SRA";
806   case PPCISD::SHL:             return "PPCISD::SHL";
807   case PPCISD::CALL:            return "PPCISD::CALL";
808   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
809   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
810   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
811   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
812   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
813   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
814   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
815   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
816   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
817   case PPCISD::VCMP:            return "PPCISD::VCMP";
818   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
819   case PPCISD::LBRX:            return "PPCISD::LBRX";
820   case PPCISD::STBRX:           return "PPCISD::STBRX";
821   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
822   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
823   case PPCISD::LARX:            return "PPCISD::LARX";
824   case PPCISD::STCX:            return "PPCISD::STCX";
825   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
826   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
827   case PPCISD::BDZ:             return "PPCISD::BDZ";
828   case PPCISD::MFFS:            return "PPCISD::MFFS";
829   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
830   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
831   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
832   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
833   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
834   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
835   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
836   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
837   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
838   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
839   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
840   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
841   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
842   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
843   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
844   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
845   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
846   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
847   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
848   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
849   case PPCISD::SC:              return "PPCISD::SC";
850   }
851 }
852
853 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
854   if (!VT.isVector())
855     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
856   return VT.changeVectorElementTypeToInteger();
857 }
858
859 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
860   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
861   return true;
862 }
863
864 //===----------------------------------------------------------------------===//
865 // Node matching predicates, for use by the tblgen matching code.
866 //===----------------------------------------------------------------------===//
867
868 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
869 static bool isFloatingPointZero(SDValue Op) {
870   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
871     return CFP->getValueAPF().isZero();
872   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
873     // Maybe this has already been legalized into the constant pool?
874     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
875       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
876         return CFP->getValueAPF().isZero();
877   }
878   return false;
879 }
880
881 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
882 /// true if Op is undef or if it matches the specified value.
883 static bool isConstantOrUndef(int Op, int Val) {
884   return Op < 0 || Op == Val;
885 }
886
887 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
888 /// VPKUHUM instruction.
889 /// The ShuffleKind distinguishes between big-endian operations with
890 /// two different inputs (0), either-endian operations with two identical
891 /// inputs (1), and little-endian operantion with two different inputs (2).
892 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
893 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
894                                SelectionDAG &DAG) {
895   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
896   if (ShuffleKind == 0) {
897     if (IsLE)
898       return false;
899     for (unsigned i = 0; i != 16; ++i)
900       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
901         return false;
902   } else if (ShuffleKind == 2) {
903     if (!IsLE)
904       return false;
905     for (unsigned i = 0; i != 16; ++i)
906       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
907         return false;
908   } else if (ShuffleKind == 1) {
909     unsigned j = IsLE ? 0 : 1;
910     for (unsigned i = 0; i != 8; ++i)
911       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
912           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
913         return false;
914   }
915   return true;
916 }
917
918 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
919 /// VPKUWUM instruction.
920 /// The ShuffleKind distinguishes between big-endian operations with
921 /// two different inputs (0), either-endian operations with two identical
922 /// inputs (1), and little-endian operantion with two different inputs (2).
923 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
924 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
925                                SelectionDAG &DAG) {
926   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
927   if (ShuffleKind == 0) {
928     if (IsLE)
929       return false;
930     for (unsigned i = 0; i != 16; i += 2)
931       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
932           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
933         return false;
934   } else if (ShuffleKind == 2) {
935     if (!IsLE)
936       return false;
937     for (unsigned i = 0; i != 16; i += 2)
938       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
939           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
940         return false;
941   } else if (ShuffleKind == 1) {
942     unsigned j = IsLE ? 0 : 2;
943     for (unsigned i = 0; i != 8; i += 2)
944       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
945           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
946           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
947           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
948         return false;
949   }
950   return true;
951 }
952
953 /// isVMerge - Common function, used to match vmrg* shuffles.
954 ///
955 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
956                      unsigned LHSStart, unsigned RHSStart) {
957   if (N->getValueType(0) != MVT::v16i8)
958     return false;
959   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
960          "Unsupported merge size!");
961
962   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
963     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
964       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
965                              LHSStart+j+i*UnitSize) ||
966           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
967                              RHSStart+j+i*UnitSize))
968         return false;
969     }
970   return true;
971 }
972
973 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
974 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
975 /// The ShuffleKind distinguishes between big-endian merges with two 
976 /// different inputs (0), either-endian merges with two identical inputs (1),
977 /// and little-endian merges with two different inputs (2).  For the latter,
978 /// the input operands are swapped (see PPCInstrAltivec.td).
979 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
980                              unsigned ShuffleKind, SelectionDAG &DAG) {
981   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
982     if (ShuffleKind == 1) // unary
983       return isVMerge(N, UnitSize, 0, 0);
984     else if (ShuffleKind == 2) // swapped
985       return isVMerge(N, UnitSize, 0, 16);
986     else
987       return false;
988   } else {
989     if (ShuffleKind == 1) // unary
990       return isVMerge(N, UnitSize, 8, 8);
991     else if (ShuffleKind == 0) // normal
992       return isVMerge(N, UnitSize, 8, 24);
993     else
994       return false;
995   }
996 }
997
998 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
999 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1000 /// The ShuffleKind distinguishes between big-endian merges with two 
1001 /// different inputs (0), either-endian merges with two identical inputs (1),
1002 /// and little-endian merges with two different inputs (2).  For the latter,
1003 /// the input operands are swapped (see PPCInstrAltivec.td).
1004 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1005                              unsigned ShuffleKind, SelectionDAG &DAG) {
1006   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1007     if (ShuffleKind == 1) // unary
1008       return isVMerge(N, UnitSize, 8, 8);
1009     else if (ShuffleKind == 2) // swapped
1010       return isVMerge(N, UnitSize, 8, 24);
1011     else
1012       return false;
1013   } else {
1014     if (ShuffleKind == 1) // unary
1015       return isVMerge(N, UnitSize, 0, 0);
1016     else if (ShuffleKind == 0) // normal
1017       return isVMerge(N, UnitSize, 0, 16);
1018     else
1019       return false;
1020   }
1021 }
1022
1023
1024 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1025 /// amount, otherwise return -1.
1026 /// The ShuffleKind distinguishes between big-endian operations with two 
1027 /// different inputs (0), either-endian operations with two identical inputs
1028 /// (1), and little-endian operations with two different inputs (2).  For the
1029 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1030 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1031                              SelectionDAG &DAG) {
1032   if (N->getValueType(0) != MVT::v16i8)
1033     return -1;
1034
1035   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1036
1037   // Find the first non-undef value in the shuffle mask.
1038   unsigned i;
1039   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1040     /*search*/;
1041
1042   if (i == 16) return -1;  // all undef.
1043
1044   // Otherwise, check to see if the rest of the elements are consecutively
1045   // numbered from this value.
1046   unsigned ShiftAmt = SVOp->getMaskElt(i);
1047   if (ShiftAmt < i) return -1;
1048
1049   ShiftAmt -= i;
1050   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1051
1052   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1053     // Check the rest of the elements to see if they are consecutive.
1054     for (++i; i != 16; ++i)
1055       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1056         return -1;
1057   } else if (ShuffleKind == 1) {
1058     // Check the rest of the elements to see if they are consecutive.
1059     for (++i; i != 16; ++i)
1060       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1061         return -1;
1062   } else
1063     return -1;
1064
1065   if (ShuffleKind == 2 && isLE)
1066     ShiftAmt = 16 - ShiftAmt;
1067
1068   return ShiftAmt;
1069 }
1070
1071 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1072 /// specifies a splat of a single element that is suitable for input to
1073 /// VSPLTB/VSPLTH/VSPLTW.
1074 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1075   assert(N->getValueType(0) == MVT::v16i8 &&
1076          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1077
1078   // This is a splat operation if each element of the permute is the same, and
1079   // if the value doesn't reference the second vector.
1080   unsigned ElementBase = N->getMaskElt(0);
1081
1082   // FIXME: Handle UNDEF elements too!
1083   if (ElementBase >= 16)
1084     return false;
1085
1086   // Check that the indices are consecutive, in the case of a multi-byte element
1087   // splatted with a v16i8 mask.
1088   for (unsigned i = 1; i != EltSize; ++i)
1089     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1090       return false;
1091
1092   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1093     if (N->getMaskElt(i) < 0) continue;
1094     for (unsigned j = 0; j != EltSize; ++j)
1095       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1096         return false;
1097   }
1098   return true;
1099 }
1100
1101 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1102 /// are -0.0.
1103 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1104   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1105
1106   APInt APVal, APUndef;
1107   unsigned BitSize;
1108   bool HasAnyUndefs;
1109
1110   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1111     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1112       return CFP->getValueAPF().isNegZero();
1113
1114   return false;
1115 }
1116
1117 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1118 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1119 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1120                                 SelectionDAG &DAG) {
1121   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1122   assert(isSplatShuffleMask(SVOp, EltSize));
1123   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1124     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1125   else
1126     return SVOp->getMaskElt(0) / EltSize;
1127 }
1128
1129 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1130 /// by using a vspltis[bhw] instruction of the specified element size, return
1131 /// the constant being splatted.  The ByteSize field indicates the number of
1132 /// bytes of each element [124] -> [bhw].
1133 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1134   SDValue OpVal(nullptr, 0);
1135
1136   // If ByteSize of the splat is bigger than the element size of the
1137   // build_vector, then we have a case where we are checking for a splat where
1138   // multiple elements of the buildvector are folded together into a single
1139   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1140   unsigned EltSize = 16/N->getNumOperands();
1141   if (EltSize < ByteSize) {
1142     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1143     SDValue UniquedVals[4];
1144     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1145
1146     // See if all of the elements in the buildvector agree across.
1147     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1148       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1149       // If the element isn't a constant, bail fully out.
1150       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1151
1152
1153       if (!UniquedVals[i&(Multiple-1)].getNode())
1154         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1155       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1156         return SDValue();  // no match.
1157     }
1158
1159     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1160     // either constant or undef values that are identical for each chunk.  See
1161     // if these chunks can form into a larger vspltis*.
1162
1163     // Check to see if all of the leading entries are either 0 or -1.  If
1164     // neither, then this won't fit into the immediate field.
1165     bool LeadingZero = true;
1166     bool LeadingOnes = true;
1167     for (unsigned i = 0; i != Multiple-1; ++i) {
1168       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1169
1170       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1171       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1172     }
1173     // Finally, check the least significant entry.
1174     if (LeadingZero) {
1175       if (!UniquedVals[Multiple-1].getNode())
1176         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1177       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1178       if (Val < 16)
1179         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1180     }
1181     if (LeadingOnes) {
1182       if (!UniquedVals[Multiple-1].getNode())
1183         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1184       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1185       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1186         return DAG.getTargetConstant(Val, MVT::i32);
1187     }
1188
1189     return SDValue();
1190   }
1191
1192   // Check to see if this buildvec has a single non-undef value in its elements.
1193   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1194     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1195     if (!OpVal.getNode())
1196       OpVal = N->getOperand(i);
1197     else if (OpVal != N->getOperand(i))
1198       return SDValue();
1199   }
1200
1201   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1202
1203   unsigned ValSizeInBytes = EltSize;
1204   uint64_t Value = 0;
1205   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1206     Value = CN->getZExtValue();
1207   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1208     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1209     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1210   }
1211
1212   // If the splat value is larger than the element value, then we can never do
1213   // this splat.  The only case that we could fit the replicated bits into our
1214   // immediate field for would be zero, and we prefer to use vxor for it.
1215   if (ValSizeInBytes < ByteSize) return SDValue();
1216
1217   // If the element value is larger than the splat value, cut it in half and
1218   // check to see if the two halves are equal.  Continue doing this until we
1219   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1220   while (ValSizeInBytes > ByteSize) {
1221     ValSizeInBytes >>= 1;
1222
1223     // If the top half equals the bottom half, we're still ok.
1224     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1225          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1226       return SDValue();
1227   }
1228
1229   // Properly sign extend the value.
1230   int MaskVal = SignExtend32(Value, ByteSize * 8);
1231
1232   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1233   if (MaskVal == 0) return SDValue();
1234
1235   // Finally, if this value fits in a 5 bit sext field, return it
1236   if (SignExtend32<5>(MaskVal) == MaskVal)
1237     return DAG.getTargetConstant(MaskVal, MVT::i32);
1238   return SDValue();
1239 }
1240
1241 //===----------------------------------------------------------------------===//
1242 //  Addressing Mode Selection
1243 //===----------------------------------------------------------------------===//
1244
1245 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1246 /// or 64-bit immediate, and if the value can be accurately represented as a
1247 /// sign extension from a 16-bit value.  If so, this returns true and the
1248 /// immediate.
1249 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1250   if (!isa<ConstantSDNode>(N))
1251     return false;
1252
1253   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1254   if (N->getValueType(0) == MVT::i32)
1255     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1256   else
1257     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1258 }
1259 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1260   return isIntS16Immediate(Op.getNode(), Imm);
1261 }
1262
1263
1264 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1265 /// can be represented as an indexed [r+r] operation.  Returns false if it
1266 /// can be more efficiently represented with [r+imm].
1267 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1268                                             SDValue &Index,
1269                                             SelectionDAG &DAG) const {
1270   short imm = 0;
1271   if (N.getOpcode() == ISD::ADD) {
1272     if (isIntS16Immediate(N.getOperand(1), imm))
1273       return false;    // r+i
1274     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1275       return false;    // r+i
1276
1277     Base = N.getOperand(0);
1278     Index = N.getOperand(1);
1279     return true;
1280   } else if (N.getOpcode() == ISD::OR) {
1281     if (isIntS16Immediate(N.getOperand(1), imm))
1282       return false;    // r+i can fold it if we can.
1283
1284     // If this is an or of disjoint bitfields, we can codegen this as an add
1285     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1286     // disjoint.
1287     APInt LHSKnownZero, LHSKnownOne;
1288     APInt RHSKnownZero, RHSKnownOne;
1289     DAG.computeKnownBits(N.getOperand(0),
1290                          LHSKnownZero, LHSKnownOne);
1291
1292     if (LHSKnownZero.getBoolValue()) {
1293       DAG.computeKnownBits(N.getOperand(1),
1294                            RHSKnownZero, RHSKnownOne);
1295       // If all of the bits are known zero on the LHS or RHS, the add won't
1296       // carry.
1297       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1298         Base = N.getOperand(0);
1299         Index = N.getOperand(1);
1300         return true;
1301       }
1302     }
1303   }
1304
1305   return false;
1306 }
1307
1308 // If we happen to be doing an i64 load or store into a stack slot that has
1309 // less than a 4-byte alignment, then the frame-index elimination may need to
1310 // use an indexed load or store instruction (because the offset may not be a
1311 // multiple of 4). The extra register needed to hold the offset comes from the
1312 // register scavenger, and it is possible that the scavenger will need to use
1313 // an emergency spill slot. As a result, we need to make sure that a spill slot
1314 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1315 // stack slot.
1316 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1317   // FIXME: This does not handle the LWA case.
1318   if (VT != MVT::i64)
1319     return;
1320
1321   // NOTE: We'll exclude negative FIs here, which come from argument
1322   // lowering, because there are no known test cases triggering this problem
1323   // using packed structures (or similar). We can remove this exclusion if
1324   // we find such a test case. The reason why this is so test-case driven is
1325   // because this entire 'fixup' is only to prevent crashes (from the
1326   // register scavenger) on not-really-valid inputs. For example, if we have:
1327   //   %a = alloca i1
1328   //   %b = bitcast i1* %a to i64*
1329   //   store i64* a, i64 b
1330   // then the store should really be marked as 'align 1', but is not. If it
1331   // were marked as 'align 1' then the indexed form would have been
1332   // instruction-selected initially, and the problem this 'fixup' is preventing
1333   // won't happen regardless.
1334   if (FrameIdx < 0)
1335     return;
1336
1337   MachineFunction &MF = DAG.getMachineFunction();
1338   MachineFrameInfo *MFI = MF.getFrameInfo();
1339
1340   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1341   if (Align >= 4)
1342     return;
1343
1344   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1345   FuncInfo->setHasNonRISpills();
1346 }
1347
1348 /// Returns true if the address N can be represented by a base register plus
1349 /// a signed 16-bit displacement [r+imm], and if it is not better
1350 /// represented as reg+reg.  If Aligned is true, only accept displacements
1351 /// suitable for STD and friends, i.e. multiples of 4.
1352 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1353                                             SDValue &Base,
1354                                             SelectionDAG &DAG,
1355                                             bool Aligned) const {
1356   // FIXME dl should come from parent load or store, not from address
1357   SDLoc dl(N);
1358   // If this can be more profitably realized as r+r, fail.
1359   if (SelectAddressRegReg(N, Disp, Base, DAG))
1360     return false;
1361
1362   if (N.getOpcode() == ISD::ADD) {
1363     short imm = 0;
1364     if (isIntS16Immediate(N.getOperand(1), imm) &&
1365         (!Aligned || (imm & 3) == 0)) {
1366       Disp = DAG.getTargetConstant(imm, N.getValueType());
1367       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1368         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1369         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1370       } else {
1371         Base = N.getOperand(0);
1372       }
1373       return true; // [r+i]
1374     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1375       // Match LOAD (ADD (X, Lo(G))).
1376       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1377              && "Cannot handle constant offsets yet!");
1378       Disp = N.getOperand(1).getOperand(0);  // The global address.
1379       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1380              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1381              Disp.getOpcode() == ISD::TargetConstantPool ||
1382              Disp.getOpcode() == ISD::TargetJumpTable);
1383       Base = N.getOperand(0);
1384       return true;  // [&g+r]
1385     }
1386   } else if (N.getOpcode() == ISD::OR) {
1387     short imm = 0;
1388     if (isIntS16Immediate(N.getOperand(1), imm) &&
1389         (!Aligned || (imm & 3) == 0)) {
1390       // If this is an or of disjoint bitfields, we can codegen this as an add
1391       // (for better address arithmetic) if the LHS and RHS of the OR are
1392       // provably disjoint.
1393       APInt LHSKnownZero, LHSKnownOne;
1394       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1395
1396       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1397         // If all of the bits are known zero on the LHS or RHS, the add won't
1398         // carry.
1399         if (FrameIndexSDNode *FI =
1400               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1401           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1402           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1403         } else {
1404           Base = N.getOperand(0);
1405         }
1406         Disp = DAG.getTargetConstant(imm, N.getValueType());
1407         return true;
1408       }
1409     }
1410   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1411     // Loading from a constant address.
1412
1413     // If this address fits entirely in a 16-bit sext immediate field, codegen
1414     // this as "d, 0"
1415     short Imm;
1416     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1417       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1418       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1419                              CN->getValueType(0));
1420       return true;
1421     }
1422
1423     // Handle 32-bit sext immediates with LIS + addr mode.
1424     if ((CN->getValueType(0) == MVT::i32 ||
1425          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1426         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1427       int Addr = (int)CN->getZExtValue();
1428
1429       // Otherwise, break this down into an LIS + disp.
1430       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1431
1432       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1433       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1434       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1435       return true;
1436     }
1437   }
1438
1439   Disp = DAG.getTargetConstant(0, getPointerTy());
1440   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1441     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1442     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1443   } else
1444     Base = N;
1445   return true;      // [r+0]
1446 }
1447
1448 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1449 /// represented as an indexed [r+r] operation.
1450 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1451                                                 SDValue &Index,
1452                                                 SelectionDAG &DAG) const {
1453   // Check to see if we can easily represent this as an [r+r] address.  This
1454   // will fail if it thinks that the address is more profitably represented as
1455   // reg+imm, e.g. where imm = 0.
1456   if (SelectAddressRegReg(N, Base, Index, DAG))
1457     return true;
1458
1459   // If the operand is an addition, always emit this as [r+r], since this is
1460   // better (for code size, and execution, as the memop does the add for free)
1461   // than emitting an explicit add.
1462   if (N.getOpcode() == ISD::ADD) {
1463     Base = N.getOperand(0);
1464     Index = N.getOperand(1);
1465     return true;
1466   }
1467
1468   // Otherwise, do it the hard way, using R0 as the base register.
1469   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1470                          N.getValueType());
1471   Index = N;
1472   return true;
1473 }
1474
1475 /// getPreIndexedAddressParts - returns true by value, base pointer and
1476 /// offset pointer and addressing mode by reference if the node's address
1477 /// can be legally represented as pre-indexed load / store address.
1478 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1479                                                   SDValue &Offset,
1480                                                   ISD::MemIndexedMode &AM,
1481                                                   SelectionDAG &DAG) const {
1482   if (DisablePPCPreinc) return false;
1483
1484   bool isLoad = true;
1485   SDValue Ptr;
1486   EVT VT;
1487   unsigned Alignment;
1488   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1489     Ptr = LD->getBasePtr();
1490     VT = LD->getMemoryVT();
1491     Alignment = LD->getAlignment();
1492   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1493     Ptr = ST->getBasePtr();
1494     VT  = ST->getMemoryVT();
1495     Alignment = ST->getAlignment();
1496     isLoad = false;
1497   } else
1498     return false;
1499
1500   // PowerPC doesn't have preinc load/store instructions for vectors.
1501   if (VT.isVector())
1502     return false;
1503
1504   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1505
1506     // Common code will reject creating a pre-inc form if the base pointer
1507     // is a frame index, or if N is a store and the base pointer is either
1508     // the same as or a predecessor of the value being stored.  Check for
1509     // those situations here, and try with swapped Base/Offset instead.
1510     bool Swap = false;
1511
1512     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1513       Swap = true;
1514     else if (!isLoad) {
1515       SDValue Val = cast<StoreSDNode>(N)->getValue();
1516       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1517         Swap = true;
1518     }
1519
1520     if (Swap)
1521       std::swap(Base, Offset);
1522
1523     AM = ISD::PRE_INC;
1524     return true;
1525   }
1526
1527   // LDU/STU can only handle immediates that are a multiple of 4.
1528   if (VT != MVT::i64) {
1529     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1530       return false;
1531   } else {
1532     // LDU/STU need an address with at least 4-byte alignment.
1533     if (Alignment < 4)
1534       return false;
1535
1536     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1537       return false;
1538   }
1539
1540   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1541     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1542     // sext i32 to i64 when addr mode is r+i.
1543     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1544         LD->getExtensionType() == ISD::SEXTLOAD &&
1545         isa<ConstantSDNode>(Offset))
1546       return false;
1547   }
1548
1549   AM = ISD::PRE_INC;
1550   return true;
1551 }
1552
1553 //===----------------------------------------------------------------------===//
1554 //  LowerOperation implementation
1555 //===----------------------------------------------------------------------===//
1556
1557 /// GetLabelAccessInfo - Return true if we should reference labels using a
1558 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1559 static bool GetLabelAccessInfo(const TargetMachine &TM,
1560                                const PPCSubtarget &Subtarget,
1561                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1562                                const GlobalValue *GV = nullptr) {
1563   HiOpFlags = PPCII::MO_HA;
1564   LoOpFlags = PPCII::MO_LO;
1565
1566   // Don't use the pic base if not in PIC relocation model.
1567   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1568
1569   if (isPIC) {
1570     HiOpFlags |= PPCII::MO_PIC_FLAG;
1571     LoOpFlags |= PPCII::MO_PIC_FLAG;
1572   }
1573
1574   // If this is a reference to a global value that requires a non-lazy-ptr, make
1575   // sure that instruction lowering adds it.
1576   if (GV && Subtarget.hasLazyResolverStub(GV, TM)) {
1577     HiOpFlags |= PPCII::MO_NLP_FLAG;
1578     LoOpFlags |= PPCII::MO_NLP_FLAG;
1579
1580     if (GV->hasHiddenVisibility()) {
1581       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1582       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1583     }
1584   }
1585
1586   return isPIC;
1587 }
1588
1589 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1590                              SelectionDAG &DAG) {
1591   EVT PtrVT = HiPart.getValueType();
1592   SDValue Zero = DAG.getConstant(0, PtrVT);
1593   SDLoc DL(HiPart);
1594
1595   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1596   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1597
1598   // With PIC, the first instruction is actually "GR+hi(&G)".
1599   if (isPIC)
1600     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1601                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1602
1603   // Generate non-pic code that has direct accesses to the constant pool.
1604   // The address of the global is just (hi(&g)+lo(&g)).
1605   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1606 }
1607
1608 static void setUsesTOCBasePtr(MachineFunction &MF) {
1609   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1610   FuncInfo->setUsesTOCBasePtr();
1611 }
1612
1613 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1614   setUsesTOCBasePtr(DAG.getMachineFunction());
1615 }
1616
1617 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1618                                              SelectionDAG &DAG) const {
1619   EVT PtrVT = Op.getValueType();
1620   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1621   const Constant *C = CP->getConstVal();
1622
1623   // 64-bit SVR4 ABI code is always position-independent.
1624   // The actual address of the GlobalValue is stored in the TOC.
1625   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1626     setUsesTOCBasePtr(DAG);
1627     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1628     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1629                        DAG.getRegister(PPC::X2, MVT::i64));
1630   }
1631
1632   unsigned MOHiFlag, MOLoFlag;
1633   bool isPIC =
1634       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1635
1636   if (isPIC && Subtarget.isSVR4ABI()) {
1637     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1638                                            PPCII::MO_PIC_FLAG);
1639     SDLoc DL(CP);
1640     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1641                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1642   }
1643
1644   SDValue CPIHi =
1645     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1646   SDValue CPILo =
1647     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1648   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1649 }
1650
1651 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1652   EVT PtrVT = Op.getValueType();
1653   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1654
1655   // 64-bit SVR4 ABI code is always position-independent.
1656   // The actual address of the GlobalValue is stored in the TOC.
1657   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1658     setUsesTOCBasePtr(DAG);
1659     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1660     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1661                        DAG.getRegister(PPC::X2, MVT::i64));
1662   }
1663
1664   unsigned MOHiFlag, MOLoFlag;
1665   bool isPIC =
1666       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1667
1668   if (isPIC && Subtarget.isSVR4ABI()) {
1669     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1670                                         PPCII::MO_PIC_FLAG);
1671     SDLoc DL(GA);
1672     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1673                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1674   }
1675
1676   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1677   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1678   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1679 }
1680
1681 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1682                                              SelectionDAG &DAG) const {
1683   EVT PtrVT = Op.getValueType();
1684   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1685   const BlockAddress *BA = BASDN->getBlockAddress();
1686
1687   // 64-bit SVR4 ABI code is always position-independent.
1688   // The actual BlockAddress is stored in the TOC.
1689   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1690     setUsesTOCBasePtr(DAG);
1691     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1692     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1693                        DAG.getRegister(PPC::X2, MVT::i64));
1694   }
1695
1696   unsigned MOHiFlag, MOLoFlag;
1697   bool isPIC =
1698       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1699   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1700   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1701   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1702 }
1703
1704 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1705                                               SelectionDAG &DAG) const {
1706
1707   // FIXME: TLS addresses currently use medium model code sequences,
1708   // which is the most useful form.  Eventually support for small and
1709   // large models could be added if users need it, at the cost of
1710   // additional complexity.
1711   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1712   SDLoc dl(GA);
1713   const GlobalValue *GV = GA->getGlobal();
1714   EVT PtrVT = getPointerTy();
1715   bool is64bit = Subtarget.isPPC64();
1716   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1717   PICLevel::Level picLevel = M->getPICLevel();
1718
1719   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1720
1721   if (Model == TLSModel::LocalExec) {
1722     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1723                                                PPCII::MO_TPREL_HA);
1724     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1725                                                PPCII::MO_TPREL_LO);
1726     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1727                                      is64bit ? MVT::i64 : MVT::i32);
1728     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1729     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1730   }
1731
1732   if (Model == TLSModel::InitialExec) {
1733     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1734     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1735                                                 PPCII::MO_TLS);
1736     SDValue GOTPtr;
1737     if (is64bit) {
1738       setUsesTOCBasePtr(DAG);
1739       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1740       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1741                            PtrVT, GOTReg, TGA);
1742     } else
1743       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1744     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1745                                    PtrVT, TGA, GOTPtr);
1746     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1747   }
1748
1749   if (Model == TLSModel::GeneralDynamic) {
1750     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1751     SDValue GOTPtr;
1752     if (is64bit) {
1753       setUsesTOCBasePtr(DAG);
1754       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1755       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1756                                    GOTReg, TGA);
1757     } else {
1758       if (picLevel == PICLevel::Small)
1759         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1760       else
1761         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1762     }
1763     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl,
1764                                    PtrVT, GOTPtr, TGA);
1765     return DAG.getNode(PPCISD::GET_TLS_ADDR, dl, PtrVT, GOTEntry, TGA);
1766   }
1767
1768   if (Model == TLSModel::LocalDynamic) {
1769     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1770     SDValue GOTPtr;
1771     if (is64bit) {
1772       setUsesTOCBasePtr(DAG);
1773       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1774       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1775                            GOTReg, TGA);
1776     } else {
1777       if (picLevel == PICLevel::Small)
1778         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1779       else
1780         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1781     }
1782     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1783                                    GOTPtr, TGA);
1784     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1785                                   PtrVT, GOTEntry, TGA);
1786     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
1787                                       PtrVT, TLSAddr, TGA);
1788     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1789   }
1790
1791   llvm_unreachable("Unknown TLS model!");
1792 }
1793
1794 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1795                                               SelectionDAG &DAG) const {
1796   EVT PtrVT = Op.getValueType();
1797   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1798   SDLoc DL(GSDN);
1799   const GlobalValue *GV = GSDN->getGlobal();
1800
1801   // 64-bit SVR4 ABI code is always position-independent.
1802   // The actual address of the GlobalValue is stored in the TOC.
1803   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1804     setUsesTOCBasePtr(DAG);
1805     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1806     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1807                        DAG.getRegister(PPC::X2, MVT::i64));
1808   }
1809
1810   unsigned MOHiFlag, MOLoFlag;
1811   bool isPIC =
1812       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
1813
1814   if (isPIC && Subtarget.isSVR4ABI()) {
1815     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1816                                             GSDN->getOffset(),
1817                                             PPCII::MO_PIC_FLAG);
1818     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1819                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1820   }
1821
1822   SDValue GAHi =
1823     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1824   SDValue GALo =
1825     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1826
1827   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1828
1829   // If the global reference is actually to a non-lazy-pointer, we have to do an
1830   // extra load to get the address of the global.
1831   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1832     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1833                       false, false, false, 0);
1834   return Ptr;
1835 }
1836
1837 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1838   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1839   SDLoc dl(Op);
1840
1841   if (Op.getValueType() == MVT::v2i64) {
1842     // When the operands themselves are v2i64 values, we need to do something
1843     // special because VSX has no underlying comparison operations for these.
1844     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1845       // Equality can be handled by casting to the legal type for Altivec
1846       // comparisons, everything else needs to be expanded.
1847       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1848         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1849                  DAG.getSetCC(dl, MVT::v4i32,
1850                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1851                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1852                    CC));
1853       }
1854
1855       return SDValue();
1856     }
1857
1858     // We handle most of these in the usual way.
1859     return Op;
1860   }
1861
1862   // If we're comparing for equality to zero, expose the fact that this is
1863   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1864   // fold the new nodes.
1865   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1866     if (C->isNullValue() && CC == ISD::SETEQ) {
1867       EVT VT = Op.getOperand(0).getValueType();
1868       SDValue Zext = Op.getOperand(0);
1869       if (VT.bitsLT(MVT::i32)) {
1870         VT = MVT::i32;
1871         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1872       }
1873       unsigned Log2b = Log2_32(VT.getSizeInBits());
1874       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1875       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1876                                 DAG.getConstant(Log2b, MVT::i32));
1877       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1878     }
1879     // Leave comparisons against 0 and -1 alone for now, since they're usually
1880     // optimized.  FIXME: revisit this when we can custom lower all setcc
1881     // optimizations.
1882     if (C->isAllOnesValue() || C->isNullValue())
1883       return SDValue();
1884   }
1885
1886   // If we have an integer seteq/setne, turn it into a compare against zero
1887   // by xor'ing the rhs with the lhs, which is faster than setting a
1888   // condition register, reading it back out, and masking the correct bit.  The
1889   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1890   // the result to other bit-twiddling opportunities.
1891   EVT LHSVT = Op.getOperand(0).getValueType();
1892   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1893     EVT VT = Op.getValueType();
1894     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1895                                 Op.getOperand(1));
1896     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1897   }
1898   return SDValue();
1899 }
1900
1901 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1902                                       const PPCSubtarget &Subtarget) const {
1903   SDNode *Node = Op.getNode();
1904   EVT VT = Node->getValueType(0);
1905   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1906   SDValue InChain = Node->getOperand(0);
1907   SDValue VAListPtr = Node->getOperand(1);
1908   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1909   SDLoc dl(Node);
1910
1911   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1912
1913   // gpr_index
1914   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1915                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1916                                     false, false, false, 0);
1917   InChain = GprIndex.getValue(1);
1918
1919   if (VT == MVT::i64) {
1920     // Check if GprIndex is even
1921     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1922                                  DAG.getConstant(1, MVT::i32));
1923     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1924                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1925     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1926                                           DAG.getConstant(1, MVT::i32));
1927     // Align GprIndex to be even if it isn't
1928     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1929                            GprIndex);
1930   }
1931
1932   // fpr index is 1 byte after gpr
1933   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1934                                DAG.getConstant(1, MVT::i32));
1935
1936   // fpr
1937   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1938                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1939                                     false, false, false, 0);
1940   InChain = FprIndex.getValue(1);
1941
1942   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1943                                        DAG.getConstant(8, MVT::i32));
1944
1945   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1946                                         DAG.getConstant(4, MVT::i32));
1947
1948   // areas
1949   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1950                                      MachinePointerInfo(), false, false,
1951                                      false, 0);
1952   InChain = OverflowArea.getValue(1);
1953
1954   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1955                                     MachinePointerInfo(), false, false,
1956                                     false, 0);
1957   InChain = RegSaveArea.getValue(1);
1958
1959   // select overflow_area if index > 8
1960   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1961                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1962
1963   // adjustment constant gpr_index * 4/8
1964   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1965                                     VT.isInteger() ? GprIndex : FprIndex,
1966                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1967                                                     MVT::i32));
1968
1969   // OurReg = RegSaveArea + RegConstant
1970   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1971                                RegConstant);
1972
1973   // Floating types are 32 bytes into RegSaveArea
1974   if (VT.isFloatingPoint())
1975     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1976                          DAG.getConstant(32, MVT::i32));
1977
1978   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1979   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1980                                    VT.isInteger() ? GprIndex : FprIndex,
1981                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1982                                                    MVT::i32));
1983
1984   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1985                               VT.isInteger() ? VAListPtr : FprPtr,
1986                               MachinePointerInfo(SV),
1987                               MVT::i8, false, false, 0);
1988
1989   // determine if we should load from reg_save_area or overflow_area
1990   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1991
1992   // increase overflow_area by 4/8 if gpr/fpr > 8
1993   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1994                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1995                                           MVT::i32));
1996
1997   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1998                              OverflowAreaPlusN);
1999
2000   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2001                               OverflowAreaPtr,
2002                               MachinePointerInfo(),
2003                               MVT::i32, false, false, 0);
2004
2005   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2006                      false, false, false, 0);
2007 }
2008
2009 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2010                                        const PPCSubtarget &Subtarget) const {
2011   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2012
2013   // We have to copy the entire va_list struct:
2014   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2015   return DAG.getMemcpy(Op.getOperand(0), Op,
2016                        Op.getOperand(1), Op.getOperand(2),
2017                        DAG.getConstant(12, MVT::i32), 8, false, true,
2018                        MachinePointerInfo(), MachinePointerInfo());
2019 }
2020
2021 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2022                                                   SelectionDAG &DAG) const {
2023   return Op.getOperand(0);
2024 }
2025
2026 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2027                                                 SelectionDAG &DAG) const {
2028   SDValue Chain = Op.getOperand(0);
2029   SDValue Trmp = Op.getOperand(1); // trampoline
2030   SDValue FPtr = Op.getOperand(2); // nested function
2031   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2032   SDLoc dl(Op);
2033
2034   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2035   bool isPPC64 = (PtrVT == MVT::i64);
2036   Type *IntPtrTy =
2037     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2038                                                              *DAG.getContext());
2039
2040   TargetLowering::ArgListTy Args;
2041   TargetLowering::ArgListEntry Entry;
2042
2043   Entry.Ty = IntPtrTy;
2044   Entry.Node = Trmp; Args.push_back(Entry);
2045
2046   // TrampSize == (isPPC64 ? 48 : 40);
2047   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2048                                isPPC64 ? MVT::i64 : MVT::i32);
2049   Args.push_back(Entry);
2050
2051   Entry.Node = FPtr; Args.push_back(Entry);
2052   Entry.Node = Nest; Args.push_back(Entry);
2053
2054   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2055   TargetLowering::CallLoweringInfo CLI(DAG);
2056   CLI.setDebugLoc(dl).setChain(Chain)
2057     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2058                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2059                std::move(Args), 0);
2060
2061   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2062   return CallResult.second;
2063 }
2064
2065 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2066                                         const PPCSubtarget &Subtarget) const {
2067   MachineFunction &MF = DAG.getMachineFunction();
2068   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2069
2070   SDLoc dl(Op);
2071
2072   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2073     // vastart just stores the address of the VarArgsFrameIndex slot into the
2074     // memory location argument.
2075     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2076     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2077     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2078     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2079                         MachinePointerInfo(SV),
2080                         false, false, 0);
2081   }
2082
2083   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2084   // We suppose the given va_list is already allocated.
2085   //
2086   // typedef struct {
2087   //  char gpr;     /* index into the array of 8 GPRs
2088   //                 * stored in the register save area
2089   //                 * gpr=0 corresponds to r3,
2090   //                 * gpr=1 to r4, etc.
2091   //                 */
2092   //  char fpr;     /* index into the array of 8 FPRs
2093   //                 * stored in the register save area
2094   //                 * fpr=0 corresponds to f1,
2095   //                 * fpr=1 to f2, etc.
2096   //                 */
2097   //  char *overflow_arg_area;
2098   //                /* location on stack that holds
2099   //                 * the next overflow argument
2100   //                 */
2101   //  char *reg_save_area;
2102   //               /* where r3:r10 and f1:f8 (if saved)
2103   //                * are stored
2104   //                */
2105   // } va_list[1];
2106
2107
2108   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2109   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2110
2111
2112   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2113
2114   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2115                                             PtrVT);
2116   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2117                                  PtrVT);
2118
2119   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2120   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2121
2122   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2123   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2124
2125   uint64_t FPROffset = 1;
2126   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2127
2128   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2129
2130   // Store first byte : number of int regs
2131   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2132                                          Op.getOperand(1),
2133                                          MachinePointerInfo(SV),
2134                                          MVT::i8, false, false, 0);
2135   uint64_t nextOffset = FPROffset;
2136   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2137                                   ConstFPROffset);
2138
2139   // Store second byte : number of float regs
2140   SDValue secondStore =
2141     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2142                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2143                       false, false, 0);
2144   nextOffset += StackOffset;
2145   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2146
2147   // Store second word : arguments given on stack
2148   SDValue thirdStore =
2149     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2150                  MachinePointerInfo(SV, nextOffset),
2151                  false, false, 0);
2152   nextOffset += FrameOffset;
2153   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2154
2155   // Store third word : arguments given in registers
2156   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2157                       MachinePointerInfo(SV, nextOffset),
2158                       false, false, 0);
2159
2160 }
2161
2162 #include "PPCGenCallingConv.inc"
2163
2164 // Function whose sole purpose is to kill compiler warnings 
2165 // stemming from unused functions included from PPCGenCallingConv.inc.
2166 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2167   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2168 }
2169
2170 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2171                                       CCValAssign::LocInfo &LocInfo,
2172                                       ISD::ArgFlagsTy &ArgFlags,
2173                                       CCState &State) {
2174   return true;
2175 }
2176
2177 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2178                                              MVT &LocVT,
2179                                              CCValAssign::LocInfo &LocInfo,
2180                                              ISD::ArgFlagsTy &ArgFlags,
2181                                              CCState &State) {
2182   static const MCPhysReg ArgRegs[] = {
2183     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2184     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2185   };
2186   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2187
2188   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2189
2190   // Skip one register if the first unallocated register has an even register
2191   // number and there are still argument registers available which have not been
2192   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2193   // need to skip a register if RegNum is odd.
2194   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2195     State.AllocateReg(ArgRegs[RegNum]);
2196   }
2197
2198   // Always return false here, as this function only makes sure that the first
2199   // unallocated register has an odd register number and does not actually
2200   // allocate a register for the current argument.
2201   return false;
2202 }
2203
2204 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2205                                                MVT &LocVT,
2206                                                CCValAssign::LocInfo &LocInfo,
2207                                                ISD::ArgFlagsTy &ArgFlags,
2208                                                CCState &State) {
2209   static const MCPhysReg ArgRegs[] = {
2210     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2211     PPC::F8
2212   };
2213
2214   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2215
2216   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2217
2218   // If there is only one Floating-point register left we need to put both f64
2219   // values of a split ppc_fp128 value on the stack.
2220   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2221     State.AllocateReg(ArgRegs[RegNum]);
2222   }
2223
2224   // Always return false here, as this function only makes sure that the two f64
2225   // values a ppc_fp128 value is split into are both passed in registers or both
2226   // passed on the stack and does not actually allocate a register for the
2227   // current argument.
2228   return false;
2229 }
2230
2231 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2232 /// on Darwin.
2233 static const MCPhysReg *GetFPR() {
2234   static const MCPhysReg FPR[] = {
2235     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2236     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2237   };
2238
2239   return FPR;
2240 }
2241
2242 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2243 /// the stack.
2244 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2245                                        unsigned PtrByteSize) {
2246   unsigned ArgSize = ArgVT.getStoreSize();
2247   if (Flags.isByVal())
2248     ArgSize = Flags.getByValSize();
2249
2250   // Round up to multiples of the pointer size, except for array members,
2251   // which are always packed.
2252   if (!Flags.isInConsecutiveRegs())
2253     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2254
2255   return ArgSize;
2256 }
2257
2258 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2259 /// on the stack.
2260 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2261                                             ISD::ArgFlagsTy Flags,
2262                                             unsigned PtrByteSize) {
2263   unsigned Align = PtrByteSize;
2264
2265   // Altivec parameters are padded to a 16 byte boundary.
2266   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2267       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2268       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2269     Align = 16;
2270
2271   // ByVal parameters are aligned as requested.
2272   if (Flags.isByVal()) {
2273     unsigned BVAlign = Flags.getByValAlign();
2274     if (BVAlign > PtrByteSize) {
2275       if (BVAlign % PtrByteSize != 0)
2276           llvm_unreachable(
2277             "ByVal alignment is not a multiple of the pointer size");
2278
2279       Align = BVAlign;
2280     }
2281   }
2282
2283   // Array members are always packed to their original alignment.
2284   if (Flags.isInConsecutiveRegs()) {
2285     // If the array member was split into multiple registers, the first
2286     // needs to be aligned to the size of the full type.  (Except for
2287     // ppcf128, which is only aligned as its f64 components.)
2288     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2289       Align = OrigVT.getStoreSize();
2290     else
2291       Align = ArgVT.getStoreSize();
2292   }
2293
2294   return Align;
2295 }
2296
2297 /// CalculateStackSlotUsed - Return whether this argument will use its
2298 /// stack slot (instead of being passed in registers).  ArgOffset,
2299 /// AvailableFPRs, and AvailableVRs must hold the current argument
2300 /// position, and will be updated to account for this argument.
2301 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2302                                    ISD::ArgFlagsTy Flags,
2303                                    unsigned PtrByteSize,
2304                                    unsigned LinkageSize,
2305                                    unsigned ParamAreaSize,
2306                                    unsigned &ArgOffset,
2307                                    unsigned &AvailableFPRs,
2308                                    unsigned &AvailableVRs) {
2309   bool UseMemory = false;
2310
2311   // Respect alignment of argument on the stack.
2312   unsigned Align =
2313     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2314   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2315   // If there's no space left in the argument save area, we must
2316   // use memory (this check also catches zero-sized arguments).
2317   if (ArgOffset >= LinkageSize + ParamAreaSize)
2318     UseMemory = true;
2319
2320   // Allocate argument on the stack.
2321   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2322   if (Flags.isInConsecutiveRegsLast())
2323     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2324   // If we overran the argument save area, we must use memory
2325   // (this check catches arguments passed partially in memory)
2326   if (ArgOffset > LinkageSize + ParamAreaSize)
2327     UseMemory = true;
2328
2329   // However, if the argument is actually passed in an FPR or a VR,
2330   // we don't use memory after all.
2331   if (!Flags.isByVal()) {
2332     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2333       if (AvailableFPRs > 0) {
2334         --AvailableFPRs;
2335         return false;
2336       }
2337     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2338         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2339         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2340       if (AvailableVRs > 0) {
2341         --AvailableVRs;
2342         return false;
2343       }
2344   }
2345
2346   return UseMemory;
2347 }
2348
2349 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2350 /// ensure minimum alignment required for target.
2351 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2352                                      unsigned NumBytes) {
2353   unsigned TargetAlign = Lowering->getStackAlignment();
2354   unsigned AlignMask = TargetAlign - 1;
2355   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2356   return NumBytes;
2357 }
2358
2359 SDValue
2360 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2361                                         CallingConv::ID CallConv, bool isVarArg,
2362                                         const SmallVectorImpl<ISD::InputArg>
2363                                           &Ins,
2364                                         SDLoc dl, SelectionDAG &DAG,
2365                                         SmallVectorImpl<SDValue> &InVals)
2366                                           const {
2367   if (Subtarget.isSVR4ABI()) {
2368     if (Subtarget.isPPC64())
2369       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2370                                          dl, DAG, InVals);
2371     else
2372       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2373                                          dl, DAG, InVals);
2374   } else {
2375     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2376                                        dl, DAG, InVals);
2377   }
2378 }
2379
2380 SDValue
2381 PPCTargetLowering::LowerFormalArguments_32SVR4(
2382                                       SDValue Chain,
2383                                       CallingConv::ID CallConv, bool isVarArg,
2384                                       const SmallVectorImpl<ISD::InputArg>
2385                                         &Ins,
2386                                       SDLoc dl, SelectionDAG &DAG,
2387                                       SmallVectorImpl<SDValue> &InVals) const {
2388
2389   // 32-bit SVR4 ABI Stack Frame Layout:
2390   //              +-----------------------------------+
2391   //        +-->  |            Back chain             |
2392   //        |     +-----------------------------------+
2393   //        |     | Floating-point register save area |
2394   //        |     +-----------------------------------+
2395   //        |     |    General register save area     |
2396   //        |     +-----------------------------------+
2397   //        |     |          CR save word             |
2398   //        |     +-----------------------------------+
2399   //        |     |         VRSAVE save word          |
2400   //        |     +-----------------------------------+
2401   //        |     |         Alignment padding         |
2402   //        |     +-----------------------------------+
2403   //        |     |     Vector register save area     |
2404   //        |     +-----------------------------------+
2405   //        |     |       Local variable space        |
2406   //        |     +-----------------------------------+
2407   //        |     |        Parameter list area        |
2408   //        |     +-----------------------------------+
2409   //        |     |           LR save word            |
2410   //        |     +-----------------------------------+
2411   // SP-->  +---  |            Back chain             |
2412   //              +-----------------------------------+
2413   //
2414   // Specifications:
2415   //   System V Application Binary Interface PowerPC Processor Supplement
2416   //   AltiVec Technology Programming Interface Manual
2417
2418   MachineFunction &MF = DAG.getMachineFunction();
2419   MachineFrameInfo *MFI = MF.getFrameInfo();
2420   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2421
2422   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2423   // Potential tail calls could cause overwriting of argument stack slots.
2424   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2425                        (CallConv == CallingConv::Fast));
2426   unsigned PtrByteSize = 4;
2427
2428   // Assign locations to all of the incoming arguments.
2429   SmallVector<CCValAssign, 16> ArgLocs;
2430   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2431                  *DAG.getContext());
2432
2433   // Reserve space for the linkage area on the stack.
2434   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2435   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2436
2437   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2438
2439   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2440     CCValAssign &VA = ArgLocs[i];
2441
2442     // Arguments stored in registers.
2443     if (VA.isRegLoc()) {
2444       const TargetRegisterClass *RC;
2445       EVT ValVT = VA.getValVT();
2446
2447       switch (ValVT.getSimpleVT().SimpleTy) {
2448         default:
2449           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2450         case MVT::i1:
2451         case MVT::i32:
2452           RC = &PPC::GPRCRegClass;
2453           break;
2454         case MVT::f32:
2455           RC = &PPC::F4RCRegClass;
2456           break;
2457         case MVT::f64:
2458           if (Subtarget.hasVSX())
2459             RC = &PPC::VSFRCRegClass;
2460           else
2461             RC = &PPC::F8RCRegClass;
2462           break;
2463         case MVT::v16i8:
2464         case MVT::v8i16:
2465         case MVT::v4i32:
2466         case MVT::v4f32:
2467           RC = &PPC::VRRCRegClass;
2468           break;
2469         case MVT::v2f64:
2470         case MVT::v2i64:
2471           RC = &PPC::VSHRCRegClass;
2472           break;
2473       }
2474
2475       // Transform the arguments stored in physical registers into virtual ones.
2476       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2477       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2478                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2479
2480       if (ValVT == MVT::i1)
2481         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2482
2483       InVals.push_back(ArgValue);
2484     } else {
2485       // Argument stored in memory.
2486       assert(VA.isMemLoc());
2487
2488       unsigned ArgSize = VA.getLocVT().getStoreSize();
2489       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2490                                       isImmutable);
2491
2492       // Create load nodes to retrieve arguments from the stack.
2493       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2494       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2495                                    MachinePointerInfo(),
2496                                    false, false, false, 0));
2497     }
2498   }
2499
2500   // Assign locations to all of the incoming aggregate by value arguments.
2501   // Aggregates passed by value are stored in the local variable space of the
2502   // caller's stack frame, right above the parameter list area.
2503   SmallVector<CCValAssign, 16> ByValArgLocs;
2504   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2505                       ByValArgLocs, *DAG.getContext());
2506
2507   // Reserve stack space for the allocations in CCInfo.
2508   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2509
2510   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2511
2512   // Area that is at least reserved in the caller of this function.
2513   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2514   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2515
2516   // Set the size that is at least reserved in caller of this function.  Tail
2517   // call optimized function's reserved stack space needs to be aligned so that
2518   // taking the difference between two stack areas will result in an aligned
2519   // stack.
2520   MinReservedArea =
2521       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2522   FuncInfo->setMinReservedArea(MinReservedArea);
2523
2524   SmallVector<SDValue, 8> MemOps;
2525
2526   // If the function takes variable number of arguments, make a frame index for
2527   // the start of the first vararg value... for expansion of llvm.va_start.
2528   if (isVarArg) {
2529     static const MCPhysReg GPArgRegs[] = {
2530       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2531       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2532     };
2533     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2534
2535     static const MCPhysReg FPArgRegs[] = {
2536       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2537       PPC::F8
2538     };
2539     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2540     if (DisablePPCFloatInVariadic)
2541       NumFPArgRegs = 0;
2542
2543     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2544                                                           NumGPArgRegs));
2545     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2546                                                           NumFPArgRegs));
2547
2548     // Make room for NumGPArgRegs and NumFPArgRegs.
2549     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2550                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2551
2552     FuncInfo->setVarArgsStackOffset(
2553       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2554                              CCInfo.getNextStackOffset(), true));
2555
2556     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2557     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2558
2559     // The fixed integer arguments of a variadic function are stored to the
2560     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2561     // the result of va_next.
2562     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2563       // Get an existing live-in vreg, or add a new one.
2564       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2565       if (!VReg)
2566         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2567
2568       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2569       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2570                                    MachinePointerInfo(), false, false, 0);
2571       MemOps.push_back(Store);
2572       // Increment the address by four for the next argument to store
2573       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2574       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2575     }
2576
2577     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2578     // is set.
2579     // The double arguments are stored to the VarArgsFrameIndex
2580     // on the stack.
2581     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2582       // Get an existing live-in vreg, or add a new one.
2583       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2584       if (!VReg)
2585         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2586
2587       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2588       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2589                                    MachinePointerInfo(), false, false, 0);
2590       MemOps.push_back(Store);
2591       // Increment the address by eight for the next argument to store
2592       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2593                                          PtrVT);
2594       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2595     }
2596   }
2597
2598   if (!MemOps.empty())
2599     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2600
2601   return Chain;
2602 }
2603
2604 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2605 // value to MVT::i64 and then truncate to the correct register size.
2606 SDValue
2607 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2608                                      SelectionDAG &DAG, SDValue ArgVal,
2609                                      SDLoc dl) const {
2610   if (Flags.isSExt())
2611     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2612                          DAG.getValueType(ObjectVT));
2613   else if (Flags.isZExt())
2614     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2615                          DAG.getValueType(ObjectVT));
2616
2617   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2618 }
2619
2620 SDValue
2621 PPCTargetLowering::LowerFormalArguments_64SVR4(
2622                                       SDValue Chain,
2623                                       CallingConv::ID CallConv, bool isVarArg,
2624                                       const SmallVectorImpl<ISD::InputArg>
2625                                         &Ins,
2626                                       SDLoc dl, SelectionDAG &DAG,
2627                                       SmallVectorImpl<SDValue> &InVals) const {
2628   // TODO: add description of PPC stack frame format, or at least some docs.
2629   //
2630   bool isELFv2ABI = Subtarget.isELFv2ABI();
2631   bool isLittleEndian = Subtarget.isLittleEndian();
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   MachineFrameInfo *MFI = MF.getFrameInfo();
2634   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2635
2636   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2637          "fastcc not supported on varargs functions");
2638
2639   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2640   // Potential tail calls could cause overwriting of argument stack slots.
2641   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2642                        (CallConv == CallingConv::Fast));
2643   unsigned PtrByteSize = 8;
2644
2645   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2646                                                           isELFv2ABI);
2647
2648   static const MCPhysReg GPR[] = {
2649     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2650     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2651   };
2652
2653   static const MCPhysReg *FPR = GetFPR();
2654
2655   static const MCPhysReg VR[] = {
2656     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2657     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2658   };
2659   static const MCPhysReg VSRH[] = {
2660     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2661     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2662   };
2663
2664   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2665   const unsigned Num_FPR_Regs = 13;
2666   const unsigned Num_VR_Regs  = array_lengthof(VR);
2667
2668   // Do a first pass over the arguments to determine whether the ABI
2669   // guarantees that our caller has allocated the parameter save area
2670   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2671   // in the ELFv2 ABI, it is true if this is a vararg function or if
2672   // any parameter is located in a stack slot.
2673
2674   bool HasParameterArea = !isELFv2ABI || isVarArg;
2675   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2676   unsigned NumBytes = LinkageSize;
2677   unsigned AvailableFPRs = Num_FPR_Regs;
2678   unsigned AvailableVRs = Num_VR_Regs;
2679   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2680     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2681                                PtrByteSize, LinkageSize, ParamAreaSize,
2682                                NumBytes, AvailableFPRs, AvailableVRs))
2683       HasParameterArea = true;
2684
2685   // Add DAG nodes to load the arguments or copy them out of registers.  On
2686   // entry to a function on PPC, the arguments start after the linkage area,
2687   // although the first ones are often in registers.
2688
2689   unsigned ArgOffset = LinkageSize;
2690   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2691   SmallVector<SDValue, 8> MemOps;
2692   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2693   unsigned CurArgIdx = 0;
2694   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2695     SDValue ArgVal;
2696     bool needsLoad = false;
2697     EVT ObjectVT = Ins[ArgNo].VT;
2698     EVT OrigVT = Ins[ArgNo].ArgVT;
2699     unsigned ObjSize = ObjectVT.getStoreSize();
2700     unsigned ArgSize = ObjSize;
2701     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2702     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2703     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2704
2705     // We re-align the argument offset for each argument, except when using the
2706     // fast calling convention, when we need to make sure we do that only when
2707     // we'll actually use a stack slot.
2708     unsigned CurArgOffset, Align;
2709     auto ComputeArgOffset = [&]() {
2710       /* Respect alignment of argument on the stack.  */
2711       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2712       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2713       CurArgOffset = ArgOffset;
2714     };
2715
2716     if (CallConv != CallingConv::Fast) {
2717       ComputeArgOffset();
2718
2719       /* Compute GPR index associated with argument offset.  */
2720       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2721       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2722     }
2723
2724     // FIXME the codegen can be much improved in some cases.
2725     // We do not have to keep everything in memory.
2726     if (Flags.isByVal()) {
2727       if (CallConv == CallingConv::Fast)
2728         ComputeArgOffset();
2729
2730       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2731       ObjSize = Flags.getByValSize();
2732       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2733       // Empty aggregate parameters do not take up registers.  Examples:
2734       //   struct { } a;
2735       //   union  { } b;
2736       //   int c[0];
2737       // etc.  However, we have to provide a place-holder in InVals, so
2738       // pretend we have an 8-byte item at the current address for that
2739       // purpose.
2740       if (!ObjSize) {
2741         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2742         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2743         InVals.push_back(FIN);
2744         continue;
2745       }
2746
2747       // Create a stack object covering all stack doublewords occupied
2748       // by the argument.  If the argument is (fully or partially) on
2749       // the stack, or if the argument is fully in registers but the
2750       // caller has allocated the parameter save anyway, we can refer
2751       // directly to the caller's stack frame.  Otherwise, create a
2752       // local copy in our own frame.
2753       int FI;
2754       if (HasParameterArea ||
2755           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2756         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2757       else
2758         FI = MFI->CreateStackObject(ArgSize, Align, false);
2759       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2760
2761       // Handle aggregates smaller than 8 bytes.
2762       if (ObjSize < PtrByteSize) {
2763         // The value of the object is its address, which differs from the
2764         // address of the enclosing doubleword on big-endian systems.
2765         SDValue Arg = FIN;
2766         if (!isLittleEndian) {
2767           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2768           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2769         }
2770         InVals.push_back(Arg);
2771
2772         if (GPR_idx != Num_GPR_Regs) {
2773           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2774           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2775           SDValue Store;
2776
2777           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2778             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2779                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2780             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2781                                       MachinePointerInfo(FuncArg),
2782                                       ObjType, false, false, 0);
2783           } else {
2784             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2785             // store the whole register as-is to the parameter save area
2786             // slot.
2787             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2788                                  MachinePointerInfo(FuncArg),
2789                                  false, false, 0);
2790           }
2791
2792           MemOps.push_back(Store);
2793         }
2794         // Whether we copied from a register or not, advance the offset
2795         // into the parameter save area by a full doubleword.
2796         ArgOffset += PtrByteSize;
2797         continue;
2798       }
2799
2800       // The value of the object is its address, which is the address of
2801       // its first stack doubleword.
2802       InVals.push_back(FIN);
2803
2804       // Store whatever pieces of the object are in registers to memory.
2805       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2806         if (GPR_idx == Num_GPR_Regs)
2807           break;
2808
2809         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2810         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2811         SDValue Addr = FIN;
2812         if (j) {
2813           SDValue Off = DAG.getConstant(j, PtrVT);
2814           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2815         }
2816         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2817                                      MachinePointerInfo(FuncArg, j),
2818                                      false, false, 0);
2819         MemOps.push_back(Store);
2820         ++GPR_idx;
2821       }
2822       ArgOffset += ArgSize;
2823       continue;
2824     }
2825
2826     switch (ObjectVT.getSimpleVT().SimpleTy) {
2827     default: llvm_unreachable("Unhandled argument type!");
2828     case MVT::i1:
2829     case MVT::i32:
2830     case MVT::i64:
2831       // These can be scalar arguments or elements of an integer array type
2832       // passed directly.  Clang may use those instead of "byval" aggregate
2833       // types to avoid forcing arguments to memory unnecessarily.
2834       if (GPR_idx != Num_GPR_Regs) {
2835         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2836         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2837
2838         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2839           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2840           // value to MVT::i64 and then truncate to the correct register size.
2841           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2842       } else {
2843         if (CallConv == CallingConv::Fast)
2844           ComputeArgOffset();
2845
2846         needsLoad = true;
2847         ArgSize = PtrByteSize;
2848       }
2849       if (CallConv != CallingConv::Fast || needsLoad)
2850         ArgOffset += 8;
2851       break;
2852
2853     case MVT::f32:
2854     case MVT::f64:
2855       // These can be scalar arguments or elements of a float array type
2856       // passed directly.  The latter are used to implement ELFv2 homogenous
2857       // float aggregates.
2858       if (FPR_idx != Num_FPR_Regs) {
2859         unsigned VReg;
2860
2861         if (ObjectVT == MVT::f32)
2862           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2863         else
2864           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
2865                                                 ? &PPC::VSFRCRegClass
2866                                                 : &PPC::F8RCRegClass);
2867
2868         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2869         ++FPR_idx;
2870       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
2871         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
2872         // once we support fp <-> gpr moves.
2873
2874         // This can only ever happen in the presence of f32 array types,
2875         // since otherwise we never run out of FPRs before running out
2876         // of GPRs.
2877         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2878         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2879
2880         if (ObjectVT == MVT::f32) {
2881           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2882             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2883                                  DAG.getConstant(32, MVT::i32));
2884           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2885         }
2886
2887         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2888       } else {
2889         if (CallConv == CallingConv::Fast)
2890           ComputeArgOffset();
2891
2892         needsLoad = true;
2893       }
2894
2895       // When passing an array of floats, the array occupies consecutive
2896       // space in the argument area; only round up to the next doubleword
2897       // at the end of the array.  Otherwise, each float takes 8 bytes.
2898       if (CallConv != CallingConv::Fast || needsLoad) {
2899         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2900         ArgOffset += ArgSize;
2901         if (Flags.isInConsecutiveRegsLast())
2902           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2903       }
2904       break;
2905     case MVT::v4f32:
2906     case MVT::v4i32:
2907     case MVT::v8i16:
2908     case MVT::v16i8:
2909     case MVT::v2f64:
2910     case MVT::v2i64:
2911       // These can be scalar arguments or elements of a vector array type
2912       // passed directly.  The latter are used to implement ELFv2 homogenous
2913       // vector aggregates.
2914       if (VR_idx != Num_VR_Regs) {
2915         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2916                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2917                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2918         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2919         ++VR_idx;
2920       } else {
2921         if (CallConv == CallingConv::Fast)
2922           ComputeArgOffset();
2923
2924         needsLoad = true;
2925       }
2926       if (CallConv != CallingConv::Fast || needsLoad)
2927         ArgOffset += 16;
2928       break;
2929     }
2930
2931     // We need to load the argument to a virtual register if we determined
2932     // above that we ran out of physical registers of the appropriate type.
2933     if (needsLoad) {
2934       if (ObjSize < ArgSize && !isLittleEndian)
2935         CurArgOffset += ArgSize - ObjSize;
2936       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2937       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2938       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2939                            false, false, false, 0);
2940     }
2941
2942     InVals.push_back(ArgVal);
2943   }
2944
2945   // Area that is at least reserved in the caller of this function.
2946   unsigned MinReservedArea;
2947   if (HasParameterArea)
2948     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2949   else
2950     MinReservedArea = LinkageSize;
2951
2952   // Set the size that is at least reserved in caller of this function.  Tail
2953   // call optimized functions' reserved stack space needs to be aligned so that
2954   // taking the difference between two stack areas will result in an aligned
2955   // stack.
2956   MinReservedArea =
2957       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2958   FuncInfo->setMinReservedArea(MinReservedArea);
2959
2960   // If the function takes variable number of arguments, make a frame index for
2961   // the start of the first vararg value... for expansion of llvm.va_start.
2962   if (isVarArg) {
2963     int Depth = ArgOffset;
2964
2965     FuncInfo->setVarArgsFrameIndex(
2966       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2967     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2968
2969     // If this function is vararg, store any remaining integer argument regs
2970     // to their spots on the stack so that they may be loaded by deferencing the
2971     // result of va_next.
2972     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2973          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2974       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2975       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2976       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2977                                    MachinePointerInfo(), false, false, 0);
2978       MemOps.push_back(Store);
2979       // Increment the address by four for the next argument to store
2980       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2981       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2982     }
2983   }
2984
2985   if (!MemOps.empty())
2986     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2987
2988   return Chain;
2989 }
2990
2991 SDValue
2992 PPCTargetLowering::LowerFormalArguments_Darwin(
2993                                       SDValue Chain,
2994                                       CallingConv::ID CallConv, bool isVarArg,
2995                                       const SmallVectorImpl<ISD::InputArg>
2996                                         &Ins,
2997                                       SDLoc dl, SelectionDAG &DAG,
2998                                       SmallVectorImpl<SDValue> &InVals) const {
2999   // TODO: add description of PPC stack frame format, or at least some docs.
3000   //
3001   MachineFunction &MF = DAG.getMachineFunction();
3002   MachineFrameInfo *MFI = MF.getFrameInfo();
3003   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3004
3005   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3006   bool isPPC64 = PtrVT == MVT::i64;
3007   // Potential tail calls could cause overwriting of argument stack slots.
3008   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3009                        (CallConv == CallingConv::Fast));
3010   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3011
3012   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
3013                                                           false);
3014   unsigned ArgOffset = LinkageSize;
3015   // Area that is at least reserved in caller of this function.
3016   unsigned MinReservedArea = ArgOffset;
3017
3018   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3019     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3020     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3021   };
3022   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3023     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3024     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3025   };
3026
3027   static const MCPhysReg *FPR = GetFPR();
3028
3029   static const MCPhysReg VR[] = {
3030     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3031     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3032   };
3033
3034   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3035   const unsigned Num_FPR_Regs = 13;
3036   const unsigned Num_VR_Regs  = array_lengthof( VR);
3037
3038   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3039
3040   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3041
3042   // In 32-bit non-varargs functions, the stack space for vectors is after the
3043   // stack space for non-vectors.  We do not use this space unless we have
3044   // too many vectors to fit in registers, something that only occurs in
3045   // constructed examples:), but we have to walk the arglist to figure
3046   // that out...for the pathological case, compute VecArgOffset as the
3047   // start of the vector parameter area.  Computing VecArgOffset is the
3048   // entire point of the following loop.
3049   unsigned VecArgOffset = ArgOffset;
3050   if (!isVarArg && !isPPC64) {
3051     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3052          ++ArgNo) {
3053       EVT ObjectVT = Ins[ArgNo].VT;
3054       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3055
3056       if (Flags.isByVal()) {
3057         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3058         unsigned ObjSize = Flags.getByValSize();
3059         unsigned ArgSize =
3060                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3061         VecArgOffset += ArgSize;
3062         continue;
3063       }
3064
3065       switch(ObjectVT.getSimpleVT().SimpleTy) {
3066       default: llvm_unreachable("Unhandled argument type!");
3067       case MVT::i1:
3068       case MVT::i32:
3069       case MVT::f32:
3070         VecArgOffset += 4;
3071         break;
3072       case MVT::i64:  // PPC64
3073       case MVT::f64:
3074         // FIXME: We are guaranteed to be !isPPC64 at this point.
3075         // Does MVT::i64 apply?
3076         VecArgOffset += 8;
3077         break;
3078       case MVT::v4f32:
3079       case MVT::v4i32:
3080       case MVT::v8i16:
3081       case MVT::v16i8:
3082         // Nothing to do, we're only looking at Nonvector args here.
3083         break;
3084       }
3085     }
3086   }
3087   // We've found where the vector parameter area in memory is.  Skip the
3088   // first 12 parameters; these don't use that memory.
3089   VecArgOffset = ((VecArgOffset+15)/16)*16;
3090   VecArgOffset += 12*16;
3091
3092   // Add DAG nodes to load the arguments or copy them out of registers.  On
3093   // entry to a function on PPC, the arguments start after the linkage area,
3094   // although the first ones are often in registers.
3095
3096   SmallVector<SDValue, 8> MemOps;
3097   unsigned nAltivecParamsAtEnd = 0;
3098   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3099   unsigned CurArgIdx = 0;
3100   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3101     SDValue ArgVal;
3102     bool needsLoad = false;
3103     EVT ObjectVT = Ins[ArgNo].VT;
3104     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3105     unsigned ArgSize = ObjSize;
3106     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3107     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3108     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3109
3110     unsigned CurArgOffset = ArgOffset;
3111
3112     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3113     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3114         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3115       if (isVarArg || isPPC64) {
3116         MinReservedArea = ((MinReservedArea+15)/16)*16;
3117         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3118                                                   Flags,
3119                                                   PtrByteSize);
3120       } else  nAltivecParamsAtEnd++;
3121     } else
3122       // Calculate min reserved area.
3123       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3124                                                 Flags,
3125                                                 PtrByteSize);
3126
3127     // FIXME the codegen can be much improved in some cases.
3128     // We do not have to keep everything in memory.
3129     if (Flags.isByVal()) {
3130       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3131       ObjSize = Flags.getByValSize();
3132       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3133       // Objects of size 1 and 2 are right justified, everything else is
3134       // left justified.  This means the memory address is adjusted forwards.
3135       if (ObjSize==1 || ObjSize==2) {
3136         CurArgOffset = CurArgOffset + (4 - ObjSize);
3137       }
3138       // The value of the object is its address.
3139       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3140       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3141       InVals.push_back(FIN);
3142       if (ObjSize==1 || ObjSize==2) {
3143         if (GPR_idx != Num_GPR_Regs) {
3144           unsigned VReg;
3145           if (isPPC64)
3146             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3147           else
3148             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3149           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3150           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3151           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3152                                             MachinePointerInfo(FuncArg),
3153                                             ObjType, false, false, 0);
3154           MemOps.push_back(Store);
3155           ++GPR_idx;
3156         }
3157
3158         ArgOffset += PtrByteSize;
3159
3160         continue;
3161       }
3162       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3163         // Store whatever pieces of the object are in registers
3164         // to memory.  ArgOffset will be the address of the beginning
3165         // of the object.
3166         if (GPR_idx != Num_GPR_Regs) {
3167           unsigned VReg;
3168           if (isPPC64)
3169             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3170           else
3171             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3172           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3173           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3174           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3175           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3176                                        MachinePointerInfo(FuncArg, j),
3177                                        false, false, 0);
3178           MemOps.push_back(Store);
3179           ++GPR_idx;
3180           ArgOffset += PtrByteSize;
3181         } else {
3182           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3183           break;
3184         }
3185       }
3186       continue;
3187     }
3188
3189     switch (ObjectVT.getSimpleVT().SimpleTy) {
3190     default: llvm_unreachable("Unhandled argument type!");
3191     case MVT::i1:
3192     case MVT::i32:
3193       if (!isPPC64) {
3194         if (GPR_idx != Num_GPR_Regs) {
3195           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3196           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3197
3198           if (ObjectVT == MVT::i1)
3199             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3200
3201           ++GPR_idx;
3202         } else {
3203           needsLoad = true;
3204           ArgSize = PtrByteSize;
3205         }
3206         // All int arguments reserve stack space in the Darwin ABI.
3207         ArgOffset += PtrByteSize;
3208         break;
3209       }
3210       // FALLTHROUGH
3211     case MVT::i64:  // PPC64
3212       if (GPR_idx != Num_GPR_Regs) {
3213         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3214         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3215
3216         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3217           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3218           // value to MVT::i64 and then truncate to the correct register size.
3219           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3220
3221         ++GPR_idx;
3222       } else {
3223         needsLoad = true;
3224         ArgSize = PtrByteSize;
3225       }
3226       // All int arguments reserve stack space in the Darwin ABI.
3227       ArgOffset += 8;
3228       break;
3229
3230     case MVT::f32:
3231     case MVT::f64:
3232       // Every 4 bytes of argument space consumes one of the GPRs available for
3233       // argument passing.
3234       if (GPR_idx != Num_GPR_Regs) {
3235         ++GPR_idx;
3236         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3237           ++GPR_idx;
3238       }
3239       if (FPR_idx != Num_FPR_Regs) {
3240         unsigned VReg;
3241
3242         if (ObjectVT == MVT::f32)
3243           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3244         else
3245           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3246
3247         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3248         ++FPR_idx;
3249       } else {
3250         needsLoad = true;
3251       }
3252
3253       // All FP arguments reserve stack space in the Darwin ABI.
3254       ArgOffset += isPPC64 ? 8 : ObjSize;
3255       break;
3256     case MVT::v4f32:
3257     case MVT::v4i32:
3258     case MVT::v8i16:
3259     case MVT::v16i8:
3260       // Note that vector arguments in registers don't reserve stack space,
3261       // except in varargs functions.
3262       if (VR_idx != Num_VR_Regs) {
3263         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3264         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3265         if (isVarArg) {
3266           while ((ArgOffset % 16) != 0) {
3267             ArgOffset += PtrByteSize;
3268             if (GPR_idx != Num_GPR_Regs)
3269               GPR_idx++;
3270           }
3271           ArgOffset += 16;
3272           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3273         }
3274         ++VR_idx;
3275       } else {
3276         if (!isVarArg && !isPPC64) {
3277           // Vectors go after all the nonvectors.
3278           CurArgOffset = VecArgOffset;
3279           VecArgOffset += 16;
3280         } else {
3281           // Vectors are aligned.
3282           ArgOffset = ((ArgOffset+15)/16)*16;
3283           CurArgOffset = ArgOffset;
3284           ArgOffset += 16;
3285         }
3286         needsLoad = true;
3287       }
3288       break;
3289     }
3290
3291     // We need to load the argument to a virtual register if we determined above
3292     // that we ran out of physical registers of the appropriate type.
3293     if (needsLoad) {
3294       int FI = MFI->CreateFixedObject(ObjSize,
3295                                       CurArgOffset + (ArgSize - ObjSize),
3296                                       isImmutable);
3297       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3298       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3299                            false, false, false, 0);
3300     }
3301
3302     InVals.push_back(ArgVal);
3303   }
3304
3305   // Allow for Altivec parameters at the end, if needed.
3306   if (nAltivecParamsAtEnd) {
3307     MinReservedArea = ((MinReservedArea+15)/16)*16;
3308     MinReservedArea += 16*nAltivecParamsAtEnd;
3309   }
3310
3311   // Area that is at least reserved in the caller of this function.
3312   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3313
3314   // Set the size that is at least reserved in caller of this function.  Tail
3315   // call optimized functions' reserved stack space needs to be aligned so that
3316   // taking the difference between two stack areas will result in an aligned
3317   // stack.
3318   MinReservedArea =
3319       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3320   FuncInfo->setMinReservedArea(MinReservedArea);
3321
3322   // If the function takes variable number of arguments, make a frame index for
3323   // the start of the first vararg value... for expansion of llvm.va_start.
3324   if (isVarArg) {
3325     int Depth = ArgOffset;
3326
3327     FuncInfo->setVarArgsFrameIndex(
3328       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3329                              Depth, true));
3330     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3331
3332     // If this function is vararg, store any remaining integer argument regs
3333     // to their spots on the stack so that they may be loaded by deferencing the
3334     // result of va_next.
3335     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3336       unsigned VReg;
3337
3338       if (isPPC64)
3339         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3340       else
3341         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3342
3343       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3344       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3345                                    MachinePointerInfo(), false, false, 0);
3346       MemOps.push_back(Store);
3347       // Increment the address by four for the next argument to store
3348       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3349       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3350     }
3351   }
3352
3353   if (!MemOps.empty())
3354     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3355
3356   return Chain;
3357 }
3358
3359 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3360 /// adjusted to accommodate the arguments for the tailcall.
3361 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3362                                    unsigned ParamSize) {
3363
3364   if (!isTailCall) return 0;
3365
3366   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3367   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3368   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3369   // Remember only if the new adjustement is bigger.
3370   if (SPDiff < FI->getTailCallSPDelta())
3371     FI->setTailCallSPDelta(SPDiff);
3372
3373   return SPDiff;
3374 }
3375
3376 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3377 /// for tail call optimization. Targets which want to do tail call
3378 /// optimization should implement this function.
3379 bool
3380 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3381                                                      CallingConv::ID CalleeCC,
3382                                                      bool isVarArg,
3383                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3384                                                      SelectionDAG& DAG) const {
3385   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3386     return false;
3387
3388   // Variable argument functions are not supported.
3389   if (isVarArg)
3390     return false;
3391
3392   MachineFunction &MF = DAG.getMachineFunction();
3393   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3394   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3395     // Functions containing by val parameters are not supported.
3396     for (unsigned i = 0; i != Ins.size(); i++) {
3397        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3398        if (Flags.isByVal()) return false;
3399     }
3400
3401     // Non-PIC/GOT tail calls are supported.
3402     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3403       return true;
3404
3405     // At the moment we can only do local tail calls (in same module, hidden
3406     // or protected) if we are generating PIC.
3407     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3408       return G->getGlobal()->hasHiddenVisibility()
3409           || G->getGlobal()->hasProtectedVisibility();
3410   }
3411
3412   return false;
3413 }
3414
3415 /// isCallCompatibleAddress - Return the immediate to use if the specified
3416 /// 32-bit value is representable in the immediate field of a BxA instruction.
3417 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3418   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3419   if (!C) return nullptr;
3420
3421   int Addr = C->getZExtValue();
3422   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3423       SignExtend32<26>(Addr) != Addr)
3424     return nullptr;  // Top 6 bits have to be sext of immediate.
3425
3426   return DAG.getConstant((int)C->getZExtValue() >> 2,
3427                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3428 }
3429
3430 namespace {
3431
3432 struct TailCallArgumentInfo {
3433   SDValue Arg;
3434   SDValue FrameIdxOp;
3435   int       FrameIdx;
3436
3437   TailCallArgumentInfo() : FrameIdx(0) {}
3438 };
3439
3440 }
3441
3442 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3443 static void
3444 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3445                                            SDValue Chain,
3446                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3447                    SmallVectorImpl<SDValue> &MemOpChains,
3448                    SDLoc dl) {
3449   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3450     SDValue Arg = TailCallArgs[i].Arg;
3451     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3452     int FI = TailCallArgs[i].FrameIdx;
3453     // Store relative to framepointer.
3454     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3455                                        MachinePointerInfo::getFixedStack(FI),
3456                                        false, false, 0));
3457   }
3458 }
3459
3460 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3461 /// the appropriate stack slot for the tail call optimized function call.
3462 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3463                                                MachineFunction &MF,
3464                                                SDValue Chain,
3465                                                SDValue OldRetAddr,
3466                                                SDValue OldFP,
3467                                                int SPDiff,
3468                                                bool isPPC64,
3469                                                bool isDarwinABI,
3470                                                SDLoc dl) {
3471   if (SPDiff) {
3472     // Calculate the new stack slot for the return address.
3473     int SlotSize = isPPC64 ? 8 : 4;
3474     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3475                                                                    isDarwinABI);
3476     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3477                                                           NewRetAddrLoc, true);
3478     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3479     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3480     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3481                          MachinePointerInfo::getFixedStack(NewRetAddr),
3482                          false, false, 0);
3483
3484     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3485     // slot as the FP is never overwritten.
3486     if (isDarwinABI) {
3487       int NewFPLoc =
3488         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3489       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3490                                                           true);
3491       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3492       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3493                            MachinePointerInfo::getFixedStack(NewFPIdx),
3494                            false, false, 0);
3495     }
3496   }
3497   return Chain;
3498 }
3499
3500 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3501 /// the position of the argument.
3502 static void
3503 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3504                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3505                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3506   int Offset = ArgOffset + SPDiff;
3507   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3508   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3509   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3510   SDValue FIN = DAG.getFrameIndex(FI, VT);
3511   TailCallArgumentInfo Info;
3512   Info.Arg = Arg;
3513   Info.FrameIdxOp = FIN;
3514   Info.FrameIdx = FI;
3515   TailCallArguments.push_back(Info);
3516 }
3517
3518 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3519 /// stack slot. Returns the chain as result and the loaded frame pointers in
3520 /// LROpOut/FPOpout. Used when tail calling.
3521 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3522                                                         int SPDiff,
3523                                                         SDValue Chain,
3524                                                         SDValue &LROpOut,
3525                                                         SDValue &FPOpOut,
3526                                                         bool isDarwinABI,
3527                                                         SDLoc dl) const {
3528   if (SPDiff) {
3529     // Load the LR and FP stack slot for later adjusting.
3530     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3531     LROpOut = getReturnAddrFrameIndex(DAG);
3532     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3533                           false, false, false, 0);
3534     Chain = SDValue(LROpOut.getNode(), 1);
3535
3536     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3537     // slot as the FP is never overwritten.
3538     if (isDarwinABI) {
3539       FPOpOut = getFramePointerFrameIndex(DAG);
3540       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3541                             false, false, false, 0);
3542       Chain = SDValue(FPOpOut.getNode(), 1);
3543     }
3544   }
3545   return Chain;
3546 }
3547
3548 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3549 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3550 /// specified by the specific parameter attribute. The copy will be passed as
3551 /// a byval function parameter.
3552 /// Sometimes what we are copying is the end of a larger object, the part that
3553 /// does not fit in registers.
3554 static SDValue
3555 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3556                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3557                           SDLoc dl) {
3558   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3559   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3560                        false, false, MachinePointerInfo(),
3561                        MachinePointerInfo());
3562 }
3563
3564 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3565 /// tail calls.
3566 static void
3567 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3568                  SDValue Arg, SDValue PtrOff, int SPDiff,
3569                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3570                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3571                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3572                  SDLoc dl) {
3573   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3574   if (!isTailCall) {
3575     if (isVector) {
3576       SDValue StackPtr;
3577       if (isPPC64)
3578         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3579       else
3580         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3581       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3582                            DAG.getConstant(ArgOffset, PtrVT));
3583     }
3584     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3585                                        MachinePointerInfo(), false, false, 0));
3586   // Calculate and remember argument location.
3587   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3588                                   TailCallArguments);
3589 }
3590
3591 static
3592 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3593                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3594                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3595                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3596   MachineFunction &MF = DAG.getMachineFunction();
3597
3598   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3599   // might overwrite each other in case of tail call optimization.
3600   SmallVector<SDValue, 8> MemOpChains2;
3601   // Do not flag preceding copytoreg stuff together with the following stuff.
3602   InFlag = SDValue();
3603   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3604                                     MemOpChains2, dl);
3605   if (!MemOpChains2.empty())
3606     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3607
3608   // Store the return address to the appropriate stack slot.
3609   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3610                                         isPPC64, isDarwinABI, dl);
3611
3612   // Emit callseq_end just before tailcall node.
3613   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3614                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3615   InFlag = Chain.getValue(1);
3616 }
3617
3618 // Is this global address that of a function that can be called by name? (as
3619 // opposed to something that must hold a descriptor for an indirect call).
3620 static bool isFunctionGlobalAddress(SDValue Callee) {
3621   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3622     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3623         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3624       return false;
3625
3626     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3627   }
3628
3629   return false;
3630 }
3631
3632 static
3633 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3634                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3635                      bool isTailCall, bool IsPatchPoint,
3636                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3637                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3638                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3639
3640   bool isPPC64 = Subtarget.isPPC64();
3641   bool isSVR4ABI = Subtarget.isSVR4ABI();
3642   bool isELFv2ABI = Subtarget.isELFv2ABI();
3643
3644   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3645   NodeTys.push_back(MVT::Other);   // Returns a chain
3646   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3647
3648   unsigned CallOpc = PPCISD::CALL;
3649
3650   bool needIndirectCall = true;
3651   if (!isSVR4ABI || !isPPC64)
3652     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3653       // If this is an absolute destination address, use the munged value.
3654       Callee = SDValue(Dest, 0);
3655       needIndirectCall = false;
3656     }
3657
3658   if (isFunctionGlobalAddress(Callee)) {
3659     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3660     // A call to a TLS address is actually an indirect call to a
3661     // thread-specific pointer.
3662     unsigned OpFlags = 0;
3663     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3664          (Subtarget.getTargetTriple().isMacOSX() &&
3665           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3666          (G->getGlobal()->isDeclaration() ||
3667           G->getGlobal()->isWeakForLinker())) ||
3668         (Subtarget.isTargetELF() && !isPPC64 &&
3669          !G->getGlobal()->hasLocalLinkage() &&
3670          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3671       // PC-relative references to external symbols should go through $stub,
3672       // unless we're building with the leopard linker or later, which
3673       // automatically synthesizes these stubs.
3674       OpFlags = PPCII::MO_PLT_OR_STUB;
3675     }
3676
3677     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3678     // every direct call is) turn it into a TargetGlobalAddress /
3679     // TargetExternalSymbol node so that legalize doesn't hack it.
3680     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3681                                         Callee.getValueType(), 0, OpFlags);
3682     needIndirectCall = false;
3683   }
3684
3685   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3686     unsigned char OpFlags = 0;
3687
3688     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3689          (Subtarget.getTargetTriple().isMacOSX() &&
3690           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3691         (Subtarget.isTargetELF() && !isPPC64 &&
3692          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3693       // PC-relative references to external symbols should go through $stub,
3694       // unless we're building with the leopard linker or later, which
3695       // automatically synthesizes these stubs.
3696       OpFlags = PPCII::MO_PLT_OR_STUB;
3697     }
3698
3699     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3700                                          OpFlags);
3701     needIndirectCall = false;
3702   }
3703
3704   if (IsPatchPoint) {
3705     // We'll form an invalid direct call when lowering a patchpoint; the full
3706     // sequence for an indirect call is complicated, and many of the
3707     // instructions introduced might have side effects (and, thus, can't be
3708     // removed later). The call itself will be removed as soon as the
3709     // argument/return lowering is complete, so the fact that it has the wrong
3710     // kind of operands should not really matter.
3711     needIndirectCall = false;
3712   }
3713
3714   if (needIndirectCall) {
3715     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3716     // to do the call, we can't use PPCISD::CALL.
3717     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3718
3719     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3720       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3721       // entry point, but to the function descriptor (the function entry point
3722       // address is part of the function descriptor though).
3723       // The function descriptor is a three doubleword structure with the
3724       // following fields: function entry point, TOC base address and
3725       // environment pointer.
3726       // Thus for a call through a function pointer, the following actions need
3727       // to be performed:
3728       //   1. Save the TOC of the caller in the TOC save area of its stack
3729       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3730       //   2. Load the address of the function entry point from the function
3731       //      descriptor.
3732       //   3. Load the TOC of the callee from the function descriptor into r2.
3733       //   4. Load the environment pointer from the function descriptor into
3734       //      r11.
3735       //   5. Branch to the function entry point address.
3736       //   6. On return of the callee, the TOC of the caller needs to be
3737       //      restored (this is done in FinishCall()).
3738       //
3739       // The loads are scheduled at the beginning of the call sequence, and the
3740       // register copies are flagged together to ensure that no other
3741       // operations can be scheduled in between. E.g. without flagging the
3742       // copies together, a TOC access in the caller could be scheduled between
3743       // the assignment of the callee TOC and the branch to the callee, which
3744       // results in the TOC access going through the TOC of the callee instead
3745       // of going through the TOC of the caller, which leads to incorrect code.
3746
3747       // Load the address of the function entry point from the function
3748       // descriptor.
3749       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
3750       if (LDChain.getValueType() == MVT::Glue)
3751         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
3752
3753       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
3754
3755       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
3756       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
3757                                         false, false, LoadsInv, 8);
3758
3759       // Load environment pointer into r11.
3760       SDValue PtrOff = DAG.getIntPtrConstant(16);
3761       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3762       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
3763                                        MPI.getWithOffset(16), false, false,
3764                                        LoadsInv, 8);
3765
3766       SDValue TOCOff = DAG.getIntPtrConstant(8);
3767       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3768       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
3769                                    MPI.getWithOffset(8), false, false,
3770                                    LoadsInv, 8);
3771
3772       setUsesTOCBasePtr(DAG);
3773       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
3774                                         InFlag);
3775       Chain = TOCVal.getValue(0);
3776       InFlag = TOCVal.getValue(1);
3777
3778       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3779                                         InFlag);
3780
3781       Chain = EnvVal.getValue(0);
3782       InFlag = EnvVal.getValue(1);
3783
3784       MTCTROps[0] = Chain;
3785       MTCTROps[1] = LoadFuncPtr;
3786       MTCTROps[2] = InFlag;
3787     }
3788
3789     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3790                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3791     InFlag = Chain.getValue(1);
3792
3793     NodeTys.clear();
3794     NodeTys.push_back(MVT::Other);
3795     NodeTys.push_back(MVT::Glue);
3796     Ops.push_back(Chain);
3797     CallOpc = PPCISD::BCTRL;
3798     Callee.setNode(nullptr);
3799     // Add use of X11 (holding environment pointer)
3800     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3801       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3802     // Add CTR register as callee so a bctr can be emitted later.
3803     if (isTailCall)
3804       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3805   }
3806
3807   // If this is a direct call, pass the chain and the callee.
3808   if (Callee.getNode()) {
3809     Ops.push_back(Chain);
3810     Ops.push_back(Callee);
3811   }
3812   // If this is a tail call add stack pointer delta.
3813   if (isTailCall)
3814     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3815
3816   // Add argument registers to the end of the list so that they are known live
3817   // into the call.
3818   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3819     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3820                                   RegsToPass[i].second.getValueType()));
3821
3822   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
3823   // into the call.
3824   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
3825     setUsesTOCBasePtr(DAG);
3826     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3827   }
3828
3829   return CallOpc;
3830 }
3831
3832 static
3833 bool isLocalCall(const SDValue &Callee)
3834 {
3835   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3836     return !G->getGlobal()->isDeclaration() &&
3837            !G->getGlobal()->isWeakForLinker();
3838   return false;
3839 }
3840
3841 SDValue
3842 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3843                                    CallingConv::ID CallConv, bool isVarArg,
3844                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3845                                    SDLoc dl, SelectionDAG &DAG,
3846                                    SmallVectorImpl<SDValue> &InVals) const {
3847
3848   SmallVector<CCValAssign, 16> RVLocs;
3849   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3850                     *DAG.getContext());
3851   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3852
3853   // Copy all of the result registers out of their specified physreg.
3854   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3855     CCValAssign &VA = RVLocs[i];
3856     assert(VA.isRegLoc() && "Can only return in registers!");
3857
3858     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3859                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3860     Chain = Val.getValue(1);
3861     InFlag = Val.getValue(2);
3862
3863     switch (VA.getLocInfo()) {
3864     default: llvm_unreachable("Unknown loc info!");
3865     case CCValAssign::Full: break;
3866     case CCValAssign::AExt:
3867       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3868       break;
3869     case CCValAssign::ZExt:
3870       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3871                         DAG.getValueType(VA.getValVT()));
3872       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3873       break;
3874     case CCValAssign::SExt:
3875       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3876                         DAG.getValueType(VA.getValVT()));
3877       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3878       break;
3879     }
3880
3881     InVals.push_back(Val);
3882   }
3883
3884   return Chain;
3885 }
3886
3887 SDValue
3888 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3889                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
3890                               SelectionDAG &DAG,
3891                               SmallVector<std::pair<unsigned, SDValue>, 8>
3892                                 &RegsToPass,
3893                               SDValue InFlag, SDValue Chain,
3894                               SDValue CallSeqStart, SDValue &Callee,
3895                               int SPDiff, unsigned NumBytes,
3896                               const SmallVectorImpl<ISD::InputArg> &Ins,
3897                               SmallVectorImpl<SDValue> &InVals,
3898                               ImmutableCallSite *CS) const {
3899
3900   bool isELFv2ABI = Subtarget.isELFv2ABI();
3901   std::vector<EVT> NodeTys;
3902   SmallVector<SDValue, 8> Ops;
3903   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
3904                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
3905                                  Ops, NodeTys, CS, Subtarget);
3906
3907   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3908   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3909     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3910
3911   // When performing tail call optimization the callee pops its arguments off
3912   // the stack. Account for this here so these bytes can be pushed back on in
3913   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3914   int BytesCalleePops =
3915     (CallConv == CallingConv::Fast &&
3916      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3917
3918   // Add a register mask operand representing the call-preserved registers.
3919   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3920   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3921   assert(Mask && "Missing call preserved mask for calling convention");
3922   Ops.push_back(DAG.getRegisterMask(Mask));
3923
3924   if (InFlag.getNode())
3925     Ops.push_back(InFlag);
3926
3927   // Emit tail call.
3928   if (isTailCall) {
3929     assert(((Callee.getOpcode() == ISD::Register &&
3930              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3931             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3932             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3933             isa<ConstantSDNode>(Callee)) &&
3934     "Expecting an global address, external symbol, absolute value or register");
3935
3936     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3937   }
3938
3939   // Add a NOP immediately after the branch instruction when using the 64-bit
3940   // SVR4 ABI. At link time, if caller and callee are in a different module and
3941   // thus have a different TOC, the call will be replaced with a call to a stub
3942   // function which saves the current TOC, loads the TOC of the callee and
3943   // branches to the callee. The NOP will be replaced with a load instruction
3944   // which restores the TOC of the caller from the TOC save slot of the current
3945   // stack frame. If caller and callee belong to the same module (and have the
3946   // same TOC), the NOP will remain unchanged.
3947
3948   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
3949       !IsPatchPoint) {
3950     if (CallOpc == PPCISD::BCTRL) {
3951       // This is a call through a function pointer.
3952       // Restore the caller TOC from the save area into R2.
3953       // See PrepareCall() for more information about calls through function
3954       // pointers in the 64-bit SVR4 ABI.
3955       // We are using a target-specific load with r2 hard coded, because the
3956       // result of a target-independent load would never go directly into r2,
3957       // since r2 is a reserved register (which prevents the register allocator
3958       // from allocating it), resulting in an additional register being
3959       // allocated and an unnecessary move instruction being generated.
3960       CallOpc = PPCISD::BCTRL_LOAD_TOC;
3961
3962       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3963       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3964       unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3965       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3966       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3967
3968       // The address needs to go after the chain input but before the flag (or
3969       // any other variadic arguments).
3970       Ops.insert(std::next(Ops.begin()), AddTOC);
3971     } else if ((CallOpc == PPCISD::CALL) &&
3972                (!isLocalCall(Callee) ||
3973                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
3974       // Otherwise insert NOP for non-local calls.
3975       CallOpc = PPCISD::CALL_NOP;
3976   }
3977
3978   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3979   InFlag = Chain.getValue(1);
3980
3981   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3982                              DAG.getIntPtrConstant(BytesCalleePops, true),
3983                              InFlag, dl);
3984   if (!Ins.empty())
3985     InFlag = Chain.getValue(1);
3986
3987   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3988                          Ins, dl, DAG, InVals);
3989 }
3990
3991 SDValue
3992 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3993                              SmallVectorImpl<SDValue> &InVals) const {
3994   SelectionDAG &DAG                     = CLI.DAG;
3995   SDLoc &dl                             = CLI.DL;
3996   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3997   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3998   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3999   SDValue Chain                         = CLI.Chain;
4000   SDValue Callee                        = CLI.Callee;
4001   bool &isTailCall                      = CLI.IsTailCall;
4002   CallingConv::ID CallConv              = CLI.CallConv;
4003   bool isVarArg                         = CLI.IsVarArg;
4004   bool IsPatchPoint                     = CLI.IsPatchPoint;
4005   ImmutableCallSite *CS                 = CLI.CS;
4006
4007   if (isTailCall)
4008     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4009                                                    Ins, DAG);
4010
4011   if (!isTailCall && CS && CS->isMustTailCall())
4012     report_fatal_error("failed to perform tail call elimination on a call "
4013                        "site marked musttail");
4014
4015   if (Subtarget.isSVR4ABI()) {
4016     if (Subtarget.isPPC64())
4017       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4018                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4019                               dl, DAG, InVals, CS);
4020     else
4021       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4022                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4023                               dl, DAG, InVals, CS);
4024   }
4025
4026   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4027                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4028                           dl, DAG, InVals, CS);
4029 }
4030
4031 SDValue
4032 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4033                                     CallingConv::ID CallConv, bool isVarArg,
4034                                     bool isTailCall, bool IsPatchPoint,
4035                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4036                                     const SmallVectorImpl<SDValue> &OutVals,
4037                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4038                                     SDLoc dl, SelectionDAG &DAG,
4039                                     SmallVectorImpl<SDValue> &InVals,
4040                                     ImmutableCallSite *CS) const {
4041   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4042   // of the 32-bit SVR4 ABI stack frame layout.
4043
4044   assert((CallConv == CallingConv::C ||
4045           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4046
4047   unsigned PtrByteSize = 4;
4048
4049   MachineFunction &MF = DAG.getMachineFunction();
4050
4051   // Mark this function as potentially containing a function that contains a
4052   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4053   // and restoring the callers stack pointer in this functions epilog. This is
4054   // done because by tail calling the called function might overwrite the value
4055   // in this function's (MF) stack pointer stack slot 0(SP).
4056   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4057       CallConv == CallingConv::Fast)
4058     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4059
4060   // Count how many bytes are to be pushed on the stack, including the linkage
4061   // area, parameter list area and the part of the local variable space which
4062   // contains copies of aggregates which are passed by value.
4063
4064   // Assign locations to all of the outgoing arguments.
4065   SmallVector<CCValAssign, 16> ArgLocs;
4066   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4067                  *DAG.getContext());
4068
4069   // Reserve space for the linkage area on the stack.
4070   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4071                        PtrByteSize);
4072
4073   if (isVarArg) {
4074     // Handle fixed and variable vector arguments differently.
4075     // Fixed vector arguments go into registers as long as registers are
4076     // available. Variable vector arguments always go into memory.
4077     unsigned NumArgs = Outs.size();
4078
4079     for (unsigned i = 0; i != NumArgs; ++i) {
4080       MVT ArgVT = Outs[i].VT;
4081       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4082       bool Result;
4083
4084       if (Outs[i].IsFixed) {
4085         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4086                                CCInfo);
4087       } else {
4088         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4089                                       ArgFlags, CCInfo);
4090       }
4091
4092       if (Result) {
4093 #ifndef NDEBUG
4094         errs() << "Call operand #" << i << " has unhandled type "
4095              << EVT(ArgVT).getEVTString() << "\n";
4096 #endif
4097         llvm_unreachable(nullptr);
4098       }
4099     }
4100   } else {
4101     // All arguments are treated the same.
4102     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4103   }
4104
4105   // Assign locations to all of the outgoing aggregate by value arguments.
4106   SmallVector<CCValAssign, 16> ByValArgLocs;
4107   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4108                       ByValArgLocs, *DAG.getContext());
4109
4110   // Reserve stack space for the allocations in CCInfo.
4111   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4112
4113   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4114
4115   // Size of the linkage area, parameter list area and the part of the local
4116   // space variable where copies of aggregates which are passed by value are
4117   // stored.
4118   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4119
4120   // Calculate by how many bytes the stack has to be adjusted in case of tail
4121   // call optimization.
4122   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4123
4124   // Adjust the stack pointer for the new arguments...
4125   // These operations are automatically eliminated by the prolog/epilog pass
4126   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4127                                dl);
4128   SDValue CallSeqStart = Chain;
4129
4130   // Load the return address and frame pointer so it can be moved somewhere else
4131   // later.
4132   SDValue LROp, FPOp;
4133   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4134                                        dl);
4135
4136   // Set up a copy of the stack pointer for use loading and storing any
4137   // arguments that may not fit in the registers available for argument
4138   // passing.
4139   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4140
4141   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4142   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4143   SmallVector<SDValue, 8> MemOpChains;
4144
4145   bool seenFloatArg = false;
4146   // Walk the register/memloc assignments, inserting copies/loads.
4147   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4148        i != e;
4149        ++i) {
4150     CCValAssign &VA = ArgLocs[i];
4151     SDValue Arg = OutVals[i];
4152     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4153
4154     if (Flags.isByVal()) {
4155       // Argument is an aggregate which is passed by value, thus we need to
4156       // create a copy of it in the local variable space of the current stack
4157       // frame (which is the stack frame of the caller) and pass the address of
4158       // this copy to the callee.
4159       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4160       CCValAssign &ByValVA = ByValArgLocs[j++];
4161       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4162
4163       // Memory reserved in the local variable space of the callers stack frame.
4164       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4165
4166       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4167       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4168
4169       // Create a copy of the argument in the local area of the current
4170       // stack frame.
4171       SDValue MemcpyCall =
4172         CreateCopyOfByValArgument(Arg, PtrOff,
4173                                   CallSeqStart.getNode()->getOperand(0),
4174                                   Flags, DAG, dl);
4175
4176       // This must go outside the CALLSEQ_START..END.
4177       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4178                            CallSeqStart.getNode()->getOperand(1),
4179                            SDLoc(MemcpyCall));
4180       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4181                              NewCallSeqStart.getNode());
4182       Chain = CallSeqStart = NewCallSeqStart;
4183
4184       // Pass the address of the aggregate copy on the stack either in a
4185       // physical register or in the parameter list area of the current stack
4186       // frame to the callee.
4187       Arg = PtrOff;
4188     }
4189
4190     if (VA.isRegLoc()) {
4191       if (Arg.getValueType() == MVT::i1)
4192         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4193
4194       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4195       // Put argument in a physical register.
4196       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4197     } else {
4198       // Put argument in the parameter list area of the current stack frame.
4199       assert(VA.isMemLoc());
4200       unsigned LocMemOffset = VA.getLocMemOffset();
4201
4202       if (!isTailCall) {
4203         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4204         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4205
4206         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4207                                            MachinePointerInfo(),
4208                                            false, false, 0));
4209       } else {
4210         // Calculate and remember argument location.
4211         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4212                                  TailCallArguments);
4213       }
4214     }
4215   }
4216
4217   if (!MemOpChains.empty())
4218     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4219
4220   // Build a sequence of copy-to-reg nodes chained together with token chain
4221   // and flag operands which copy the outgoing args into the appropriate regs.
4222   SDValue InFlag;
4223   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4224     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4225                              RegsToPass[i].second, InFlag);
4226     InFlag = Chain.getValue(1);
4227   }
4228
4229   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4230   // registers.
4231   if (isVarArg) {
4232     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4233     SDValue Ops[] = { Chain, InFlag };
4234
4235     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4236                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4237
4238     InFlag = Chain.getValue(1);
4239   }
4240
4241   if (isTailCall)
4242     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4243                     false, TailCallArguments);
4244
4245   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4246                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4247                     NumBytes, Ins, InVals, CS);
4248 }
4249
4250 // Copy an argument into memory, being careful to do this outside the
4251 // call sequence for the call to which the argument belongs.
4252 SDValue
4253 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4254                                               SDValue CallSeqStart,
4255                                               ISD::ArgFlagsTy Flags,
4256                                               SelectionDAG &DAG,
4257                                               SDLoc dl) const {
4258   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4259                         CallSeqStart.getNode()->getOperand(0),
4260                         Flags, DAG, dl);
4261   // The MEMCPY must go outside the CALLSEQ_START..END.
4262   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4263                              CallSeqStart.getNode()->getOperand(1),
4264                              SDLoc(MemcpyCall));
4265   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4266                          NewCallSeqStart.getNode());
4267   return NewCallSeqStart;
4268 }
4269
4270 SDValue
4271 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4272                                     CallingConv::ID CallConv, bool isVarArg,
4273                                     bool isTailCall, bool IsPatchPoint,
4274                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4275                                     const SmallVectorImpl<SDValue> &OutVals,
4276                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4277                                     SDLoc dl, SelectionDAG &DAG,
4278                                     SmallVectorImpl<SDValue> &InVals,
4279                                     ImmutableCallSite *CS) const {
4280
4281   bool isELFv2ABI = Subtarget.isELFv2ABI();
4282   bool isLittleEndian = Subtarget.isLittleEndian();
4283   unsigned NumOps = Outs.size();
4284
4285   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4286   unsigned PtrByteSize = 8;
4287
4288   MachineFunction &MF = DAG.getMachineFunction();
4289
4290   // Mark this function as potentially containing a function that contains a
4291   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4292   // and restoring the callers stack pointer in this functions epilog. This is
4293   // done because by tail calling the called function might overwrite the value
4294   // in this function's (MF) stack pointer stack slot 0(SP).
4295   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4296       CallConv == CallingConv::Fast)
4297     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4298
4299   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4300          "fastcc not supported on varargs functions");
4301
4302   // Count how many bytes are to be pushed on the stack, including the linkage
4303   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4304   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4305   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4306   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4307                                                           isELFv2ABI);
4308   unsigned NumBytes = LinkageSize;
4309   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4310
4311   static const MCPhysReg GPR[] = {
4312     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4313     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4314   };
4315   static const MCPhysReg *FPR = GetFPR();
4316
4317   static const MCPhysReg VR[] = {
4318     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4319     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4320   };
4321   static const MCPhysReg VSRH[] = {
4322     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4323     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4324   };
4325
4326   const unsigned NumGPRs = array_lengthof(GPR);
4327   const unsigned NumFPRs = 13;
4328   const unsigned NumVRs  = array_lengthof(VR);
4329
4330   // When using the fast calling convention, we don't provide backing for
4331   // arguments that will be in registers.
4332   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4333
4334   // Add up all the space actually used.
4335   for (unsigned i = 0; i != NumOps; ++i) {
4336     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4337     EVT ArgVT = Outs[i].VT;
4338     EVT OrigVT = Outs[i].ArgVT;
4339
4340     if (CallConv == CallingConv::Fast) {
4341       if (Flags.isByVal())
4342         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4343       else
4344         switch (ArgVT.getSimpleVT().SimpleTy) {
4345         default: llvm_unreachable("Unexpected ValueType for argument!");
4346         case MVT::i1:
4347         case MVT::i32:
4348         case MVT::i64:
4349           if (++NumGPRsUsed <= NumGPRs)
4350             continue;
4351           break;
4352         case MVT::f32:
4353         case MVT::f64:
4354           if (++NumFPRsUsed <= NumFPRs)
4355             continue;
4356           break;
4357         case MVT::v4f32:
4358         case MVT::v4i32:
4359         case MVT::v8i16:
4360         case MVT::v16i8:
4361         case MVT::v2f64:
4362         case MVT::v2i64:
4363           if (++NumVRsUsed <= NumVRs)
4364             continue;
4365           break;
4366         }
4367     }
4368
4369     /* Respect alignment of argument on the stack.  */
4370     unsigned Align =
4371       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4372     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4373
4374     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4375     if (Flags.isInConsecutiveRegsLast())
4376       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4377   }
4378
4379   unsigned NumBytesActuallyUsed = NumBytes;
4380
4381   // The prolog code of the callee may store up to 8 GPR argument registers to
4382   // the stack, allowing va_start to index over them in memory if its varargs.
4383   // Because we cannot tell if this is needed on the caller side, we have to
4384   // conservatively assume that it is needed.  As such, make sure we have at
4385   // least enough stack space for the caller to store the 8 GPRs.
4386   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4387   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4388
4389   // Tail call needs the stack to be aligned.
4390   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4391       CallConv == CallingConv::Fast)
4392     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4393
4394   // Calculate by how many bytes the stack has to be adjusted in case of tail
4395   // call optimization.
4396   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4397
4398   // To protect arguments on the stack from being clobbered in a tail call,
4399   // force all the loads to happen before doing any other lowering.
4400   if (isTailCall)
4401     Chain = DAG.getStackArgumentTokenFactor(Chain);
4402
4403   // Adjust the stack pointer for the new arguments...
4404   // These operations are automatically eliminated by the prolog/epilog pass
4405   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4406                                dl);
4407   SDValue CallSeqStart = Chain;
4408
4409   // Load the return address and frame pointer so it can be move somewhere else
4410   // later.
4411   SDValue LROp, FPOp;
4412   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4413                                        dl);
4414
4415   // Set up a copy of the stack pointer for use loading and storing any
4416   // arguments that may not fit in the registers available for argument
4417   // passing.
4418   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4419
4420   // Figure out which arguments are going to go in registers, and which in
4421   // memory.  Also, if this is a vararg function, floating point operations
4422   // must be stored to our stack, and loaded into integer regs as well, if
4423   // any integer regs are available for argument passing.
4424   unsigned ArgOffset = LinkageSize;
4425
4426   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4427   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4428
4429   SmallVector<SDValue, 8> MemOpChains;
4430   for (unsigned i = 0; i != NumOps; ++i) {
4431     SDValue Arg = OutVals[i];
4432     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4433     EVT ArgVT = Outs[i].VT;
4434     EVT OrigVT = Outs[i].ArgVT;
4435
4436     // PtrOff will be used to store the current argument to the stack if a
4437     // register cannot be found for it.
4438     SDValue PtrOff;
4439
4440     // We re-align the argument offset for each argument, except when using the
4441     // fast calling convention, when we need to make sure we do that only when
4442     // we'll actually use a stack slot.
4443     auto ComputePtrOff = [&]() {
4444       /* Respect alignment of argument on the stack.  */
4445       unsigned Align =
4446         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4447       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4448
4449       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4450
4451       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4452     };
4453
4454     if (CallConv != CallingConv::Fast) {
4455       ComputePtrOff();
4456
4457       /* Compute GPR index associated with argument offset.  */
4458       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4459       GPR_idx = std::min(GPR_idx, NumGPRs);
4460     }
4461
4462     // Promote integers to 64-bit values.
4463     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4464       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4465       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4466       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4467     }
4468
4469     // FIXME memcpy is used way more than necessary.  Correctness first.
4470     // Note: "by value" is code for passing a structure by value, not
4471     // basic types.
4472     if (Flags.isByVal()) {
4473       // Note: Size includes alignment padding, so
4474       //   struct x { short a; char b; }
4475       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4476       // These are the proper values we need for right-justifying the
4477       // aggregate in a parameter register.
4478       unsigned Size = Flags.getByValSize();
4479
4480       // An empty aggregate parameter takes up no storage and no
4481       // registers.
4482       if (Size == 0)
4483         continue;
4484
4485       if (CallConv == CallingConv::Fast)
4486         ComputePtrOff();
4487
4488       // All aggregates smaller than 8 bytes must be passed right-justified.
4489       if (Size==1 || Size==2 || Size==4) {
4490         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4491         if (GPR_idx != NumGPRs) {
4492           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4493                                         MachinePointerInfo(), VT,
4494                                         false, false, false, 0);
4495           MemOpChains.push_back(Load.getValue(1));
4496           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4497
4498           ArgOffset += PtrByteSize;
4499           continue;
4500         }
4501       }
4502
4503       if (GPR_idx == NumGPRs && Size < 8) {
4504         SDValue AddPtr = PtrOff;
4505         if (!isLittleEndian) {
4506           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4507                                           PtrOff.getValueType());
4508           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4509         }
4510         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4511                                                           CallSeqStart,
4512                                                           Flags, DAG, dl);
4513         ArgOffset += PtrByteSize;
4514         continue;
4515       }
4516       // Copy entire object into memory.  There are cases where gcc-generated
4517       // code assumes it is there, even if it could be put entirely into
4518       // registers.  (This is not what the doc says.)
4519
4520       // FIXME: The above statement is likely due to a misunderstanding of the
4521       // documents.  All arguments must be copied into the parameter area BY
4522       // THE CALLEE in the event that the callee takes the address of any
4523       // formal argument.  That has not yet been implemented.  However, it is
4524       // reasonable to use the stack area as a staging area for the register
4525       // load.
4526
4527       // Skip this for small aggregates, as we will use the same slot for a
4528       // right-justified copy, below.
4529       if (Size >= 8)
4530         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4531                                                           CallSeqStart,
4532                                                           Flags, DAG, dl);
4533
4534       // When a register is available, pass a small aggregate right-justified.
4535       if (Size < 8 && GPR_idx != NumGPRs) {
4536         // The easiest way to get this right-justified in a register
4537         // is to copy the structure into the rightmost portion of a
4538         // local variable slot, then load the whole slot into the
4539         // register.
4540         // FIXME: The memcpy seems to produce pretty awful code for
4541         // small aggregates, particularly for packed ones.
4542         // FIXME: It would be preferable to use the slot in the
4543         // parameter save area instead of a new local variable.
4544         SDValue AddPtr = PtrOff;
4545         if (!isLittleEndian) {
4546           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4547           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4548         }
4549         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4550                                                           CallSeqStart,
4551                                                           Flags, DAG, dl);
4552
4553         // Load the slot into the register.
4554         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4555                                    MachinePointerInfo(),
4556                                    false, false, false, 0);
4557         MemOpChains.push_back(Load.getValue(1));
4558         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4559
4560         // Done with this argument.
4561         ArgOffset += PtrByteSize;
4562         continue;
4563       }
4564
4565       // For aggregates larger than PtrByteSize, copy the pieces of the
4566       // object that fit into registers from the parameter save area.
4567       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4568         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4569         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4570         if (GPR_idx != NumGPRs) {
4571           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4572                                      MachinePointerInfo(),
4573                                      false, false, false, 0);
4574           MemOpChains.push_back(Load.getValue(1));
4575           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4576           ArgOffset += PtrByteSize;
4577         } else {
4578           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4579           break;
4580         }
4581       }
4582       continue;
4583     }
4584
4585     switch (Arg.getSimpleValueType().SimpleTy) {
4586     default: llvm_unreachable("Unexpected ValueType for argument!");
4587     case MVT::i1:
4588     case MVT::i32:
4589     case MVT::i64:
4590       // These can be scalar arguments or elements of an integer array type
4591       // passed directly.  Clang may use those instead of "byval" aggregate
4592       // types to avoid forcing arguments to memory unnecessarily.
4593       if (GPR_idx != NumGPRs) {
4594         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4595       } else {
4596         if (CallConv == CallingConv::Fast)
4597           ComputePtrOff();
4598
4599         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4600                          true, isTailCall, false, MemOpChains,
4601                          TailCallArguments, dl);
4602         if (CallConv == CallingConv::Fast)
4603           ArgOffset += PtrByteSize;
4604       }
4605       if (CallConv != CallingConv::Fast)
4606         ArgOffset += PtrByteSize;
4607       break;
4608     case MVT::f32:
4609     case MVT::f64: {
4610       // These can be scalar arguments or elements of a float array type
4611       // passed directly.  The latter are used to implement ELFv2 homogenous
4612       // float aggregates.
4613
4614       // Named arguments go into FPRs first, and once they overflow, the
4615       // remaining arguments go into GPRs and then the parameter save area.
4616       // Unnamed arguments for vararg functions always go to GPRs and
4617       // then the parameter save area.  For now, put all arguments to vararg
4618       // routines always in both locations (FPR *and* GPR or stack slot).
4619       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4620       bool NeededLoad = false;
4621
4622       // First load the argument into the next available FPR.
4623       if (FPR_idx != NumFPRs)
4624         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4625
4626       // Next, load the argument into GPR or stack slot if needed.
4627       if (!NeedGPROrStack)
4628         ;
4629       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4630         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4631         // once we support fp <-> gpr moves.
4632
4633         // In the non-vararg case, this can only ever happen in the
4634         // presence of f32 array types, since otherwise we never run
4635         // out of FPRs before running out of GPRs.
4636         SDValue ArgVal;
4637
4638         // Double values are always passed in a single GPR.
4639         if (Arg.getValueType() != MVT::f32) {
4640           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4641
4642         // Non-array float values are extended and passed in a GPR.
4643         } else if (!Flags.isInConsecutiveRegs()) {
4644           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4645           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4646
4647         // If we have an array of floats, we collect every odd element
4648         // together with its predecessor into one GPR.
4649         } else if (ArgOffset % PtrByteSize != 0) {
4650           SDValue Lo, Hi;
4651           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4652           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4653           if (!isLittleEndian)
4654             std::swap(Lo, Hi);
4655           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4656
4657         // The final element, if even, goes into the first half of a GPR.
4658         } else if (Flags.isInConsecutiveRegsLast()) {
4659           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4660           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4661           if (!isLittleEndian)
4662             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4663                                  DAG.getConstant(32, MVT::i32));
4664
4665         // Non-final even elements are skipped; they will be handled
4666         // together the with subsequent argument on the next go-around.
4667         } else
4668           ArgVal = SDValue();
4669
4670         if (ArgVal.getNode())
4671           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4672       } else {
4673         if (CallConv == CallingConv::Fast)
4674           ComputePtrOff();
4675
4676         // Single-precision floating-point values are mapped to the
4677         // second (rightmost) word of the stack doubleword.
4678         if (Arg.getValueType() == MVT::f32 &&
4679             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4680           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4681           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4682         }
4683
4684         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4685                          true, isTailCall, false, MemOpChains,
4686                          TailCallArguments, dl);
4687
4688         NeededLoad = true;
4689       }
4690       // When passing an array of floats, the array occupies consecutive
4691       // space in the argument area; only round up to the next doubleword
4692       // at the end of the array.  Otherwise, each float takes 8 bytes.
4693       if (CallConv != CallingConv::Fast || NeededLoad) {
4694         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4695                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4696         if (Flags.isInConsecutiveRegsLast())
4697           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4698       }
4699       break;
4700     }
4701     case MVT::v4f32:
4702     case MVT::v4i32:
4703     case MVT::v8i16:
4704     case MVT::v16i8:
4705     case MVT::v2f64:
4706     case MVT::v2i64:
4707       // These can be scalar arguments or elements of a vector array type
4708       // passed directly.  The latter are used to implement ELFv2 homogenous
4709       // vector aggregates.
4710
4711       // For a varargs call, named arguments go into VRs or on the stack as
4712       // usual; unnamed arguments always go to the stack or the corresponding
4713       // GPRs when within range.  For now, we always put the value in both
4714       // locations (or even all three).
4715       if (isVarArg) {
4716         // We could elide this store in the case where the object fits
4717         // entirely in R registers.  Maybe later.
4718         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4719                                      MachinePointerInfo(), false, false, 0);
4720         MemOpChains.push_back(Store);
4721         if (VR_idx != NumVRs) {
4722           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4723                                      MachinePointerInfo(),
4724                                      false, false, false, 0);
4725           MemOpChains.push_back(Load.getValue(1));
4726
4727           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4728                            Arg.getSimpleValueType() == MVT::v2i64) ?
4729                           VSRH[VR_idx] : VR[VR_idx];
4730           ++VR_idx;
4731
4732           RegsToPass.push_back(std::make_pair(VReg, Load));
4733         }
4734         ArgOffset += 16;
4735         for (unsigned i=0; i<16; i+=PtrByteSize) {
4736           if (GPR_idx == NumGPRs)
4737             break;
4738           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4739                                   DAG.getConstant(i, PtrVT));
4740           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4741                                      false, false, false, 0);
4742           MemOpChains.push_back(Load.getValue(1));
4743           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4744         }
4745         break;
4746       }
4747
4748       // Non-varargs Altivec params go into VRs or on the stack.
4749       if (VR_idx != NumVRs) {
4750         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4751                          Arg.getSimpleValueType() == MVT::v2i64) ?
4752                         VSRH[VR_idx] : VR[VR_idx];
4753         ++VR_idx;
4754
4755         RegsToPass.push_back(std::make_pair(VReg, Arg));
4756       } else {
4757         if (CallConv == CallingConv::Fast)
4758           ComputePtrOff();
4759
4760         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4761                          true, isTailCall, true, MemOpChains,
4762                          TailCallArguments, dl);
4763         if (CallConv == CallingConv::Fast)
4764           ArgOffset += 16;
4765       }
4766
4767       if (CallConv != CallingConv::Fast)
4768         ArgOffset += 16;
4769       break;
4770     }
4771   }
4772
4773   assert(NumBytesActuallyUsed == ArgOffset);
4774   (void)NumBytesActuallyUsed;
4775
4776   if (!MemOpChains.empty())
4777     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4778
4779   // Check if this is an indirect call (MTCTR/BCTRL).
4780   // See PrepareCall() for more information about calls through function
4781   // pointers in the 64-bit SVR4 ABI.
4782   if (!isTailCall && !IsPatchPoint &&
4783       !isFunctionGlobalAddress(Callee) &&
4784       !isa<ExternalSymbolSDNode>(Callee)) {
4785     // Load r2 into a virtual register and store it to the TOC save area.
4786     setUsesTOCBasePtr(DAG);
4787     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4788     // TOC save area offset.
4789     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4790     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4791     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4792     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
4793                          MachinePointerInfo::getStack(TOCSaveOffset),
4794                          false, false, 0);
4795     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4796     // This does not mean the MTCTR instruction must use R12; it's easier
4797     // to model this as an extra parameter, so do that.
4798     if (isELFv2ABI && !IsPatchPoint)
4799       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4800   }
4801
4802   // Build a sequence of copy-to-reg nodes chained together with token chain
4803   // and flag operands which copy the outgoing args into the appropriate regs.
4804   SDValue InFlag;
4805   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4806     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4807                              RegsToPass[i].second, InFlag);
4808     InFlag = Chain.getValue(1);
4809   }
4810
4811   if (isTailCall)
4812     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4813                     FPOp, true, TailCallArguments);
4814
4815   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4816                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4817                     NumBytes, Ins, InVals, CS);
4818 }
4819
4820 SDValue
4821 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4822                                     CallingConv::ID CallConv, bool isVarArg,
4823                                     bool isTailCall, bool IsPatchPoint,
4824                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4825                                     const SmallVectorImpl<SDValue> &OutVals,
4826                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4827                                     SDLoc dl, SelectionDAG &DAG,
4828                                     SmallVectorImpl<SDValue> &InVals,
4829                                     ImmutableCallSite *CS) const {
4830
4831   unsigned NumOps = Outs.size();
4832
4833   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4834   bool isPPC64 = PtrVT == MVT::i64;
4835   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4836
4837   MachineFunction &MF = DAG.getMachineFunction();
4838
4839   // Mark this function as potentially containing a function that contains a
4840   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4841   // and restoring the callers stack pointer in this functions epilog. This is
4842   // done because by tail calling the called function might overwrite the value
4843   // in this function's (MF) stack pointer stack slot 0(SP).
4844   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4845       CallConv == CallingConv::Fast)
4846     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4847
4848   // Count how many bytes are to be pushed on the stack, including the linkage
4849   // area, and parameter passing area.  We start with 24/48 bytes, which is
4850   // prereserved space for [SP][CR][LR][3 x unused].
4851   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4852                                                           false);
4853   unsigned NumBytes = LinkageSize;
4854
4855   // Add up all the space actually used.
4856   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4857   // they all go in registers, but we must reserve stack space for them for
4858   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4859   // assigned stack space in order, with padding so Altivec parameters are
4860   // 16-byte aligned.
4861   unsigned nAltivecParamsAtEnd = 0;
4862   for (unsigned i = 0; i != NumOps; ++i) {
4863     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4864     EVT ArgVT = Outs[i].VT;
4865     // Varargs Altivec parameters are padded to a 16 byte boundary.
4866     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4867         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4868         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4869       if (!isVarArg && !isPPC64) {
4870         // Non-varargs Altivec parameters go after all the non-Altivec
4871         // parameters; handle those later so we know how much padding we need.
4872         nAltivecParamsAtEnd++;
4873         continue;
4874       }
4875       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4876       NumBytes = ((NumBytes+15)/16)*16;
4877     }
4878     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4879   }
4880
4881   // Allow for Altivec parameters at the end, if needed.
4882   if (nAltivecParamsAtEnd) {
4883     NumBytes = ((NumBytes+15)/16)*16;
4884     NumBytes += 16*nAltivecParamsAtEnd;
4885   }
4886
4887   // The prolog code of the callee may store up to 8 GPR argument registers to
4888   // the stack, allowing va_start to index over them in memory if its varargs.
4889   // Because we cannot tell if this is needed on the caller side, we have to
4890   // conservatively assume that it is needed.  As such, make sure we have at
4891   // least enough stack space for the caller to store the 8 GPRs.
4892   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4893
4894   // Tail call needs the stack to be aligned.
4895   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4896       CallConv == CallingConv::Fast)
4897     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4898
4899   // Calculate by how many bytes the stack has to be adjusted in case of tail
4900   // call optimization.
4901   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4902
4903   // To protect arguments on the stack from being clobbered in a tail call,
4904   // force all the loads to happen before doing any other lowering.
4905   if (isTailCall)
4906     Chain = DAG.getStackArgumentTokenFactor(Chain);
4907
4908   // Adjust the stack pointer for the new arguments...
4909   // These operations are automatically eliminated by the prolog/epilog pass
4910   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4911                                dl);
4912   SDValue CallSeqStart = Chain;
4913
4914   // Load the return address and frame pointer so it can be move somewhere else
4915   // later.
4916   SDValue LROp, FPOp;
4917   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4918                                        dl);
4919
4920   // Set up a copy of the stack pointer for use loading and storing any
4921   // arguments that may not fit in the registers available for argument
4922   // passing.
4923   SDValue StackPtr;
4924   if (isPPC64)
4925     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4926   else
4927     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4928
4929   // Figure out which arguments are going to go in registers, and which in
4930   // memory.  Also, if this is a vararg function, floating point operations
4931   // must be stored to our stack, and loaded into integer regs as well, if
4932   // any integer regs are available for argument passing.
4933   unsigned ArgOffset = LinkageSize;
4934   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4935
4936   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4937     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4938     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4939   };
4940   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4941     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4942     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4943   };
4944   static const MCPhysReg *FPR = GetFPR();
4945
4946   static const MCPhysReg VR[] = {
4947     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4948     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4949   };
4950   const unsigned NumGPRs = array_lengthof(GPR_32);
4951   const unsigned NumFPRs = 13;
4952   const unsigned NumVRs  = array_lengthof(VR);
4953
4954   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4955
4956   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4957   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4958
4959   SmallVector<SDValue, 8> MemOpChains;
4960   for (unsigned i = 0; i != NumOps; ++i) {
4961     SDValue Arg = OutVals[i];
4962     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4963
4964     // PtrOff will be used to store the current argument to the stack if a
4965     // register cannot be found for it.
4966     SDValue PtrOff;
4967
4968     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4969
4970     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4971
4972     // On PPC64, promote integers to 64-bit values.
4973     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4974       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4975       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4976       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4977     }
4978
4979     // FIXME memcpy is used way more than necessary.  Correctness first.
4980     // Note: "by value" is code for passing a structure by value, not
4981     // basic types.
4982     if (Flags.isByVal()) {
4983       unsigned Size = Flags.getByValSize();
4984       // Very small objects are passed right-justified.  Everything else is
4985       // passed left-justified.
4986       if (Size==1 || Size==2) {
4987         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4988         if (GPR_idx != NumGPRs) {
4989           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4990                                         MachinePointerInfo(), VT,
4991                                         false, false, false, 0);
4992           MemOpChains.push_back(Load.getValue(1));
4993           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4994
4995           ArgOffset += PtrByteSize;
4996         } else {
4997           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4998                                           PtrOff.getValueType());
4999           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5000           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5001                                                             CallSeqStart,
5002                                                             Flags, DAG, dl);
5003           ArgOffset += PtrByteSize;
5004         }
5005         continue;
5006       }
5007       // Copy entire object into memory.  There are cases where gcc-generated
5008       // code assumes it is there, even if it could be put entirely into
5009       // registers.  (This is not what the doc says.)
5010       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5011                                                         CallSeqStart,
5012                                                         Flags, DAG, dl);
5013
5014       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5015       // copy the pieces of the object that fit into registers from the
5016       // parameter save area.
5017       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5018         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5019         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5020         if (GPR_idx != NumGPRs) {
5021           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5022                                      MachinePointerInfo(),
5023                                      false, false, false, 0);
5024           MemOpChains.push_back(Load.getValue(1));
5025           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5026           ArgOffset += PtrByteSize;
5027         } else {
5028           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5029           break;
5030         }
5031       }
5032       continue;
5033     }
5034
5035     switch (Arg.getSimpleValueType().SimpleTy) {
5036     default: llvm_unreachable("Unexpected ValueType for argument!");
5037     case MVT::i1:
5038     case MVT::i32:
5039     case MVT::i64:
5040       if (GPR_idx != NumGPRs) {
5041         if (Arg.getValueType() == MVT::i1)
5042           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5043
5044         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5045       } else {
5046         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5047                          isPPC64, isTailCall, false, MemOpChains,
5048                          TailCallArguments, dl);
5049       }
5050       ArgOffset += PtrByteSize;
5051       break;
5052     case MVT::f32:
5053     case MVT::f64:
5054       if (FPR_idx != NumFPRs) {
5055         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5056
5057         if (isVarArg) {
5058           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5059                                        MachinePointerInfo(), false, false, 0);
5060           MemOpChains.push_back(Store);
5061
5062           // Float varargs are always shadowed in available integer registers
5063           if (GPR_idx != NumGPRs) {
5064             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5065                                        MachinePointerInfo(), false, false,
5066                                        false, 0);
5067             MemOpChains.push_back(Load.getValue(1));
5068             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5069           }
5070           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5071             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5072             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5073             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5074                                        MachinePointerInfo(),
5075                                        false, false, false, 0);
5076             MemOpChains.push_back(Load.getValue(1));
5077             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5078           }
5079         } else {
5080           // If we have any FPRs remaining, we may also have GPRs remaining.
5081           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5082           // GPRs.
5083           if (GPR_idx != NumGPRs)
5084             ++GPR_idx;
5085           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5086               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5087             ++GPR_idx;
5088         }
5089       } else
5090         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5091                          isPPC64, isTailCall, false, MemOpChains,
5092                          TailCallArguments, dl);
5093       if (isPPC64)
5094         ArgOffset += 8;
5095       else
5096         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5097       break;
5098     case MVT::v4f32:
5099     case MVT::v4i32:
5100     case MVT::v8i16:
5101     case MVT::v16i8:
5102       if (isVarArg) {
5103         // These go aligned on the stack, or in the corresponding R registers
5104         // when within range.  The Darwin PPC ABI doc claims they also go in
5105         // V registers; in fact gcc does this only for arguments that are
5106         // prototyped, not for those that match the ...  We do it for all
5107         // arguments, seems to work.
5108         while (ArgOffset % 16 !=0) {
5109           ArgOffset += PtrByteSize;
5110           if (GPR_idx != NumGPRs)
5111             GPR_idx++;
5112         }
5113         // We could elide this store in the case where the object fits
5114         // entirely in R registers.  Maybe later.
5115         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5116                             DAG.getConstant(ArgOffset, PtrVT));
5117         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5118                                      MachinePointerInfo(), false, false, 0);
5119         MemOpChains.push_back(Store);
5120         if (VR_idx != NumVRs) {
5121           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5122                                      MachinePointerInfo(),
5123                                      false, false, false, 0);
5124           MemOpChains.push_back(Load.getValue(1));
5125           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5126         }
5127         ArgOffset += 16;
5128         for (unsigned i=0; i<16; i+=PtrByteSize) {
5129           if (GPR_idx == NumGPRs)
5130             break;
5131           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5132                                   DAG.getConstant(i, PtrVT));
5133           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5134                                      false, false, false, 0);
5135           MemOpChains.push_back(Load.getValue(1));
5136           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5137         }
5138         break;
5139       }
5140
5141       // Non-varargs Altivec params generally go in registers, but have
5142       // stack space allocated at the end.
5143       if (VR_idx != NumVRs) {
5144         // Doesn't have GPR space allocated.
5145         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5146       } else if (nAltivecParamsAtEnd==0) {
5147         // We are emitting Altivec params in order.
5148         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5149                          isPPC64, isTailCall, true, MemOpChains,
5150                          TailCallArguments, dl);
5151         ArgOffset += 16;
5152       }
5153       break;
5154     }
5155   }
5156   // If all Altivec parameters fit in registers, as they usually do,
5157   // they get stack space following the non-Altivec parameters.  We
5158   // don't track this here because nobody below needs it.
5159   // If there are more Altivec parameters than fit in registers emit
5160   // the stores here.
5161   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5162     unsigned j = 0;
5163     // Offset is aligned; skip 1st 12 params which go in V registers.
5164     ArgOffset = ((ArgOffset+15)/16)*16;
5165     ArgOffset += 12*16;
5166     for (unsigned i = 0; i != NumOps; ++i) {
5167       SDValue Arg = OutVals[i];
5168       EVT ArgType = Outs[i].VT;
5169       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5170           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5171         if (++j > NumVRs) {
5172           SDValue PtrOff;
5173           // We are emitting Altivec params in order.
5174           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5175                            isPPC64, isTailCall, true, MemOpChains,
5176                            TailCallArguments, dl);
5177           ArgOffset += 16;
5178         }
5179       }
5180     }
5181   }
5182
5183   if (!MemOpChains.empty())
5184     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5185
5186   // On Darwin, R12 must contain the address of an indirect callee.  This does
5187   // not mean the MTCTR instruction must use R12; it's easier to model this as
5188   // an extra parameter, so do that.
5189   if (!isTailCall &&
5190       !isFunctionGlobalAddress(Callee) &&
5191       !isa<ExternalSymbolSDNode>(Callee) &&
5192       !isBLACompatibleAddress(Callee, DAG))
5193     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5194                                                    PPC::R12), Callee));
5195
5196   // Build a sequence of copy-to-reg nodes chained together with token chain
5197   // and flag operands which copy the outgoing args into the appropriate regs.
5198   SDValue InFlag;
5199   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5200     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5201                              RegsToPass[i].second, InFlag);
5202     InFlag = Chain.getValue(1);
5203   }
5204
5205   if (isTailCall)
5206     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5207                     FPOp, true, TailCallArguments);
5208
5209   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5210                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5211                     NumBytes, Ins, InVals, CS);
5212 }
5213
5214 bool
5215 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5216                                   MachineFunction &MF, bool isVarArg,
5217                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5218                                   LLVMContext &Context) const {
5219   SmallVector<CCValAssign, 16> RVLocs;
5220   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5221   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5222 }
5223
5224 SDValue
5225 PPCTargetLowering::LowerReturn(SDValue Chain,
5226                                CallingConv::ID CallConv, bool isVarArg,
5227                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5228                                const SmallVectorImpl<SDValue> &OutVals,
5229                                SDLoc dl, SelectionDAG &DAG) const {
5230
5231   SmallVector<CCValAssign, 16> RVLocs;
5232   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5233                  *DAG.getContext());
5234   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5235
5236   SDValue Flag;
5237   SmallVector<SDValue, 4> RetOps(1, Chain);
5238
5239   // Copy the result values into the output registers.
5240   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5241     CCValAssign &VA = RVLocs[i];
5242     assert(VA.isRegLoc() && "Can only return in registers!");
5243
5244     SDValue Arg = OutVals[i];
5245
5246     switch (VA.getLocInfo()) {
5247     default: llvm_unreachable("Unknown loc info!");
5248     case CCValAssign::Full: break;
5249     case CCValAssign::AExt:
5250       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5251       break;
5252     case CCValAssign::ZExt:
5253       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5254       break;
5255     case CCValAssign::SExt:
5256       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5257       break;
5258     }
5259
5260     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5261     Flag = Chain.getValue(1);
5262     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5263   }
5264
5265   RetOps[0] = Chain;  // Update chain.
5266
5267   // Add the flag if we have it.
5268   if (Flag.getNode())
5269     RetOps.push_back(Flag);
5270
5271   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5272 }
5273
5274 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5275                                    const PPCSubtarget &Subtarget) const {
5276   // When we pop the dynamic allocation we need to restore the SP link.
5277   SDLoc dl(Op);
5278
5279   // Get the corect type for pointers.
5280   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5281
5282   // Construct the stack pointer operand.
5283   bool isPPC64 = Subtarget.isPPC64();
5284   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5285   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5286
5287   // Get the operands for the STACKRESTORE.
5288   SDValue Chain = Op.getOperand(0);
5289   SDValue SaveSP = Op.getOperand(1);
5290
5291   // Load the old link SP.
5292   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5293                                    MachinePointerInfo(),
5294                                    false, false, false, 0);
5295
5296   // Restore the stack pointer.
5297   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5298
5299   // Store the old link SP.
5300   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5301                       false, false, 0);
5302 }
5303
5304
5305
5306 SDValue
5307 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5308   MachineFunction &MF = DAG.getMachineFunction();
5309   bool isPPC64 = Subtarget.isPPC64();
5310   bool isDarwinABI = Subtarget.isDarwinABI();
5311   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5312
5313   // Get current frame pointer save index.  The users of this index will be
5314   // primarily DYNALLOC instructions.
5315   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5316   int RASI = FI->getReturnAddrSaveIndex();
5317
5318   // If the frame pointer save index hasn't been defined yet.
5319   if (!RASI) {
5320     // Find out what the fix offset of the frame pointer save area.
5321     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5322     // Allocate the frame index for frame pointer save area.
5323     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5324     // Save the result.
5325     FI->setReturnAddrSaveIndex(RASI);
5326   }
5327   return DAG.getFrameIndex(RASI, PtrVT);
5328 }
5329
5330 SDValue
5331 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5332   MachineFunction &MF = DAG.getMachineFunction();
5333   bool isPPC64 = Subtarget.isPPC64();
5334   bool isDarwinABI = Subtarget.isDarwinABI();
5335   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5336
5337   // Get current frame pointer save index.  The users of this index will be
5338   // primarily DYNALLOC instructions.
5339   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5340   int FPSI = FI->getFramePointerSaveIndex();
5341
5342   // If the frame pointer save index hasn't been defined yet.
5343   if (!FPSI) {
5344     // Find out what the fix offset of the frame pointer save area.
5345     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5346                                                            isDarwinABI);
5347
5348     // Allocate the frame index for frame pointer save area.
5349     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5350     // Save the result.
5351     FI->setFramePointerSaveIndex(FPSI);
5352   }
5353   return DAG.getFrameIndex(FPSI, PtrVT);
5354 }
5355
5356 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5357                                          SelectionDAG &DAG,
5358                                          const PPCSubtarget &Subtarget) const {
5359   // Get the inputs.
5360   SDValue Chain = Op.getOperand(0);
5361   SDValue Size  = Op.getOperand(1);
5362   SDLoc dl(Op);
5363
5364   // Get the corect type for pointers.
5365   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5366   // Negate the size.
5367   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5368                                   DAG.getConstant(0, PtrVT), Size);
5369   // Construct a node for the frame pointer save index.
5370   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5371   // Build a DYNALLOC node.
5372   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5373   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5374   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5375 }
5376
5377 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5378                                                SelectionDAG &DAG) const {
5379   SDLoc DL(Op);
5380   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5381                      DAG.getVTList(MVT::i32, MVT::Other),
5382                      Op.getOperand(0), Op.getOperand(1));
5383 }
5384
5385 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5386                                                 SelectionDAG &DAG) const {
5387   SDLoc DL(Op);
5388   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5389                      Op.getOperand(0), Op.getOperand(1));
5390 }
5391
5392 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5393   assert(Op.getValueType() == MVT::i1 &&
5394          "Custom lowering only for i1 loads");
5395
5396   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5397
5398   SDLoc dl(Op);
5399   LoadSDNode *LD = cast<LoadSDNode>(Op);
5400
5401   SDValue Chain = LD->getChain();
5402   SDValue BasePtr = LD->getBasePtr();
5403   MachineMemOperand *MMO = LD->getMemOperand();
5404
5405   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5406                                  BasePtr, MVT::i8, MMO);
5407   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5408
5409   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5410   return DAG.getMergeValues(Ops, dl);
5411 }
5412
5413 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5414   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5415          "Custom lowering only for i1 stores");
5416
5417   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5418
5419   SDLoc dl(Op);
5420   StoreSDNode *ST = cast<StoreSDNode>(Op);
5421
5422   SDValue Chain = ST->getChain();
5423   SDValue BasePtr = ST->getBasePtr();
5424   SDValue Value = ST->getValue();
5425   MachineMemOperand *MMO = ST->getMemOperand();
5426
5427   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5428   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5429 }
5430
5431 // FIXME: Remove this once the ANDI glue bug is fixed:
5432 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5433   assert(Op.getValueType() == MVT::i1 &&
5434          "Custom lowering only for i1 results");
5435
5436   SDLoc DL(Op);
5437   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5438                      Op.getOperand(0));
5439 }
5440
5441 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5442 /// possible.
5443 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5444   // Not FP? Not a fsel.
5445   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5446       !Op.getOperand(2).getValueType().isFloatingPoint())
5447     return Op;
5448
5449   // We might be able to do better than this under some circumstances, but in
5450   // general, fsel-based lowering of select is a finite-math-only optimization.
5451   // For more information, see section F.3 of the 2.06 ISA specification.
5452   if (!DAG.getTarget().Options.NoInfsFPMath ||
5453       !DAG.getTarget().Options.NoNaNsFPMath)
5454     return Op;
5455
5456   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5457
5458   EVT ResVT = Op.getValueType();
5459   EVT CmpVT = Op.getOperand(0).getValueType();
5460   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5461   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5462   SDLoc dl(Op);
5463
5464   // If the RHS of the comparison is a 0.0, we don't need to do the
5465   // subtraction at all.
5466   SDValue Sel1;
5467   if (isFloatingPointZero(RHS))
5468     switch (CC) {
5469     default: break;       // SETUO etc aren't handled by fsel.
5470     case ISD::SETNE:
5471       std::swap(TV, FV);
5472     case ISD::SETEQ:
5473       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5474         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5475       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5476       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5477         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5478       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5479                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5480     case ISD::SETULT:
5481     case ISD::SETLT:
5482       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5483     case ISD::SETOGE:
5484     case ISD::SETGE:
5485       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5486         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5487       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5488     case ISD::SETUGT:
5489     case ISD::SETGT:
5490       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5491     case ISD::SETOLE:
5492     case ISD::SETLE:
5493       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5494         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5495       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5496                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5497     }
5498
5499   SDValue Cmp;
5500   switch (CC) {
5501   default: break;       // SETUO etc aren't handled by fsel.
5502   case ISD::SETNE:
5503     std::swap(TV, FV);
5504   case ISD::SETEQ:
5505     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5506     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5507       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5508     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5509     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5510       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5511     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5512                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5513   case ISD::SETULT:
5514   case ISD::SETLT:
5515     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5516     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5517       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5518     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5519   case ISD::SETOGE:
5520   case ISD::SETGE:
5521     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5522     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5523       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5524     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5525   case ISD::SETUGT:
5526   case ISD::SETGT:
5527     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5528     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5529       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5530     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5531   case ISD::SETOLE:
5532   case ISD::SETLE:
5533     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5534     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5535       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5536     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5537   }
5538   return Op;
5539 }
5540
5541 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5542                                                SelectionDAG &DAG,
5543                                                SDLoc dl) const {
5544   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5545   SDValue Src = Op.getOperand(0);
5546   if (Src.getValueType() == MVT::f32)
5547     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5548
5549   SDValue Tmp;
5550   switch (Op.getSimpleValueType().SimpleTy) {
5551   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5552   case MVT::i32:
5553     Tmp = DAG.getNode(
5554         Op.getOpcode() == ISD::FP_TO_SINT
5555             ? PPCISD::FCTIWZ
5556             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5557         dl, MVT::f64, Src);
5558     break;
5559   case MVT::i64:
5560     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5561            "i64 FP_TO_UINT is supported only with FPCVT");
5562     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5563                                                         PPCISD::FCTIDUZ,
5564                       dl, MVT::f64, Src);
5565     break;
5566   }
5567
5568   // Convert the FP value to an int value through memory.
5569   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5570     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5571   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5572   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5573   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5574
5575   // Emit a store to the stack slot.
5576   SDValue Chain;
5577   if (i32Stack) {
5578     MachineFunction &MF = DAG.getMachineFunction();
5579     MachineMemOperand *MMO =
5580       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5581     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5582     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5583               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5584   } else
5585     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5586                          MPI, false, false, 0);
5587
5588   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5589   // add in a bias.
5590   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5591     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5592                         DAG.getConstant(4, FIPtr.getValueType()));
5593     MPI = MPI.getWithOffset(4);
5594   }
5595
5596   RLI.Chain = Chain;
5597   RLI.Ptr = FIPtr;
5598   RLI.MPI = MPI;
5599 }
5600
5601 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5602                                           SDLoc dl) const {
5603   ReuseLoadInfo RLI;
5604   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5605
5606   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5607                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5608                      RLI.Ranges);
5609 }
5610
5611 // We're trying to insert a regular store, S, and then a load, L. If the
5612 // incoming value, O, is a load, we might just be able to have our load use the
5613 // address used by O. However, we don't know if anything else will store to
5614 // that address before we can load from it. To prevent this situation, we need
5615 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5616 // the same chain operand as O, we create a token factor from the chain results
5617 // of O and L, and we replace all uses of O's chain result with that token
5618 // factor (see spliceIntoChain below for this last part).
5619 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5620                                             ReuseLoadInfo &RLI,
5621                                             SelectionDAG &DAG,
5622                                             ISD::LoadExtType ET) const {
5623   SDLoc dl(Op);
5624   if (ET == ISD::NON_EXTLOAD &&
5625       (Op.getOpcode() == ISD::FP_TO_UINT ||
5626        Op.getOpcode() == ISD::FP_TO_SINT) &&
5627       isOperationLegalOrCustom(Op.getOpcode(),
5628                                Op.getOperand(0).getValueType())) {
5629
5630     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5631     return true;
5632   }
5633
5634   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5635   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5636       LD->isNonTemporal())
5637     return false;
5638   if (LD->getMemoryVT() != MemVT)
5639     return false;
5640
5641   RLI.Ptr = LD->getBasePtr();
5642   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5643     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5644            "Non-pre-inc AM on PPC?");
5645     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5646                           LD->getOffset());
5647   }
5648
5649   RLI.Chain = LD->getChain();
5650   RLI.MPI = LD->getPointerInfo();
5651   RLI.IsInvariant = LD->isInvariant();
5652   RLI.Alignment = LD->getAlignment();
5653   RLI.AAInfo = LD->getAAInfo();
5654   RLI.Ranges = LD->getRanges();
5655
5656   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5657   return true;
5658 }
5659
5660 // Given the head of the old chain, ResChain, insert a token factor containing
5661 // it and NewResChain, and make users of ResChain now be users of that token
5662 // factor.
5663 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5664                                         SDValue NewResChain,
5665                                         SelectionDAG &DAG) const {
5666   if (!ResChain)
5667     return;
5668
5669   SDLoc dl(NewResChain);
5670
5671   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5672                            NewResChain, DAG.getUNDEF(MVT::Other));
5673   assert(TF.getNode() != NewResChain.getNode() &&
5674          "A new TF really is required here");
5675
5676   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5677   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5678 }
5679
5680 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5681                                           SelectionDAG &DAG) const {
5682   SDLoc dl(Op);
5683   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5684   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5685     return SDValue();
5686
5687   if (Op.getOperand(0).getValueType() == MVT::i1)
5688     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5689                        DAG.getConstantFP(1.0, Op.getValueType()),
5690                        DAG.getConstantFP(0.0, Op.getValueType()));
5691
5692   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5693          "UINT_TO_FP is supported only with FPCVT");
5694
5695   // If we have FCFIDS, then use it when converting to single-precision.
5696   // Otherwise, convert to double-precision and then round.
5697   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5698                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
5699                                                             : PPCISD::FCFIDS)
5700                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
5701                                                             : PPCISD::FCFID);
5702   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
5703                   ? MVT::f32
5704                   : MVT::f64;
5705
5706   if (Op.getOperand(0).getValueType() == MVT::i64) {
5707     SDValue SINT = Op.getOperand(0);
5708     // When converting to single-precision, we actually need to convert
5709     // to double-precision first and then round to single-precision.
5710     // To avoid double-rounding effects during that operation, we have
5711     // to prepare the input operand.  Bits that might be truncated when
5712     // converting to double-precision are replaced by a bit that won't
5713     // be lost at this stage, but is below the single-precision rounding
5714     // position.
5715     //
5716     // However, if -enable-unsafe-fp-math is in effect, accept double
5717     // rounding to avoid the extra overhead.
5718     if (Op.getValueType() == MVT::f32 &&
5719         !Subtarget.hasFPCVT() &&
5720         !DAG.getTarget().Options.UnsafeFPMath) {
5721
5722       // Twiddle input to make sure the low 11 bits are zero.  (If this
5723       // is the case, we are guaranteed the value will fit into the 53 bit
5724       // mantissa of an IEEE double-precision value without rounding.)
5725       // If any of those low 11 bits were not zero originally, make sure
5726       // bit 12 (value 2048) is set instead, so that the final rounding
5727       // to single-precision gets the correct result.
5728       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5729                                   SINT, DAG.getConstant(2047, MVT::i64));
5730       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5731                           Round, DAG.getConstant(2047, MVT::i64));
5732       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5733       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5734                           Round, DAG.getConstant(-2048, MVT::i64));
5735
5736       // However, we cannot use that value unconditionally: if the magnitude
5737       // of the input value is small, the bit-twiddling we did above might
5738       // end up visibly changing the output.  Fortunately, in that case, we
5739       // don't need to twiddle bits since the original input will convert
5740       // exactly to double-precision floating-point already.  Therefore,
5741       // construct a conditional to use the original value if the top 11
5742       // bits are all sign-bit copies, and use the rounded value computed
5743       // above otherwise.
5744       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5745                                  SINT, DAG.getConstant(53, MVT::i32));
5746       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5747                          Cond, DAG.getConstant(1, MVT::i64));
5748       Cond = DAG.getSetCC(dl, MVT::i32,
5749                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5750
5751       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5752     }
5753
5754     ReuseLoadInfo RLI;
5755     SDValue Bits;
5756
5757     MachineFunction &MF = DAG.getMachineFunction();
5758     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5759       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5760                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5761                          RLI.Ranges);
5762       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5763     } else if (Subtarget.hasLFIWAX() &&
5764                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5765       MachineMemOperand *MMO =
5766         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5767                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5768       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5769       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5770                                      DAG.getVTList(MVT::f64, MVT::Other),
5771                                      Ops, MVT::i32, MMO);
5772       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5773     } else if (Subtarget.hasFPCVT() &&
5774                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5775       MachineMemOperand *MMO =
5776         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5777                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5778       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5779       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5780                                      DAG.getVTList(MVT::f64, MVT::Other),
5781                                      Ops, MVT::i32, MMO);
5782       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5783     } else if (((Subtarget.hasLFIWAX() &&
5784                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5785                 (Subtarget.hasFPCVT() &&
5786                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5787                SINT.getOperand(0).getValueType() == MVT::i32) {
5788       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5789       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5790
5791       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5792       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5793
5794       SDValue Store =
5795         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5796                      MachinePointerInfo::getFixedStack(FrameIdx),
5797                      false, false, 0);
5798
5799       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5800              "Expected an i32 store");
5801
5802       RLI.Ptr = FIdx;
5803       RLI.Chain = Store;
5804       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5805       RLI.Alignment = 4;
5806
5807       MachineMemOperand *MMO =
5808         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5809                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5810       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5811       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5812                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
5813                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
5814                                      Ops, MVT::i32, MMO);
5815     } else
5816       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5817
5818     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5819
5820     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5821       FP = DAG.getNode(ISD::FP_ROUND, dl,
5822                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5823     return FP;
5824   }
5825
5826   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5827          "Unhandled INT_TO_FP type in custom expander!");
5828   // Since we only generate this in 64-bit mode, we can take advantage of
5829   // 64-bit registers.  In particular, sign extend the input value into the
5830   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5831   // then lfd it and fcfid it.
5832   MachineFunction &MF = DAG.getMachineFunction();
5833   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5834   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5835
5836   SDValue Ld;
5837   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5838     ReuseLoadInfo RLI;
5839     bool ReusingLoad;
5840     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5841                                             DAG))) {
5842       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5843       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5844
5845       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5846                                    MachinePointerInfo::getFixedStack(FrameIdx),
5847                                    false, false, 0);
5848
5849       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5850              "Expected an i32 store");
5851
5852       RLI.Ptr = FIdx;
5853       RLI.Chain = Store;
5854       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5855       RLI.Alignment = 4;
5856     }
5857
5858     MachineMemOperand *MMO =
5859       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5860                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5861     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5862     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5863                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5864                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5865                                  Ops, MVT::i32, MMO);
5866     if (ReusingLoad)
5867       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5868   } else {
5869     assert(Subtarget.isPPC64() &&
5870            "i32->FP without LFIWAX supported only on PPC64");
5871
5872     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5873     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5874
5875     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5876                                 Op.getOperand(0));
5877
5878     // STD the extended value into the stack slot.
5879     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5880                                  MachinePointerInfo::getFixedStack(FrameIdx),
5881                                  false, false, 0);
5882
5883     // Load the value as a double.
5884     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5885                      MachinePointerInfo::getFixedStack(FrameIdx),
5886                      false, false, false, 0);
5887   }
5888
5889   // FCFID it and return it.
5890   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5891   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5892     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5893   return FP;
5894 }
5895
5896 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5897                                             SelectionDAG &DAG) const {
5898   SDLoc dl(Op);
5899   /*
5900    The rounding mode is in bits 30:31 of FPSR, and has the following
5901    settings:
5902      00 Round to nearest
5903      01 Round to 0
5904      10 Round to +inf
5905      11 Round to -inf
5906
5907   FLT_ROUNDS, on the other hand, expects the following:
5908     -1 Undefined
5909      0 Round to 0
5910      1 Round to nearest
5911      2 Round to +inf
5912      3 Round to -inf
5913
5914   To perform the conversion, we do:
5915     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5916   */
5917
5918   MachineFunction &MF = DAG.getMachineFunction();
5919   EVT VT = Op.getValueType();
5920   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5921
5922   // Save FP Control Word to register
5923   EVT NodeTys[] = {
5924     MVT::f64,    // return register
5925     MVT::Glue    // unused in this context
5926   };
5927   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5928
5929   // Save FP register to stack slot
5930   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5931   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5932   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5933                                StackSlot, MachinePointerInfo(), false, false,0);
5934
5935   // Load FP Control Word from low 32 bits of stack slot.
5936   SDValue Four = DAG.getConstant(4, PtrVT);
5937   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5938   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5939                             false, false, false, 0);
5940
5941   // Transform as necessary
5942   SDValue CWD1 =
5943     DAG.getNode(ISD::AND, dl, MVT::i32,
5944                 CWD, DAG.getConstant(3, MVT::i32));
5945   SDValue CWD2 =
5946     DAG.getNode(ISD::SRL, dl, MVT::i32,
5947                 DAG.getNode(ISD::AND, dl, MVT::i32,
5948                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5949                                         CWD, DAG.getConstant(3, MVT::i32)),
5950                             DAG.getConstant(3, MVT::i32)),
5951                 DAG.getConstant(1, MVT::i32));
5952
5953   SDValue RetVal =
5954     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5955
5956   return DAG.getNode((VT.getSizeInBits() < 16 ?
5957                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5958 }
5959
5960 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5961   EVT VT = Op.getValueType();
5962   unsigned BitWidth = VT.getSizeInBits();
5963   SDLoc dl(Op);
5964   assert(Op.getNumOperands() == 3 &&
5965          VT == Op.getOperand(1).getValueType() &&
5966          "Unexpected SHL!");
5967
5968   // Expand into a bunch of logical ops.  Note that these ops
5969   // depend on the PPC behavior for oversized shift amounts.
5970   SDValue Lo = Op.getOperand(0);
5971   SDValue Hi = Op.getOperand(1);
5972   SDValue Amt = Op.getOperand(2);
5973   EVT AmtVT = Amt.getValueType();
5974
5975   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5976                              DAG.getConstant(BitWidth, AmtVT), Amt);
5977   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5978   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5979   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5980   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5981                              DAG.getConstant(-BitWidth, AmtVT));
5982   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5983   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5984   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5985   SDValue OutOps[] = { OutLo, OutHi };
5986   return DAG.getMergeValues(OutOps, dl);
5987 }
5988
5989 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5990   EVT VT = Op.getValueType();
5991   SDLoc dl(Op);
5992   unsigned BitWidth = VT.getSizeInBits();
5993   assert(Op.getNumOperands() == 3 &&
5994          VT == Op.getOperand(1).getValueType() &&
5995          "Unexpected SRL!");
5996
5997   // Expand into a bunch of logical ops.  Note that these ops
5998   // depend on the PPC behavior for oversized shift amounts.
5999   SDValue Lo = Op.getOperand(0);
6000   SDValue Hi = Op.getOperand(1);
6001   SDValue Amt = Op.getOperand(2);
6002   EVT AmtVT = Amt.getValueType();
6003
6004   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6005                              DAG.getConstant(BitWidth, AmtVT), Amt);
6006   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6007   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6008   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6009   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6010                              DAG.getConstant(-BitWidth, AmtVT));
6011   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6012   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6013   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6014   SDValue OutOps[] = { OutLo, OutHi };
6015   return DAG.getMergeValues(OutOps, dl);
6016 }
6017
6018 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6019   SDLoc dl(Op);
6020   EVT VT = Op.getValueType();
6021   unsigned BitWidth = VT.getSizeInBits();
6022   assert(Op.getNumOperands() == 3 &&
6023          VT == Op.getOperand(1).getValueType() &&
6024          "Unexpected SRA!");
6025
6026   // Expand into a bunch of logical ops, followed by a select_cc.
6027   SDValue Lo = Op.getOperand(0);
6028   SDValue Hi = Op.getOperand(1);
6029   SDValue Amt = Op.getOperand(2);
6030   EVT AmtVT = Amt.getValueType();
6031
6032   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6033                              DAG.getConstant(BitWidth, AmtVT), Amt);
6034   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6035   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6036   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6037   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6038                              DAG.getConstant(-BitWidth, AmtVT));
6039   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6040   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6041   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6042                                   Tmp4, Tmp6, ISD::SETLE);
6043   SDValue OutOps[] = { OutLo, OutHi };
6044   return DAG.getMergeValues(OutOps, dl);
6045 }
6046
6047 //===----------------------------------------------------------------------===//
6048 // Vector related lowering.
6049 //
6050
6051 /// BuildSplatI - Build a canonical splati of Val with an element size of
6052 /// SplatSize.  Cast the result to VT.
6053 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6054                              SelectionDAG &DAG, SDLoc dl) {
6055   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6056
6057   static const EVT VTys[] = { // canonical VT to use for each size.
6058     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6059   };
6060
6061   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6062
6063   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6064   if (Val == -1)
6065     SplatSize = 1;
6066
6067   EVT CanonicalVT = VTys[SplatSize-1];
6068
6069   // Build a canonical splat for this value.
6070   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6071   SmallVector<SDValue, 8> Ops;
6072   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6073   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6074   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6075 }
6076
6077 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6078 /// specified intrinsic ID.
6079 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6080                                 SelectionDAG &DAG, SDLoc dl,
6081                                 EVT DestVT = MVT::Other) {
6082   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6083   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6084                      DAG.getConstant(IID, MVT::i32), Op);
6085 }
6086
6087 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6088 /// specified intrinsic ID.
6089 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6090                                 SelectionDAG &DAG, SDLoc dl,
6091                                 EVT DestVT = MVT::Other) {
6092   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6093   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6094                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6095 }
6096
6097 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6098 /// specified intrinsic ID.
6099 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6100                                 SDValue Op2, SelectionDAG &DAG,
6101                                 SDLoc dl, EVT DestVT = MVT::Other) {
6102   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6103   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6104                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6105 }
6106
6107
6108 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6109 /// amount.  The result has the specified value type.
6110 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6111                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6112   // Force LHS/RHS to be the right type.
6113   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6114   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6115
6116   int Ops[16];
6117   for (unsigned i = 0; i != 16; ++i)
6118     Ops[i] = i + Amt;
6119   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6120   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6121 }
6122
6123 // If this is a case we can't handle, return null and let the default
6124 // expansion code take care of it.  If we CAN select this case, and if it
6125 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6126 // this case more efficiently than a constant pool load, lower it to the
6127 // sequence of ops that should be used.
6128 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6129                                              SelectionDAG &DAG) const {
6130   SDLoc dl(Op);
6131   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6132   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6133
6134   // Check if this is a splat of a constant value.
6135   APInt APSplatBits, APSplatUndef;
6136   unsigned SplatBitSize;
6137   bool HasAnyUndefs;
6138   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6139                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6140     return SDValue();
6141
6142   unsigned SplatBits = APSplatBits.getZExtValue();
6143   unsigned SplatUndef = APSplatUndef.getZExtValue();
6144   unsigned SplatSize = SplatBitSize / 8;
6145
6146   // First, handle single instruction cases.
6147
6148   // All zeros?
6149   if (SplatBits == 0) {
6150     // Canonicalize all zero vectors to be v4i32.
6151     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6152       SDValue Z = DAG.getConstant(0, MVT::i32);
6153       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6154       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6155     }
6156     return Op;
6157   }
6158
6159   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6160   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6161                     (32-SplatBitSize));
6162   if (SextVal >= -16 && SextVal <= 15)
6163     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6164
6165
6166   // Two instruction sequences.
6167
6168   // If this value is in the range [-32,30] and is even, use:
6169   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6170   // If this value is in the range [17,31] and is odd, use:
6171   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6172   // If this value is in the range [-31,-17] and is odd, use:
6173   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6174   // Note the last two are three-instruction sequences.
6175   if (SextVal >= -32 && SextVal <= 31) {
6176     // To avoid having these optimizations undone by constant folding,
6177     // we convert to a pseudo that will be expanded later into one of
6178     // the above forms.
6179     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6180     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6181               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6182     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6183     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6184     if (VT == Op.getValueType())
6185       return RetVal;
6186     else
6187       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6188   }
6189
6190   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6191   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6192   // for fneg/fabs.
6193   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6194     // Make -1 and vspltisw -1:
6195     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6196
6197     // Make the VSLW intrinsic, computing 0x8000_0000.
6198     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6199                                    OnesV, DAG, dl);
6200
6201     // xor by OnesV to invert it.
6202     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6203     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6204   }
6205
6206   // The remaining cases assume either big endian element order or
6207   // a splat-size that equates to the element size of the vector
6208   // to be built.  An example that doesn't work for little endian is
6209   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6210   // and a vector element size of 16 bits.  The code below will
6211   // produce the vector in big endian element order, which for little
6212   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6213
6214   // For now, just avoid these optimizations in that case.
6215   // FIXME: Develop correct optimizations for LE with mismatched
6216   // splat and element sizes.
6217
6218   if (Subtarget.isLittleEndian() &&
6219       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6220     return SDValue();
6221
6222   // Check to see if this is a wide variety of vsplti*, binop self cases.
6223   static const signed char SplatCsts[] = {
6224     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6225     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6226   };
6227
6228   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6229     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6230     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6231     int i = SplatCsts[idx];
6232
6233     // Figure out what shift amount will be used by altivec if shifted by i in
6234     // this splat size.
6235     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6236
6237     // vsplti + shl self.
6238     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6239       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6240       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6241         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6242         Intrinsic::ppc_altivec_vslw
6243       };
6244       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6245       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6246     }
6247
6248     // vsplti + srl self.
6249     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6250       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6251       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6252         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6253         Intrinsic::ppc_altivec_vsrw
6254       };
6255       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6256       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6257     }
6258
6259     // vsplti + sra self.
6260     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6261       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6262       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6263         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6264         Intrinsic::ppc_altivec_vsraw
6265       };
6266       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6267       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6268     }
6269
6270     // vsplti + rol self.
6271     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6272                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6273       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6274       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6275         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6276         Intrinsic::ppc_altivec_vrlw
6277       };
6278       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6279       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6280     }
6281
6282     // t = vsplti c, result = vsldoi t, t, 1
6283     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6284       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6285       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6286     }
6287     // t = vsplti c, result = vsldoi t, t, 2
6288     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6289       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6290       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6291     }
6292     // t = vsplti c, result = vsldoi t, t, 3
6293     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6294       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6295       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6296     }
6297   }
6298
6299   return SDValue();
6300 }
6301
6302 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6303 /// the specified operations to build the shuffle.
6304 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6305                                       SDValue RHS, SelectionDAG &DAG,
6306                                       SDLoc dl) {
6307   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6308   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6309   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6310
6311   enum {
6312     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6313     OP_VMRGHW,
6314     OP_VMRGLW,
6315     OP_VSPLTISW0,
6316     OP_VSPLTISW1,
6317     OP_VSPLTISW2,
6318     OP_VSPLTISW3,
6319     OP_VSLDOI4,
6320     OP_VSLDOI8,
6321     OP_VSLDOI12
6322   };
6323
6324   if (OpNum == OP_COPY) {
6325     if (LHSID == (1*9+2)*9+3) return LHS;
6326     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6327     return RHS;
6328   }
6329
6330   SDValue OpLHS, OpRHS;
6331   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6332   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6333
6334   int ShufIdxs[16];
6335   switch (OpNum) {
6336   default: llvm_unreachable("Unknown i32 permute!");
6337   case OP_VMRGHW:
6338     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6339     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6340     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6341     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6342     break;
6343   case OP_VMRGLW:
6344     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6345     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6346     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6347     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6348     break;
6349   case OP_VSPLTISW0:
6350     for (unsigned i = 0; i != 16; ++i)
6351       ShufIdxs[i] = (i&3)+0;
6352     break;
6353   case OP_VSPLTISW1:
6354     for (unsigned i = 0; i != 16; ++i)
6355       ShufIdxs[i] = (i&3)+4;
6356     break;
6357   case OP_VSPLTISW2:
6358     for (unsigned i = 0; i != 16; ++i)
6359       ShufIdxs[i] = (i&3)+8;
6360     break;
6361   case OP_VSPLTISW3:
6362     for (unsigned i = 0; i != 16; ++i)
6363       ShufIdxs[i] = (i&3)+12;
6364     break;
6365   case OP_VSLDOI4:
6366     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6367   case OP_VSLDOI8:
6368     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6369   case OP_VSLDOI12:
6370     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6371   }
6372   EVT VT = OpLHS.getValueType();
6373   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6374   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6375   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6376   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6377 }
6378
6379 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6380 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6381 /// return the code it can be lowered into.  Worst case, it can always be
6382 /// lowered into a vperm.
6383 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6384                                                SelectionDAG &DAG) const {
6385   SDLoc dl(Op);
6386   SDValue V1 = Op.getOperand(0);
6387   SDValue V2 = Op.getOperand(1);
6388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6389   EVT VT = Op.getValueType();
6390   bool isLittleEndian = Subtarget.isLittleEndian();
6391
6392   // Cases that are handled by instructions that take permute immediates
6393   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6394   // selected by the instruction selector.
6395   if (V2.getOpcode() == ISD::UNDEF) {
6396     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6397         PPC::isSplatShuffleMask(SVOp, 2) ||
6398         PPC::isSplatShuffleMask(SVOp, 4) ||
6399         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6400         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6401         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6402         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6403         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6404         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6405         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6406         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6407         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6408       return Op;
6409     }
6410   }
6411
6412   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6413   // and produce a fixed permutation.  If any of these match, do not lower to
6414   // VPERM.
6415   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6416   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6417       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6418       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6419       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6420       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6421       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6422       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6423       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6424       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6425     return Op;
6426
6427   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6428   // perfect shuffle table to emit an optimal matching sequence.
6429   ArrayRef<int> PermMask = SVOp->getMask();
6430
6431   unsigned PFIndexes[4];
6432   bool isFourElementShuffle = true;
6433   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6434     unsigned EltNo = 8;   // Start out undef.
6435     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6436       if (PermMask[i*4+j] < 0)
6437         continue;   // Undef, ignore it.
6438
6439       unsigned ByteSource = PermMask[i*4+j];
6440       if ((ByteSource & 3) != j) {
6441         isFourElementShuffle = false;
6442         break;
6443       }
6444
6445       if (EltNo == 8) {
6446         EltNo = ByteSource/4;
6447       } else if (EltNo != ByteSource/4) {
6448         isFourElementShuffle = false;
6449         break;
6450       }
6451     }
6452     PFIndexes[i] = EltNo;
6453   }
6454
6455   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6456   // perfect shuffle vector to determine if it is cost effective to do this as
6457   // discrete instructions, or whether we should use a vperm.
6458   // For now, we skip this for little endian until such time as we have a
6459   // little-endian perfect shuffle table.
6460   if (isFourElementShuffle && !isLittleEndian) {
6461     // Compute the index in the perfect shuffle table.
6462     unsigned PFTableIndex =
6463       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6464
6465     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6466     unsigned Cost  = (PFEntry >> 30);
6467
6468     // Determining when to avoid vperm is tricky.  Many things affect the cost
6469     // of vperm, particularly how many times the perm mask needs to be computed.
6470     // For example, if the perm mask can be hoisted out of a loop or is already
6471     // used (perhaps because there are multiple permutes with the same shuffle
6472     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6473     // the loop requires an extra register.
6474     //
6475     // As a compromise, we only emit discrete instructions if the shuffle can be
6476     // generated in 3 or fewer operations.  When we have loop information
6477     // available, if this block is within a loop, we should avoid using vperm
6478     // for 3-operation perms and use a constant pool load instead.
6479     if (Cost < 3)
6480       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6481   }
6482
6483   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6484   // vector that will get spilled to the constant pool.
6485   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6486
6487   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6488   // that it is in input element units, not in bytes.  Convert now.
6489
6490   // For little endian, the order of the input vectors is reversed, and
6491   // the permutation mask is complemented with respect to 31.  This is
6492   // necessary to produce proper semantics with the big-endian-biased vperm
6493   // instruction.
6494   EVT EltVT = V1.getValueType().getVectorElementType();
6495   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6496
6497   SmallVector<SDValue, 16> ResultMask;
6498   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6499     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6500
6501     for (unsigned j = 0; j != BytesPerElement; ++j)
6502       if (isLittleEndian)
6503         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6504                                              MVT::i32));
6505       else
6506         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6507                                              MVT::i32));
6508   }
6509
6510   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6511                                   ResultMask);
6512   if (isLittleEndian)
6513     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6514                        V2, V1, VPermMask);
6515   else
6516     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6517                        V1, V2, VPermMask);
6518 }
6519
6520 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6521 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6522 /// information about the intrinsic.
6523 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6524                                   bool &isDot) {
6525   unsigned IntrinsicID =
6526     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6527   CompareOpc = -1;
6528   isDot = false;
6529   switch (IntrinsicID) {
6530   default: return false;
6531     // Comparison predicates.
6532   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6533   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6534   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6535   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6536   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6537   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6538   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6539   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6540   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6541   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6542   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6543   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6544   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6545
6546     // Normal Comparisons.
6547   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6548   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6549   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6550   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6551   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6552   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6553   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6554   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6555   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6556   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6557   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6558   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6559   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6560   }
6561   return true;
6562 }
6563
6564 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6565 /// lower, do it, otherwise return null.
6566 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6567                                                    SelectionDAG &DAG) const {
6568   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6569   // opcode number of the comparison.
6570   SDLoc dl(Op);
6571   int CompareOpc;
6572   bool isDot;
6573   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6574     return SDValue();    // Don't custom lower most intrinsics.
6575
6576   // If this is a non-dot comparison, make the VCMP node and we are done.
6577   if (!isDot) {
6578     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6579                               Op.getOperand(1), Op.getOperand(2),
6580                               DAG.getConstant(CompareOpc, MVT::i32));
6581     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6582   }
6583
6584   // Create the PPCISD altivec 'dot' comparison node.
6585   SDValue Ops[] = {
6586     Op.getOperand(2),  // LHS
6587     Op.getOperand(3),  // RHS
6588     DAG.getConstant(CompareOpc, MVT::i32)
6589   };
6590   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6591   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6592
6593   // Now that we have the comparison, emit a copy from the CR to a GPR.
6594   // This is flagged to the above dot comparison.
6595   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6596                                 DAG.getRegister(PPC::CR6, MVT::i32),
6597                                 CompNode.getValue(1));
6598
6599   // Unpack the result based on how the target uses it.
6600   unsigned BitNo;   // Bit # of CR6.
6601   bool InvertBit;   // Invert result?
6602   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6603   default:  // Can't happen, don't crash on invalid number though.
6604   case 0:   // Return the value of the EQ bit of CR6.
6605     BitNo = 0; InvertBit = false;
6606     break;
6607   case 1:   // Return the inverted value of the EQ bit of CR6.
6608     BitNo = 0; InvertBit = true;
6609     break;
6610   case 2:   // Return the value of the LT bit of CR6.
6611     BitNo = 2; InvertBit = false;
6612     break;
6613   case 3:   // Return the inverted value of the LT bit of CR6.
6614     BitNo = 2; InvertBit = true;
6615     break;
6616   }
6617
6618   // Shift the bit into the low position.
6619   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6620                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6621   // Isolate the bit.
6622   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6623                       DAG.getConstant(1, MVT::i32));
6624
6625   // If we are supposed to, toggle the bit.
6626   if (InvertBit)
6627     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6628                         DAG.getConstant(1, MVT::i32));
6629   return Flags;
6630 }
6631
6632 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6633                                                   SelectionDAG &DAG) const {
6634   SDLoc dl(Op);
6635   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6636   // instructions), but for smaller types, we need to first extend up to v2i32
6637   // before doing going farther.
6638   if (Op.getValueType() == MVT::v2i64) {
6639     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6640     if (ExtVT != MVT::v2i32) {
6641       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6642       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6643                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6644                                         ExtVT.getVectorElementType(), 4)));
6645       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6646       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6647                        DAG.getValueType(MVT::v2i32));
6648     }
6649
6650     return Op;
6651   }
6652
6653   return SDValue();
6654 }
6655
6656 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6657                                                    SelectionDAG &DAG) const {
6658   SDLoc dl(Op);
6659   // Create a stack slot that is 16-byte aligned.
6660   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6661   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6662   EVT PtrVT = getPointerTy();
6663   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6664
6665   // Store the input value into Value#0 of the stack slot.
6666   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6667                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6668                                false, false, 0);
6669   // Load it out.
6670   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6671                      false, false, false, 0);
6672 }
6673
6674 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6675   SDLoc dl(Op);
6676   if (Op.getValueType() == MVT::v4i32) {
6677     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6678
6679     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6680     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6681
6682     SDValue RHSSwap =   // = vrlw RHS, 16
6683       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6684
6685     // Shrinkify inputs to v8i16.
6686     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6687     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6688     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6689
6690     // Low parts multiplied together, generating 32-bit results (we ignore the
6691     // top parts).
6692     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6693                                         LHS, RHS, DAG, dl, MVT::v4i32);
6694
6695     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6696                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6697     // Shift the high parts up 16 bits.
6698     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6699                               Neg16, DAG, dl);
6700     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6701   } else if (Op.getValueType() == MVT::v8i16) {
6702     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6703
6704     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6705
6706     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6707                             LHS, RHS, Zero, DAG, dl);
6708   } else if (Op.getValueType() == MVT::v16i8) {
6709     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6710     bool isLittleEndian = Subtarget.isLittleEndian();
6711
6712     // Multiply the even 8-bit parts, producing 16-bit sums.
6713     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6714                                            LHS, RHS, DAG, dl, MVT::v8i16);
6715     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6716
6717     // Multiply the odd 8-bit parts, producing 16-bit sums.
6718     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6719                                           LHS, RHS, DAG, dl, MVT::v8i16);
6720     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6721
6722     // Merge the results together.  Because vmuleub and vmuloub are
6723     // instructions with a big-endian bias, we must reverse the
6724     // element numbering and reverse the meaning of "odd" and "even"
6725     // when generating little endian code.
6726     int Ops[16];
6727     for (unsigned i = 0; i != 8; ++i) {
6728       if (isLittleEndian) {
6729         Ops[i*2  ] = 2*i;
6730         Ops[i*2+1] = 2*i+16;
6731       } else {
6732         Ops[i*2  ] = 2*i+1;
6733         Ops[i*2+1] = 2*i+1+16;
6734       }
6735     }
6736     if (isLittleEndian)
6737       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6738     else
6739       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6740   } else {
6741     llvm_unreachable("Unknown mul to lower!");
6742   }
6743 }
6744
6745 /// LowerOperation - Provide custom lowering hooks for some operations.
6746 ///
6747 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6748   switch (Op.getOpcode()) {
6749   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6750   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6751   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6752   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6753   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6754   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6755   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6756   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6757   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6758   case ISD::VASTART:
6759     return LowerVASTART(Op, DAG, Subtarget);
6760
6761   case ISD::VAARG:
6762     return LowerVAARG(Op, DAG, Subtarget);
6763
6764   case ISD::VACOPY:
6765     return LowerVACOPY(Op, DAG, Subtarget);
6766
6767   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6768   case ISD::DYNAMIC_STACKALLOC:
6769     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6770
6771   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6772   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6773
6774   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6775   case ISD::STORE:              return LowerSTORE(Op, DAG);
6776   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6777   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6778   case ISD::FP_TO_UINT:
6779   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6780                                                       SDLoc(Op));
6781   case ISD::UINT_TO_FP:
6782   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6783   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6784
6785   // Lower 64-bit shifts.
6786   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6787   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6788   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6789
6790   // Vector-related lowering.
6791   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6792   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6793   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6794   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6795   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6796   case ISD::MUL:                return LowerMUL(Op, DAG);
6797
6798   // For counter-based loop handling.
6799   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6800
6801   // Frame & Return address.
6802   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6803   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6804   }
6805 }
6806
6807 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6808                                            SmallVectorImpl<SDValue>&Results,
6809                                            SelectionDAG &DAG) const {
6810   SDLoc dl(N);
6811   switch (N->getOpcode()) {
6812   default:
6813     llvm_unreachable("Do not know how to custom type legalize this operation!");
6814   case ISD::READCYCLECOUNTER: {
6815     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6816     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6817
6818     Results.push_back(RTB);
6819     Results.push_back(RTB.getValue(1));
6820     Results.push_back(RTB.getValue(2));
6821     break;
6822   }
6823   case ISD::INTRINSIC_W_CHAIN: {
6824     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6825         Intrinsic::ppc_is_decremented_ctr_nonzero)
6826       break;
6827
6828     assert(N->getValueType(0) == MVT::i1 &&
6829            "Unexpected result type for CTR decrement intrinsic");
6830     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6831     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6832     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6833                                  N->getOperand(1)); 
6834
6835     Results.push_back(NewInt);
6836     Results.push_back(NewInt.getValue(1));
6837     break;
6838   }
6839   case ISD::VAARG: {
6840     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
6841       return;
6842
6843     EVT VT = N->getValueType(0);
6844
6845     if (VT == MVT::i64) {
6846       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6847
6848       Results.push_back(NewNode);
6849       Results.push_back(NewNode.getValue(1));
6850     }
6851     return;
6852   }
6853   case ISD::FP_ROUND_INREG: {
6854     assert(N->getValueType(0) == MVT::ppcf128);
6855     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6856     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6857                              MVT::f64, N->getOperand(0),
6858                              DAG.getIntPtrConstant(0));
6859     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6860                              MVT::f64, N->getOperand(0),
6861                              DAG.getIntPtrConstant(1));
6862
6863     // Add the two halves of the long double in round-to-zero mode.
6864     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6865
6866     // We know the low half is about to be thrown away, so just use something
6867     // convenient.
6868     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6869                                 FPreg, FPreg));
6870     return;
6871   }
6872   case ISD::FP_TO_SINT:
6873     // LowerFP_TO_INT() can only handle f32 and f64.
6874     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6875       return;
6876     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6877     return;
6878   }
6879 }
6880
6881
6882 //===----------------------------------------------------------------------===//
6883 //  Other Lowering Code
6884 //===----------------------------------------------------------------------===//
6885
6886 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6887   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6888   Function *Func = Intrinsic::getDeclaration(M, Id);
6889   return Builder.CreateCall(Func);
6890 }
6891
6892 // The mappings for emitLeading/TrailingFence is taken from
6893 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6894 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6895                                          AtomicOrdering Ord, bool IsStore,
6896                                          bool IsLoad) const {
6897   if (Ord == SequentiallyConsistent)
6898     return callIntrinsic(Builder, Intrinsic::ppc_sync);
6899   else if (isAtLeastRelease(Ord))
6900     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6901   else
6902     return nullptr;
6903 }
6904
6905 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6906                                           AtomicOrdering Ord, bool IsStore,
6907                                           bool IsLoad) const {
6908   if (IsLoad && isAtLeastAcquire(Ord))
6909     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6910   // FIXME: this is too conservative, a dependent branch + isync is enough.
6911   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6912   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6913   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6914   else
6915     return nullptr;
6916 }
6917
6918 MachineBasicBlock *
6919 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6920                                     bool is64bit, unsigned BinOpcode) const {
6921   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6922   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6923
6924   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6925   MachineFunction *F = BB->getParent();
6926   MachineFunction::iterator It = BB;
6927   ++It;
6928
6929   unsigned dest = MI->getOperand(0).getReg();
6930   unsigned ptrA = MI->getOperand(1).getReg();
6931   unsigned ptrB = MI->getOperand(2).getReg();
6932   unsigned incr = MI->getOperand(3).getReg();
6933   DebugLoc dl = MI->getDebugLoc();
6934
6935   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6936   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6937   F->insert(It, loopMBB);
6938   F->insert(It, exitMBB);
6939   exitMBB->splice(exitMBB->begin(), BB,
6940                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6941   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6942
6943   MachineRegisterInfo &RegInfo = F->getRegInfo();
6944   unsigned TmpReg = (!BinOpcode) ? incr :
6945     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6946                                            : &PPC::GPRCRegClass);
6947
6948   //  thisMBB:
6949   //   ...
6950   //   fallthrough --> loopMBB
6951   BB->addSuccessor(loopMBB);
6952
6953   //  loopMBB:
6954   //   l[wd]arx dest, ptr
6955   //   add r0, dest, incr
6956   //   st[wd]cx. r0, ptr
6957   //   bne- loopMBB
6958   //   fallthrough --> exitMBB
6959   BB = loopMBB;
6960   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6961     .addReg(ptrA).addReg(ptrB);
6962   if (BinOpcode)
6963     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6964   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6965     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6966   BuildMI(BB, dl, TII->get(PPC::BCC))
6967     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6968   BB->addSuccessor(loopMBB);
6969   BB->addSuccessor(exitMBB);
6970
6971   //  exitMBB:
6972   //   ...
6973   BB = exitMBB;
6974   return BB;
6975 }
6976
6977 MachineBasicBlock *
6978 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6979                                             MachineBasicBlock *BB,
6980                                             bool is8bit,    // operation
6981                                             unsigned BinOpcode) const {
6982   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6983   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
6984   // In 64 bit mode we have to use 64 bits for addresses, even though the
6985   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6986   // registers without caring whether they're 32 or 64, but here we're
6987   // doing actual arithmetic on the addresses.
6988   bool is64bit = Subtarget.isPPC64();
6989   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6990
6991   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6992   MachineFunction *F = BB->getParent();
6993   MachineFunction::iterator It = BB;
6994   ++It;
6995
6996   unsigned dest = MI->getOperand(0).getReg();
6997   unsigned ptrA = MI->getOperand(1).getReg();
6998   unsigned ptrB = MI->getOperand(2).getReg();
6999   unsigned incr = MI->getOperand(3).getReg();
7000   DebugLoc dl = MI->getDebugLoc();
7001
7002   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7003   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7004   F->insert(It, loopMBB);
7005   F->insert(It, exitMBB);
7006   exitMBB->splice(exitMBB->begin(), BB,
7007                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7008   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7009
7010   MachineRegisterInfo &RegInfo = F->getRegInfo();
7011   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7012                                           : &PPC::GPRCRegClass;
7013   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7014   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7015   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7016   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7017   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7018   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7019   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7020   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7021   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7022   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7023   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7024   unsigned Ptr1Reg;
7025   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7026
7027   //  thisMBB:
7028   //   ...
7029   //   fallthrough --> loopMBB
7030   BB->addSuccessor(loopMBB);
7031
7032   // The 4-byte load must be aligned, while a char or short may be
7033   // anywhere in the word.  Hence all this nasty bookkeeping code.
7034   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7035   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7036   //   xori shift, shift1, 24 [16]
7037   //   rlwinm ptr, ptr1, 0, 0, 29
7038   //   slw incr2, incr, shift
7039   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7040   //   slw mask, mask2, shift
7041   //  loopMBB:
7042   //   lwarx tmpDest, ptr
7043   //   add tmp, tmpDest, incr2
7044   //   andc tmp2, tmpDest, mask
7045   //   and tmp3, tmp, mask
7046   //   or tmp4, tmp3, tmp2
7047   //   stwcx. tmp4, ptr
7048   //   bne- loopMBB
7049   //   fallthrough --> exitMBB
7050   //   srw dest, tmpDest, shift
7051   if (ptrA != ZeroReg) {
7052     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7053     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7054       .addReg(ptrA).addReg(ptrB);
7055   } else {
7056     Ptr1Reg = ptrB;
7057   }
7058   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7059       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7060   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7061       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7062   if (is64bit)
7063     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7064       .addReg(Ptr1Reg).addImm(0).addImm(61);
7065   else
7066     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7067       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7068   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7069       .addReg(incr).addReg(ShiftReg);
7070   if (is8bit)
7071     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7072   else {
7073     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7074     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7075   }
7076   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7077       .addReg(Mask2Reg).addReg(ShiftReg);
7078
7079   BB = loopMBB;
7080   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7081     .addReg(ZeroReg).addReg(PtrReg);
7082   if (BinOpcode)
7083     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7084       .addReg(Incr2Reg).addReg(TmpDestReg);
7085   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7086     .addReg(TmpDestReg).addReg(MaskReg);
7087   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7088     .addReg(TmpReg).addReg(MaskReg);
7089   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7090     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7091   BuildMI(BB, dl, TII->get(PPC::STWCX))
7092     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7093   BuildMI(BB, dl, TII->get(PPC::BCC))
7094     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7095   BB->addSuccessor(loopMBB);
7096   BB->addSuccessor(exitMBB);
7097
7098   //  exitMBB:
7099   //   ...
7100   BB = exitMBB;
7101   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7102     .addReg(ShiftReg);
7103   return BB;
7104 }
7105
7106 llvm::MachineBasicBlock*
7107 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7108                                     MachineBasicBlock *MBB) const {
7109   DebugLoc DL = MI->getDebugLoc();
7110   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7111
7112   MachineFunction *MF = MBB->getParent();
7113   MachineRegisterInfo &MRI = MF->getRegInfo();
7114
7115   const BasicBlock *BB = MBB->getBasicBlock();
7116   MachineFunction::iterator I = MBB;
7117   ++I;
7118
7119   // Memory Reference
7120   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7121   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7122
7123   unsigned DstReg = MI->getOperand(0).getReg();
7124   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7125   assert(RC->hasType(MVT::i32) && "Invalid destination!");
7126   unsigned mainDstReg = MRI.createVirtualRegister(RC);
7127   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7128
7129   MVT PVT = getPointerTy();
7130   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7131          "Invalid Pointer Size!");
7132   // For v = setjmp(buf), we generate
7133   //
7134   // thisMBB:
7135   //  SjLjSetup mainMBB
7136   //  bl mainMBB
7137   //  v_restore = 1
7138   //  b sinkMBB
7139   //
7140   // mainMBB:
7141   //  buf[LabelOffset] = LR
7142   //  v_main = 0
7143   //
7144   // sinkMBB:
7145   //  v = phi(main, restore)
7146   //
7147
7148   MachineBasicBlock *thisMBB = MBB;
7149   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7150   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7151   MF->insert(I, mainMBB);
7152   MF->insert(I, sinkMBB);
7153
7154   MachineInstrBuilder MIB;
7155
7156   // Transfer the remainder of BB and its successor edges to sinkMBB.
7157   sinkMBB->splice(sinkMBB->begin(), MBB,
7158                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7159   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7160
7161   // Note that the structure of the jmp_buf used here is not compatible
7162   // with that used by libc, and is not designed to be. Specifically, it
7163   // stores only those 'reserved' registers that LLVM does not otherwise
7164   // understand how to spill. Also, by convention, by the time this
7165   // intrinsic is called, Clang has already stored the frame address in the
7166   // first slot of the buffer and stack address in the third. Following the
7167   // X86 target code, we'll store the jump address in the second slot. We also
7168   // need to save the TOC pointer (R2) to handle jumps between shared
7169   // libraries, and that will be stored in the fourth slot. The thread
7170   // identifier (R13) is not affected.
7171
7172   // thisMBB:
7173   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7174   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7175   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7176
7177   // Prepare IP either in reg.
7178   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7179   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7180   unsigned BufReg = MI->getOperand(1).getReg();
7181
7182   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7183     setUsesTOCBasePtr(*MBB->getParent());
7184     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7185             .addReg(PPC::X2)
7186             .addImm(TOCOffset)
7187             .addReg(BufReg);
7188     MIB.setMemRefs(MMOBegin, MMOEnd);
7189   }
7190
7191   // Naked functions never have a base pointer, and so we use r1. For all
7192   // other functions, this decision must be delayed until during PEI.
7193   unsigned BaseReg;
7194   if (MF->getFunction()->getAttributes().hasAttribute(
7195           AttributeSet::FunctionIndex, Attribute::Naked))
7196     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7197   else
7198     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7199
7200   MIB = BuildMI(*thisMBB, MI, DL,
7201                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7202             .addReg(BaseReg)
7203             .addImm(BPOffset)
7204             .addReg(BufReg);
7205   MIB.setMemRefs(MMOBegin, MMOEnd);
7206
7207   // Setup
7208   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7209   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7210   MIB.addRegMask(TRI->getNoPreservedMask());
7211
7212   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7213
7214   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7215           .addMBB(mainMBB);
7216   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7217
7218   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7219   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7220
7221   // mainMBB:
7222   //  mainDstReg = 0
7223   MIB =
7224       BuildMI(mainMBB, DL,
7225               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7226
7227   // Store IP
7228   if (Subtarget.isPPC64()) {
7229     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7230             .addReg(LabelReg)
7231             .addImm(LabelOffset)
7232             .addReg(BufReg);
7233   } else {
7234     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7235             .addReg(LabelReg)
7236             .addImm(LabelOffset)
7237             .addReg(BufReg);
7238   }
7239
7240   MIB.setMemRefs(MMOBegin, MMOEnd);
7241
7242   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7243   mainMBB->addSuccessor(sinkMBB);
7244
7245   // sinkMBB:
7246   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7247           TII->get(PPC::PHI), DstReg)
7248     .addReg(mainDstReg).addMBB(mainMBB)
7249     .addReg(restoreDstReg).addMBB(thisMBB);
7250
7251   MI->eraseFromParent();
7252   return sinkMBB;
7253 }
7254
7255 MachineBasicBlock *
7256 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7257                                      MachineBasicBlock *MBB) const {
7258   DebugLoc DL = MI->getDebugLoc();
7259   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7260
7261   MachineFunction *MF = MBB->getParent();
7262   MachineRegisterInfo &MRI = MF->getRegInfo();
7263
7264   // Memory Reference
7265   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7266   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7267
7268   MVT PVT = getPointerTy();
7269   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7270          "Invalid Pointer Size!");
7271
7272   const TargetRegisterClass *RC =
7273     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7274   unsigned Tmp = MRI.createVirtualRegister(RC);
7275   // Since FP is only updated here but NOT referenced, it's treated as GPR.
7276   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7277   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7278   unsigned BP =
7279       (PVT == MVT::i64)
7280           ? PPC::X30
7281           : (Subtarget.isSVR4ABI() &&
7282                      MF->getTarget().getRelocationModel() == Reloc::PIC_
7283                  ? PPC::R29
7284                  : PPC::R30);
7285
7286   MachineInstrBuilder MIB;
7287
7288   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7289   const int64_t SPOffset    = 2 * PVT.getStoreSize();
7290   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7291   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7292
7293   unsigned BufReg = MI->getOperand(0).getReg();
7294
7295   // Reload FP (the jumped-to function may not have had a
7296   // frame pointer, and if so, then its r31 will be restored
7297   // as necessary).
7298   if (PVT == MVT::i64) {
7299     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7300             .addImm(0)
7301             .addReg(BufReg);
7302   } else {
7303     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7304             .addImm(0)
7305             .addReg(BufReg);
7306   }
7307   MIB.setMemRefs(MMOBegin, MMOEnd);
7308
7309   // Reload IP
7310   if (PVT == MVT::i64) {
7311     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7312             .addImm(LabelOffset)
7313             .addReg(BufReg);
7314   } else {
7315     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7316             .addImm(LabelOffset)
7317             .addReg(BufReg);
7318   }
7319   MIB.setMemRefs(MMOBegin, MMOEnd);
7320
7321   // Reload SP
7322   if (PVT == MVT::i64) {
7323     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7324             .addImm(SPOffset)
7325             .addReg(BufReg);
7326   } else {
7327     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7328             .addImm(SPOffset)
7329             .addReg(BufReg);
7330   }
7331   MIB.setMemRefs(MMOBegin, MMOEnd);
7332
7333   // Reload BP
7334   if (PVT == MVT::i64) {
7335     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7336             .addImm(BPOffset)
7337             .addReg(BufReg);
7338   } else {
7339     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7340             .addImm(BPOffset)
7341             .addReg(BufReg);
7342   }
7343   MIB.setMemRefs(MMOBegin, MMOEnd);
7344
7345   // Reload TOC
7346   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7347     setUsesTOCBasePtr(*MBB->getParent());
7348     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7349             .addImm(TOCOffset)
7350             .addReg(BufReg);
7351
7352     MIB.setMemRefs(MMOBegin, MMOEnd);
7353   }
7354
7355   // Jump
7356   BuildMI(*MBB, MI, DL,
7357           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7358   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7359
7360   MI->eraseFromParent();
7361   return MBB;
7362 }
7363
7364 MachineBasicBlock *
7365 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7366                                                MachineBasicBlock *BB) const {
7367   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
7368       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7369     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
7370         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
7371       // Call lowering should have added an r2 operand to indicate a dependence
7372       // on the TOC base pointer value. It can't however, because there is no
7373       // way to mark the dependence as implicit there, and so the stackmap code
7374       // will confuse it with a regular operand. Instead, add the dependence
7375       // here.
7376       setUsesTOCBasePtr(*BB->getParent());
7377       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
7378     }
7379
7380     return emitPatchPoint(MI, BB);
7381   }
7382
7383   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7384       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7385     return emitEHSjLjSetJmp(MI, BB);
7386   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7387              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7388     return emitEHSjLjLongJmp(MI, BB);
7389   }
7390
7391   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7392
7393   // To "insert" these instructions we actually have to insert their
7394   // control-flow patterns.
7395   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7396   MachineFunction::iterator It = BB;
7397   ++It;
7398
7399   MachineFunction *F = BB->getParent();
7400
7401   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7402                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
7403                               MI->getOpcode() == PPC::SELECT_I4 ||
7404                               MI->getOpcode() == PPC::SELECT_I8)) {
7405     SmallVector<MachineOperand, 2> Cond;
7406     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7407         MI->getOpcode() == PPC::SELECT_CC_I8)
7408       Cond.push_back(MI->getOperand(4));
7409     else
7410       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7411     Cond.push_back(MI->getOperand(1));
7412
7413     DebugLoc dl = MI->getDebugLoc();
7414     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7415                       Cond, MI->getOperand(2).getReg(),
7416                       MI->getOperand(3).getReg());
7417   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7418              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7419              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7420              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7421              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7422              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7423              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7424              MI->getOpcode() == PPC::SELECT_I4 ||
7425              MI->getOpcode() == PPC::SELECT_I8 ||
7426              MI->getOpcode() == PPC::SELECT_F4 ||
7427              MI->getOpcode() == PPC::SELECT_F8 ||
7428              MI->getOpcode() == PPC::SELECT_VRRC ||
7429              MI->getOpcode() == PPC::SELECT_VSFRC ||
7430              MI->getOpcode() == PPC::SELECT_VSRC) {
7431     // The incoming instruction knows the destination vreg to set, the
7432     // condition code register to branch on, the true/false values to
7433     // select between, and a branch opcode to use.
7434
7435     //  thisMBB:
7436     //  ...
7437     //   TrueVal = ...
7438     //   cmpTY ccX, r1, r2
7439     //   bCC copy1MBB
7440     //   fallthrough --> copy0MBB
7441     MachineBasicBlock *thisMBB = BB;
7442     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7443     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7444     DebugLoc dl = MI->getDebugLoc();
7445     F->insert(It, copy0MBB);
7446     F->insert(It, sinkMBB);
7447
7448     // Transfer the remainder of BB and its successor edges to sinkMBB.
7449     sinkMBB->splice(sinkMBB->begin(), BB,
7450                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7451     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7452
7453     // Next, add the true and fallthrough blocks as its successors.
7454     BB->addSuccessor(copy0MBB);
7455     BB->addSuccessor(sinkMBB);
7456
7457     if (MI->getOpcode() == PPC::SELECT_I4 ||
7458         MI->getOpcode() == PPC::SELECT_I8 ||
7459         MI->getOpcode() == PPC::SELECT_F4 ||
7460         MI->getOpcode() == PPC::SELECT_F8 ||
7461         MI->getOpcode() == PPC::SELECT_VRRC ||
7462         MI->getOpcode() == PPC::SELECT_VSFRC ||
7463         MI->getOpcode() == PPC::SELECT_VSRC) {
7464       BuildMI(BB, dl, TII->get(PPC::BC))
7465         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7466     } else {
7467       unsigned SelectPred = MI->getOperand(4).getImm();
7468       BuildMI(BB, dl, TII->get(PPC::BCC))
7469         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7470     }
7471
7472     //  copy0MBB:
7473     //   %FalseValue = ...
7474     //   # fallthrough to sinkMBB
7475     BB = copy0MBB;
7476
7477     // Update machine-CFG edges
7478     BB->addSuccessor(sinkMBB);
7479
7480     //  sinkMBB:
7481     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7482     //  ...
7483     BB = sinkMBB;
7484     BuildMI(*BB, BB->begin(), dl,
7485             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7486       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7487       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7488   } else if (MI->getOpcode() == PPC::ReadTB) {
7489     // To read the 64-bit time-base register on a 32-bit target, we read the
7490     // two halves. Should the counter have wrapped while it was being read, we
7491     // need to try again.
7492     // ...
7493     // readLoop:
7494     // mfspr Rx,TBU # load from TBU
7495     // mfspr Ry,TB  # load from TB
7496     // mfspr Rz,TBU # load from TBU
7497     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
7498     // bne readLoop   # branch if they're not equal
7499     // ...
7500
7501     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7502     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7503     DebugLoc dl = MI->getDebugLoc();
7504     F->insert(It, readMBB);
7505     F->insert(It, sinkMBB);
7506
7507     // Transfer the remainder of BB and its successor edges to sinkMBB.
7508     sinkMBB->splice(sinkMBB->begin(), BB,
7509                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7510     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7511
7512     BB->addSuccessor(readMBB);
7513     BB = readMBB;
7514
7515     MachineRegisterInfo &RegInfo = F->getRegInfo();
7516     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7517     unsigned LoReg = MI->getOperand(0).getReg();
7518     unsigned HiReg = MI->getOperand(1).getReg();
7519
7520     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7521     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7522     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7523
7524     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7525
7526     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7527       .addReg(HiReg).addReg(ReadAgainReg);
7528     BuildMI(BB, dl, TII->get(PPC::BCC))
7529       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7530
7531     BB->addSuccessor(readMBB);
7532     BB->addSuccessor(sinkMBB);
7533   }
7534   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7535     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7536   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7537     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7538   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7539     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7540   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7541     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7542
7543   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7544     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7545   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7546     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7547   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7548     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7549   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7550     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7551
7552   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7553     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7554   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7555     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7556   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7557     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7558   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7559     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7560
7561   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7562     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7563   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7564     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7565   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7566     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7567   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7568     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7569
7570   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7571     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7572   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7573     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7574   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7575     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7576   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7577     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7578
7579   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7580     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7581   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7582     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7583   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7584     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7585   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7586     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7587
7588   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7589     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7590   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7591     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7592   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7593     BB = EmitAtomicBinary(MI, BB, false, 0);
7594   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7595     BB = EmitAtomicBinary(MI, BB, true, 0);
7596
7597   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7598            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7599     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7600
7601     unsigned dest   = MI->getOperand(0).getReg();
7602     unsigned ptrA   = MI->getOperand(1).getReg();
7603     unsigned ptrB   = MI->getOperand(2).getReg();
7604     unsigned oldval = MI->getOperand(3).getReg();
7605     unsigned newval = MI->getOperand(4).getReg();
7606     DebugLoc dl     = MI->getDebugLoc();
7607
7608     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7609     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7610     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7611     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7612     F->insert(It, loop1MBB);
7613     F->insert(It, loop2MBB);
7614     F->insert(It, midMBB);
7615     F->insert(It, exitMBB);
7616     exitMBB->splice(exitMBB->begin(), BB,
7617                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7618     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7619
7620     //  thisMBB:
7621     //   ...
7622     //   fallthrough --> loopMBB
7623     BB->addSuccessor(loop1MBB);
7624
7625     // loop1MBB:
7626     //   l[wd]arx dest, ptr
7627     //   cmp[wd] dest, oldval
7628     //   bne- midMBB
7629     // loop2MBB:
7630     //   st[wd]cx. newval, ptr
7631     //   bne- loopMBB
7632     //   b exitBB
7633     // midMBB:
7634     //   st[wd]cx. dest, ptr
7635     // exitBB:
7636     BB = loop1MBB;
7637     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7638       .addReg(ptrA).addReg(ptrB);
7639     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7640       .addReg(oldval).addReg(dest);
7641     BuildMI(BB, dl, TII->get(PPC::BCC))
7642       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7643     BB->addSuccessor(loop2MBB);
7644     BB->addSuccessor(midMBB);
7645
7646     BB = loop2MBB;
7647     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7648       .addReg(newval).addReg(ptrA).addReg(ptrB);
7649     BuildMI(BB, dl, TII->get(PPC::BCC))
7650       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7651     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7652     BB->addSuccessor(loop1MBB);
7653     BB->addSuccessor(exitMBB);
7654
7655     BB = midMBB;
7656     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7657       .addReg(dest).addReg(ptrA).addReg(ptrB);
7658     BB->addSuccessor(exitMBB);
7659
7660     //  exitMBB:
7661     //   ...
7662     BB = exitMBB;
7663   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7664              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7665     // We must use 64-bit registers for addresses when targeting 64-bit,
7666     // since we're actually doing arithmetic on them.  Other registers
7667     // can be 32-bit.
7668     bool is64bit = Subtarget.isPPC64();
7669     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7670
7671     unsigned dest   = MI->getOperand(0).getReg();
7672     unsigned ptrA   = MI->getOperand(1).getReg();
7673     unsigned ptrB   = MI->getOperand(2).getReg();
7674     unsigned oldval = MI->getOperand(3).getReg();
7675     unsigned newval = MI->getOperand(4).getReg();
7676     DebugLoc dl     = MI->getDebugLoc();
7677
7678     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7679     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7680     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7681     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7682     F->insert(It, loop1MBB);
7683     F->insert(It, loop2MBB);
7684     F->insert(It, midMBB);
7685     F->insert(It, exitMBB);
7686     exitMBB->splice(exitMBB->begin(), BB,
7687                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7688     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7689
7690     MachineRegisterInfo &RegInfo = F->getRegInfo();
7691     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7692                                             : &PPC::GPRCRegClass;
7693     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7694     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7695     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7696     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7697     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7698     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7699     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7700     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7701     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7702     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7703     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7704     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7705     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7706     unsigned Ptr1Reg;
7707     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7708     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7709     //  thisMBB:
7710     //   ...
7711     //   fallthrough --> loopMBB
7712     BB->addSuccessor(loop1MBB);
7713
7714     // The 4-byte load must be aligned, while a char or short may be
7715     // anywhere in the word.  Hence all this nasty bookkeeping code.
7716     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7717     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7718     //   xori shift, shift1, 24 [16]
7719     //   rlwinm ptr, ptr1, 0, 0, 29
7720     //   slw newval2, newval, shift
7721     //   slw oldval2, oldval,shift
7722     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7723     //   slw mask, mask2, shift
7724     //   and newval3, newval2, mask
7725     //   and oldval3, oldval2, mask
7726     // loop1MBB:
7727     //   lwarx tmpDest, ptr
7728     //   and tmp, tmpDest, mask
7729     //   cmpw tmp, oldval3
7730     //   bne- midMBB
7731     // loop2MBB:
7732     //   andc tmp2, tmpDest, mask
7733     //   or tmp4, tmp2, newval3
7734     //   stwcx. tmp4, ptr
7735     //   bne- loop1MBB
7736     //   b exitBB
7737     // midMBB:
7738     //   stwcx. tmpDest, ptr
7739     // exitBB:
7740     //   srw dest, tmpDest, shift
7741     if (ptrA != ZeroReg) {
7742       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7743       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7744         .addReg(ptrA).addReg(ptrB);
7745     } else {
7746       Ptr1Reg = ptrB;
7747     }
7748     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7749         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7750     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7751         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7752     if (is64bit)
7753       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7754         .addReg(Ptr1Reg).addImm(0).addImm(61);
7755     else
7756       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7757         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7758     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7759         .addReg(newval).addReg(ShiftReg);
7760     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7761         .addReg(oldval).addReg(ShiftReg);
7762     if (is8bit)
7763       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7764     else {
7765       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7766       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7767         .addReg(Mask3Reg).addImm(65535);
7768     }
7769     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7770         .addReg(Mask2Reg).addReg(ShiftReg);
7771     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7772         .addReg(NewVal2Reg).addReg(MaskReg);
7773     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7774         .addReg(OldVal2Reg).addReg(MaskReg);
7775
7776     BB = loop1MBB;
7777     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7778         .addReg(ZeroReg).addReg(PtrReg);
7779     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7780         .addReg(TmpDestReg).addReg(MaskReg);
7781     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7782         .addReg(TmpReg).addReg(OldVal3Reg);
7783     BuildMI(BB, dl, TII->get(PPC::BCC))
7784         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7785     BB->addSuccessor(loop2MBB);
7786     BB->addSuccessor(midMBB);
7787
7788     BB = loop2MBB;
7789     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7790         .addReg(TmpDestReg).addReg(MaskReg);
7791     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7792         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7793     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7794         .addReg(ZeroReg).addReg(PtrReg);
7795     BuildMI(BB, dl, TII->get(PPC::BCC))
7796       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7797     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7798     BB->addSuccessor(loop1MBB);
7799     BB->addSuccessor(exitMBB);
7800
7801     BB = midMBB;
7802     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7803       .addReg(ZeroReg).addReg(PtrReg);
7804     BB->addSuccessor(exitMBB);
7805
7806     //  exitMBB:
7807     //   ...
7808     BB = exitMBB;
7809     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7810       .addReg(ShiftReg);
7811   } else if (MI->getOpcode() == PPC::FADDrtz) {
7812     // This pseudo performs an FADD with rounding mode temporarily forced
7813     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7814     // is not modeled at the SelectionDAG level.
7815     unsigned Dest = MI->getOperand(0).getReg();
7816     unsigned Src1 = MI->getOperand(1).getReg();
7817     unsigned Src2 = MI->getOperand(2).getReg();
7818     DebugLoc dl   = MI->getDebugLoc();
7819
7820     MachineRegisterInfo &RegInfo = F->getRegInfo();
7821     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7822
7823     // Save FPSCR value.
7824     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7825
7826     // Set rounding mode to round-to-zero.
7827     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7828     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7829
7830     // Perform addition.
7831     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7832
7833     // Restore FPSCR value.
7834     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
7835   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7836              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7837              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7838              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7839     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7840                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7841                       PPC::ANDIo8 : PPC::ANDIo;
7842     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7843                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7844
7845     MachineRegisterInfo &RegInfo = F->getRegInfo();
7846     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7847                                                   &PPC::GPRCRegClass :
7848                                                   &PPC::G8RCRegClass);
7849
7850     DebugLoc dl   = MI->getDebugLoc();
7851     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7852       .addReg(MI->getOperand(1).getReg()).addImm(1);
7853     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7854             MI->getOperand(0).getReg())
7855       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7856   } else {
7857     llvm_unreachable("Unexpected instr type to insert");
7858   }
7859
7860   MI->eraseFromParent();   // The pseudo instruction is gone now.
7861   return BB;
7862 }
7863
7864 //===----------------------------------------------------------------------===//
7865 // Target Optimization Hooks
7866 //===----------------------------------------------------------------------===//
7867
7868 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7869                                             DAGCombinerInfo &DCI,
7870                                             unsigned &RefinementSteps,
7871                                             bool &UseOneConstNR) const {
7872   EVT VT = Operand.getValueType();
7873   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7874       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7875       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7876       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7877     // Convergence is quadratic, so we essentially double the number of digits
7878     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7879     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7880     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7881     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7882     if (VT.getScalarType() == MVT::f64)
7883       ++RefinementSteps;
7884     UseOneConstNR = true;
7885     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7886   }
7887   return SDValue();
7888 }
7889
7890 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7891                                             DAGCombinerInfo &DCI,
7892                                             unsigned &RefinementSteps) const {
7893   EVT VT = Operand.getValueType();
7894   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7895       (VT == MVT::f64 && Subtarget.hasFRE()) ||
7896       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7897       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7898     // Convergence is quadratic, so we essentially double the number of digits
7899     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7900     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7901     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7902     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7903     if (VT.getScalarType() == MVT::f64)
7904       ++RefinementSteps;
7905     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7906   }
7907   return SDValue();
7908 }
7909
7910 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7911   // Note: This functionality is used only when unsafe-fp-math is enabled, and
7912   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7913   // enabled for division), this functionality is redundant with the default
7914   // combiner logic (once the division -> reciprocal/multiply transformation
7915   // has taken place). As a result, this matters more for older cores than for
7916   // newer ones.
7917
7918   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7919   // reciprocal if there are two or more FDIVs (for embedded cores with only
7920   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7921   switch (Subtarget.getDarwinDirective()) {
7922   default:
7923     return NumUsers > 2;
7924   case PPC::DIR_440:
7925   case PPC::DIR_A2:
7926   case PPC::DIR_E500mc:
7927   case PPC::DIR_E5500:
7928     return NumUsers > 1;
7929   }
7930 }
7931
7932 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7933                             unsigned Bytes, int Dist,
7934                             SelectionDAG &DAG) {
7935   if (VT.getSizeInBits() / 8 != Bytes)
7936     return false;
7937
7938   SDValue BaseLoc = Base->getBasePtr();
7939   if (Loc.getOpcode() == ISD::FrameIndex) {
7940     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7941       return false;
7942     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7943     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7944     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7945     int FS  = MFI->getObjectSize(FI);
7946     int BFS = MFI->getObjectSize(BFI);
7947     if (FS != BFS || FS != (int)Bytes) return false;
7948     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7949   }
7950
7951   // Handle X+C
7952   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7953       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7954     return true;
7955
7956   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7957   const GlobalValue *GV1 = nullptr;
7958   const GlobalValue *GV2 = nullptr;
7959   int64_t Offset1 = 0;
7960   int64_t Offset2 = 0;
7961   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7962   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7963   if (isGA1 && isGA2 && GV1 == GV2)
7964     return Offset1 == (Offset2 + Dist*Bytes);
7965   return false;
7966 }
7967
7968 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7969 // not enforce equality of the chain operands.
7970 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7971                             unsigned Bytes, int Dist,
7972                             SelectionDAG &DAG) {
7973   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7974     EVT VT = LS->getMemoryVT();
7975     SDValue Loc = LS->getBasePtr();
7976     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7977   }
7978
7979   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7980     EVT VT;
7981     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7982     default: return false;
7983     case Intrinsic::ppc_altivec_lvx:
7984     case Intrinsic::ppc_altivec_lvxl:
7985     case Intrinsic::ppc_vsx_lxvw4x:
7986       VT = MVT::v4i32;
7987       break;
7988     case Intrinsic::ppc_vsx_lxvd2x:
7989       VT = MVT::v2f64;
7990       break;
7991     case Intrinsic::ppc_altivec_lvebx:
7992       VT = MVT::i8;
7993       break;
7994     case Intrinsic::ppc_altivec_lvehx:
7995       VT = MVT::i16;
7996       break;
7997     case Intrinsic::ppc_altivec_lvewx:
7998       VT = MVT::i32;
7999       break;
8000     }
8001
8002     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8003   }
8004
8005   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8006     EVT VT;
8007     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8008     default: return false;
8009     case Intrinsic::ppc_altivec_stvx:
8010     case Intrinsic::ppc_altivec_stvxl:
8011     case Intrinsic::ppc_vsx_stxvw4x:
8012       VT = MVT::v4i32;
8013       break;
8014     case Intrinsic::ppc_vsx_stxvd2x:
8015       VT = MVT::v2f64;
8016       break;
8017     case Intrinsic::ppc_altivec_stvebx:
8018       VT = MVT::i8;
8019       break;
8020     case Intrinsic::ppc_altivec_stvehx:
8021       VT = MVT::i16;
8022       break;
8023     case Intrinsic::ppc_altivec_stvewx:
8024       VT = MVT::i32;
8025       break;
8026     }
8027
8028     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8029   }
8030
8031   return false;
8032 }
8033
8034 // Return true is there is a nearyby consecutive load to the one provided
8035 // (regardless of alignment). We search up and down the chain, looking though
8036 // token factors and other loads (but nothing else). As a result, a true result
8037 // indicates that it is safe to create a new consecutive load adjacent to the
8038 // load provided.
8039 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8040   SDValue Chain = LD->getChain();
8041   EVT VT = LD->getMemoryVT();
8042
8043   SmallSet<SDNode *, 16> LoadRoots;
8044   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8045   SmallSet<SDNode *, 16> Visited;
8046
8047   // First, search up the chain, branching to follow all token-factor operands.
8048   // If we find a consecutive load, then we're done, otherwise, record all
8049   // nodes just above the top-level loads and token factors.
8050   while (!Queue.empty()) {
8051     SDNode *ChainNext = Queue.pop_back_val();
8052     if (!Visited.insert(ChainNext).second)
8053       continue;
8054
8055     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8056       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8057         return true;
8058
8059       if (!Visited.count(ChainLD->getChain().getNode()))
8060         Queue.push_back(ChainLD->getChain().getNode());
8061     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8062       for (const SDUse &O : ChainNext->ops())
8063         if (!Visited.count(O.getNode()))
8064           Queue.push_back(O.getNode());
8065     } else
8066       LoadRoots.insert(ChainNext);
8067   }
8068
8069   // Second, search down the chain, starting from the top-level nodes recorded
8070   // in the first phase. These top-level nodes are the nodes just above all
8071   // loads and token factors. Starting with their uses, recursively look though
8072   // all loads (just the chain uses) and token factors to find a consecutive
8073   // load.
8074   Visited.clear();
8075   Queue.clear();
8076
8077   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8078        IE = LoadRoots.end(); I != IE; ++I) {
8079     Queue.push_back(*I);
8080        
8081     while (!Queue.empty()) {
8082       SDNode *LoadRoot = Queue.pop_back_val();
8083       if (!Visited.insert(LoadRoot).second)
8084         continue;
8085
8086       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
8087         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8088           return true;
8089
8090       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
8091            UE = LoadRoot->use_end(); UI != UE; ++UI)
8092         if (((isa<MemSDNode>(*UI) &&
8093             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
8094             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
8095           Queue.push_back(*UI);
8096     }
8097   }
8098
8099   return false;
8100 }
8101
8102 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
8103                                                   DAGCombinerInfo &DCI) const {
8104   SelectionDAG &DAG = DCI.DAG;
8105   SDLoc dl(N);
8106
8107   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
8108   // If we're tracking CR bits, we need to be careful that we don't have:
8109   //   trunc(binary-ops(zext(x), zext(y)))
8110   // or
8111   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
8112   // such that we're unnecessarily moving things into GPRs when it would be
8113   // better to keep them in CR bits.
8114
8115   // Note that trunc here can be an actual i1 trunc, or can be the effective
8116   // truncation that comes from a setcc or select_cc.
8117   if (N->getOpcode() == ISD::TRUNCATE &&
8118       N->getValueType(0) != MVT::i1)
8119     return SDValue();
8120
8121   if (N->getOperand(0).getValueType() != MVT::i32 &&
8122       N->getOperand(0).getValueType() != MVT::i64)
8123     return SDValue();
8124
8125   if (N->getOpcode() == ISD::SETCC ||
8126       N->getOpcode() == ISD::SELECT_CC) {
8127     // If we're looking at a comparison, then we need to make sure that the
8128     // high bits (all except for the first) don't matter the result.
8129     ISD::CondCode CC =
8130       cast<CondCodeSDNode>(N->getOperand(
8131         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8132     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8133
8134     if (ISD::isSignedIntSetCC(CC)) {
8135       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
8136           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
8137         return SDValue();
8138     } else if (ISD::isUnsignedIntSetCC(CC)) {
8139       if (!DAG.MaskedValueIsZero(N->getOperand(0),
8140                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
8141           !DAG.MaskedValueIsZero(N->getOperand(1),
8142                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
8143         return SDValue();
8144     } else {
8145       // This is neither a signed nor an unsigned comparison, just make sure
8146       // that the high bits are equal.
8147       APInt Op1Zero, Op1One;
8148       APInt Op2Zero, Op2One;
8149       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8150       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8151
8152       // We don't really care about what is known about the first bit (if
8153       // anything), so clear it in all masks prior to comparing them.
8154       Op1Zero.clearBit(0); Op1One.clearBit(0);
8155       Op2Zero.clearBit(0); Op2One.clearBit(0);
8156
8157       if (Op1Zero != Op2Zero || Op1One != Op2One)
8158         return SDValue();
8159     }
8160   }
8161
8162   // We now know that the higher-order bits are irrelevant, we just need to
8163   // make sure that all of the intermediate operations are bit operations, and
8164   // all inputs are extensions.
8165   if (N->getOperand(0).getOpcode() != ISD::AND &&
8166       N->getOperand(0).getOpcode() != ISD::OR  &&
8167       N->getOperand(0).getOpcode() != ISD::XOR &&
8168       N->getOperand(0).getOpcode() != ISD::SELECT &&
8169       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8170       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8171       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8172       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8173       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8174     return SDValue();
8175
8176   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8177       N->getOperand(1).getOpcode() != ISD::AND &&
8178       N->getOperand(1).getOpcode() != ISD::OR  &&
8179       N->getOperand(1).getOpcode() != ISD::XOR &&
8180       N->getOperand(1).getOpcode() != ISD::SELECT &&
8181       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8182       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8183       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8184       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8185       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8186     return SDValue();
8187
8188   SmallVector<SDValue, 4> Inputs;
8189   SmallVector<SDValue, 8> BinOps, PromOps;
8190   SmallPtrSet<SDNode *, 16> Visited;
8191
8192   for (unsigned i = 0; i < 2; ++i) {
8193     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8194           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8195           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8196           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8197         isa<ConstantSDNode>(N->getOperand(i)))
8198       Inputs.push_back(N->getOperand(i));
8199     else
8200       BinOps.push_back(N->getOperand(i));
8201
8202     if (N->getOpcode() == ISD::TRUNCATE)
8203       break;
8204   }
8205
8206   // Visit all inputs, collect all binary operations (and, or, xor and
8207   // select) that are all fed by extensions. 
8208   while (!BinOps.empty()) {
8209     SDValue BinOp = BinOps.back();
8210     BinOps.pop_back();
8211
8212     if (!Visited.insert(BinOp.getNode()).second)
8213       continue;
8214
8215     PromOps.push_back(BinOp);
8216
8217     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8218       // The condition of the select is not promoted.
8219       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8220         continue;
8221       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8222         continue;
8223
8224       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8225             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8226             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8227            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8228           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8229         Inputs.push_back(BinOp.getOperand(i)); 
8230       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8231                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8232                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8233                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8234                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8235                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8236                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8237                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8238                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8239         BinOps.push_back(BinOp.getOperand(i));
8240       } else {
8241         // We have an input that is not an extension or another binary
8242         // operation; we'll abort this transformation.
8243         return SDValue();
8244       }
8245     }
8246   }
8247
8248   // Make sure that this is a self-contained cluster of operations (which
8249   // is not quite the same thing as saying that everything has only one
8250   // use).
8251   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8252     if (isa<ConstantSDNode>(Inputs[i]))
8253       continue;
8254
8255     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8256                               UE = Inputs[i].getNode()->use_end();
8257          UI != UE; ++UI) {
8258       SDNode *User = *UI;
8259       if (User != N && !Visited.count(User))
8260         return SDValue();
8261
8262       // Make sure that we're not going to promote the non-output-value
8263       // operand(s) or SELECT or SELECT_CC.
8264       // FIXME: Although we could sometimes handle this, and it does occur in
8265       // practice that one of the condition inputs to the select is also one of
8266       // the outputs, we currently can't deal with this.
8267       if (User->getOpcode() == ISD::SELECT) {
8268         if (User->getOperand(0) == Inputs[i])
8269           return SDValue();
8270       } else if (User->getOpcode() == ISD::SELECT_CC) {
8271         if (User->getOperand(0) == Inputs[i] ||
8272             User->getOperand(1) == Inputs[i])
8273           return SDValue();
8274       }
8275     }
8276   }
8277
8278   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8279     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8280                               UE = PromOps[i].getNode()->use_end();
8281          UI != UE; ++UI) {
8282       SDNode *User = *UI;
8283       if (User != N && !Visited.count(User))
8284         return SDValue();
8285
8286       // Make sure that we're not going to promote the non-output-value
8287       // operand(s) or SELECT or SELECT_CC.
8288       // FIXME: Although we could sometimes handle this, and it does occur in
8289       // practice that one of the condition inputs to the select is also one of
8290       // the outputs, we currently can't deal with this.
8291       if (User->getOpcode() == ISD::SELECT) {
8292         if (User->getOperand(0) == PromOps[i])
8293           return SDValue();
8294       } else if (User->getOpcode() == ISD::SELECT_CC) {
8295         if (User->getOperand(0) == PromOps[i] ||
8296             User->getOperand(1) == PromOps[i])
8297           return SDValue();
8298       }
8299     }
8300   }
8301
8302   // Replace all inputs with the extension operand.
8303   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8304     // Constants may have users outside the cluster of to-be-promoted nodes,
8305     // and so we need to replace those as we do the promotions.
8306     if (isa<ConstantSDNode>(Inputs[i]))
8307       continue;
8308     else
8309       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
8310   }
8311
8312   // Replace all operations (these are all the same, but have a different
8313   // (i1) return type). DAG.getNode will validate that the types of
8314   // a binary operator match, so go through the list in reverse so that
8315   // we've likely promoted both operands first. Any intermediate truncations or
8316   // extensions disappear.
8317   while (!PromOps.empty()) {
8318     SDValue PromOp = PromOps.back();
8319     PromOps.pop_back();
8320
8321     if (PromOp.getOpcode() == ISD::TRUNCATE ||
8322         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8323         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8324         PromOp.getOpcode() == ISD::ANY_EXTEND) {
8325       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8326           PromOp.getOperand(0).getValueType() != MVT::i1) {
8327         // The operand is not yet ready (see comment below).
8328         PromOps.insert(PromOps.begin(), PromOp);
8329         continue;
8330       }
8331
8332       SDValue RepValue = PromOp.getOperand(0);
8333       if (isa<ConstantSDNode>(RepValue))
8334         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8335
8336       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8337       continue;
8338     }
8339
8340     unsigned C;
8341     switch (PromOp.getOpcode()) {
8342     default:             C = 0; break;
8343     case ISD::SELECT:    C = 1; break;
8344     case ISD::SELECT_CC: C = 2; break;
8345     }
8346
8347     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8348          PromOp.getOperand(C).getValueType() != MVT::i1) ||
8349         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8350          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8351       // The to-be-promoted operands of this node have not yet been
8352       // promoted (this should be rare because we're going through the
8353       // list backward, but if one of the operands has several users in
8354       // this cluster of to-be-promoted nodes, it is possible).
8355       PromOps.insert(PromOps.begin(), PromOp);
8356       continue;
8357     }
8358
8359     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8360                                 PromOp.getNode()->op_end());
8361
8362     // If there are any constant inputs, make sure they're replaced now.
8363     for (unsigned i = 0; i < 2; ++i)
8364       if (isa<ConstantSDNode>(Ops[C+i]))
8365         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8366
8367     DAG.ReplaceAllUsesOfValueWith(PromOp,
8368       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8369   }
8370
8371   // Now we're left with the initial truncation itself.
8372   if (N->getOpcode() == ISD::TRUNCATE)
8373     return N->getOperand(0);
8374
8375   // Otherwise, this is a comparison. The operands to be compared have just
8376   // changed type (to i1), but everything else is the same.
8377   return SDValue(N, 0);
8378 }
8379
8380 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8381                                                   DAGCombinerInfo &DCI) const {
8382   SelectionDAG &DAG = DCI.DAG;
8383   SDLoc dl(N);
8384
8385   // If we're tracking CR bits, we need to be careful that we don't have:
8386   //   zext(binary-ops(trunc(x), trunc(y)))
8387   // or
8388   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8389   // such that we're unnecessarily moving things into CR bits that can more
8390   // efficiently stay in GPRs. Note that if we're not certain that the high
8391   // bits are set as required by the final extension, we still may need to do
8392   // some masking to get the proper behavior.
8393
8394   // This same functionality is important on PPC64 when dealing with
8395   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8396   // the return values of functions. Because it is so similar, it is handled
8397   // here as well.
8398
8399   if (N->getValueType(0) != MVT::i32 &&
8400       N->getValueType(0) != MVT::i64)
8401     return SDValue();
8402
8403   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
8404         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
8405     return SDValue();
8406
8407   if (N->getOperand(0).getOpcode() != ISD::AND &&
8408       N->getOperand(0).getOpcode() != ISD::OR  &&
8409       N->getOperand(0).getOpcode() != ISD::XOR &&
8410       N->getOperand(0).getOpcode() != ISD::SELECT &&
8411       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8412     return SDValue();
8413
8414   SmallVector<SDValue, 4> Inputs;
8415   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8416   SmallPtrSet<SDNode *, 16> Visited;
8417
8418   // Visit all inputs, collect all binary operations (and, or, xor and
8419   // select) that are all fed by truncations. 
8420   while (!BinOps.empty()) {
8421     SDValue BinOp = BinOps.back();
8422     BinOps.pop_back();
8423
8424     if (!Visited.insert(BinOp.getNode()).second)
8425       continue;
8426
8427     PromOps.push_back(BinOp);
8428
8429     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8430       // The condition of the select is not promoted.
8431       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8432         continue;
8433       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8434         continue;
8435
8436       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8437           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8438         Inputs.push_back(BinOp.getOperand(i)); 
8439       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8440                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8441                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8442                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8443                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8444         BinOps.push_back(BinOp.getOperand(i));
8445       } else {
8446         // We have an input that is not a truncation or another binary
8447         // operation; we'll abort this transformation.
8448         return SDValue();
8449       }
8450     }
8451   }
8452
8453   // The operands of a select that must be truncated when the select is
8454   // promoted because the operand is actually part of the to-be-promoted set.
8455   DenseMap<SDNode *, EVT> SelectTruncOp[2];
8456
8457   // Make sure that this is a self-contained cluster of operations (which
8458   // is not quite the same thing as saying that everything has only one
8459   // use).
8460   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8461     if (isa<ConstantSDNode>(Inputs[i]))
8462       continue;
8463
8464     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8465                               UE = Inputs[i].getNode()->use_end();
8466          UI != UE; ++UI) {
8467       SDNode *User = *UI;
8468       if (User != N && !Visited.count(User))
8469         return SDValue();
8470
8471       // If we're going to promote the non-output-value operand(s) or SELECT or
8472       // SELECT_CC, record them for truncation.
8473       if (User->getOpcode() == ISD::SELECT) {
8474         if (User->getOperand(0) == Inputs[i])
8475           SelectTruncOp[0].insert(std::make_pair(User,
8476                                     User->getOperand(0).getValueType()));
8477       } else if (User->getOpcode() == ISD::SELECT_CC) {
8478         if (User->getOperand(0) == Inputs[i])
8479           SelectTruncOp[0].insert(std::make_pair(User,
8480                                     User->getOperand(0).getValueType()));
8481         if (User->getOperand(1) == Inputs[i])
8482           SelectTruncOp[1].insert(std::make_pair(User,
8483                                     User->getOperand(1).getValueType()));
8484       }
8485     }
8486   }
8487
8488   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8489     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8490                               UE = PromOps[i].getNode()->use_end();
8491          UI != UE; ++UI) {
8492       SDNode *User = *UI;
8493       if (User != N && !Visited.count(User))
8494         return SDValue();
8495
8496       // If we're going to promote the non-output-value operand(s) or SELECT or
8497       // SELECT_CC, record them for truncation.
8498       if (User->getOpcode() == ISD::SELECT) {
8499         if (User->getOperand(0) == PromOps[i])
8500           SelectTruncOp[0].insert(std::make_pair(User,
8501                                     User->getOperand(0).getValueType()));
8502       } else if (User->getOpcode() == ISD::SELECT_CC) {
8503         if (User->getOperand(0) == PromOps[i])
8504           SelectTruncOp[0].insert(std::make_pair(User,
8505                                     User->getOperand(0).getValueType()));
8506         if (User->getOperand(1) == PromOps[i])
8507           SelectTruncOp[1].insert(std::make_pair(User,
8508                                     User->getOperand(1).getValueType()));
8509       }
8510     }
8511   }
8512
8513   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8514   bool ReallyNeedsExt = false;
8515   if (N->getOpcode() != ISD::ANY_EXTEND) {
8516     // If all of the inputs are not already sign/zero extended, then
8517     // we'll still need to do that at the end.
8518     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8519       if (isa<ConstantSDNode>(Inputs[i]))
8520         continue;
8521
8522       unsigned OpBits =
8523         Inputs[i].getOperand(0).getValueSizeInBits();
8524       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8525
8526       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8527            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8528                                   APInt::getHighBitsSet(OpBits,
8529                                                         OpBits-PromBits))) ||
8530           (N->getOpcode() == ISD::SIGN_EXTEND &&
8531            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8532              (OpBits-(PromBits-1)))) {
8533         ReallyNeedsExt = true;
8534         break;
8535       }
8536     }
8537   }
8538
8539   // Replace all inputs, either with the truncation operand, or a
8540   // truncation or extension to the final output type.
8541   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8542     // Constant inputs need to be replaced with the to-be-promoted nodes that
8543     // use them because they might have users outside of the cluster of
8544     // promoted nodes.
8545     if (isa<ConstantSDNode>(Inputs[i]))
8546       continue;
8547
8548     SDValue InSrc = Inputs[i].getOperand(0);
8549     if (Inputs[i].getValueType() == N->getValueType(0))
8550       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8551     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8552       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8553         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8554     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8555       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8556         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8557     else
8558       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8559         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8560   }
8561
8562   // Replace all operations (these are all the same, but have a different
8563   // (promoted) return type). DAG.getNode will validate that the types of
8564   // a binary operator match, so go through the list in reverse so that
8565   // we've likely promoted both operands first.
8566   while (!PromOps.empty()) {
8567     SDValue PromOp = PromOps.back();
8568     PromOps.pop_back();
8569
8570     unsigned C;
8571     switch (PromOp.getOpcode()) {
8572     default:             C = 0; break;
8573     case ISD::SELECT:    C = 1; break;
8574     case ISD::SELECT_CC: C = 2; break;
8575     }
8576
8577     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8578          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8579         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8580          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8581       // The to-be-promoted operands of this node have not yet been
8582       // promoted (this should be rare because we're going through the
8583       // list backward, but if one of the operands has several users in
8584       // this cluster of to-be-promoted nodes, it is possible).
8585       PromOps.insert(PromOps.begin(), PromOp);
8586       continue;
8587     }
8588
8589     // For SELECT and SELECT_CC nodes, we do a similar check for any
8590     // to-be-promoted comparison inputs.
8591     if (PromOp.getOpcode() == ISD::SELECT ||
8592         PromOp.getOpcode() == ISD::SELECT_CC) {
8593       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8594            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8595           (SelectTruncOp[1].count(PromOp.getNode()) &&
8596            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8597         PromOps.insert(PromOps.begin(), PromOp);
8598         continue;
8599       }
8600     }
8601
8602     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8603                                 PromOp.getNode()->op_end());
8604
8605     // If this node has constant inputs, then they'll need to be promoted here.
8606     for (unsigned i = 0; i < 2; ++i) {
8607       if (!isa<ConstantSDNode>(Ops[C+i]))
8608         continue;
8609       if (Ops[C+i].getValueType() == N->getValueType(0))
8610         continue;
8611
8612       if (N->getOpcode() == ISD::SIGN_EXTEND)
8613         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8614       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8615         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8616       else
8617         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8618     }
8619
8620     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8621     // truncate them again to the original value type.
8622     if (PromOp.getOpcode() == ISD::SELECT ||
8623         PromOp.getOpcode() == ISD::SELECT_CC) {
8624       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8625       if (SI0 != SelectTruncOp[0].end())
8626         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8627       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8628       if (SI1 != SelectTruncOp[1].end())
8629         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8630     }
8631
8632     DAG.ReplaceAllUsesOfValueWith(PromOp,
8633       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8634   }
8635
8636   // Now we're left with the initial extension itself.
8637   if (!ReallyNeedsExt)
8638     return N->getOperand(0);
8639
8640   // To zero extend, just mask off everything except for the first bit (in the
8641   // i1 case).
8642   if (N->getOpcode() == ISD::ZERO_EXTEND)
8643     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8644                        DAG.getConstant(APInt::getLowBitsSet(
8645                                          N->getValueSizeInBits(0), PromBits),
8646                                        N->getValueType(0)));
8647
8648   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8649          "Invalid extension type");
8650   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8651   SDValue ShiftCst =
8652     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8653   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8654                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8655                                  N->getOperand(0), ShiftCst), ShiftCst);
8656 }
8657
8658 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8659                                               DAGCombinerInfo &DCI) const {
8660   assert((N->getOpcode() == ISD::SINT_TO_FP ||
8661           N->getOpcode() == ISD::UINT_TO_FP) &&
8662          "Need an int -> FP conversion node here");
8663
8664   if (!Subtarget.has64BitSupport())
8665     return SDValue();
8666
8667   SelectionDAG &DAG = DCI.DAG;
8668   SDLoc dl(N);
8669   SDValue Op(N, 0);
8670
8671   // Don't handle ppc_fp128 here or i1 conversions.
8672   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8673     return SDValue();
8674   if (Op.getOperand(0).getValueType() == MVT::i1)
8675     return SDValue();
8676
8677   // For i32 intermediate values, unfortunately, the conversion functions
8678   // leave the upper 32 bits of the value are undefined. Within the set of
8679   // scalar instructions, we have no method for zero- or sign-extending the
8680   // value. Thus, we cannot handle i32 intermediate values here.
8681   if (Op.getOperand(0).getValueType() == MVT::i32)
8682     return SDValue();
8683
8684   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8685          "UINT_TO_FP is supported only with FPCVT");
8686
8687   // If we have FCFIDS, then use it when converting to single-precision.
8688   // Otherwise, convert to double-precision and then round.
8689   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8690                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8691                                                             : PPCISD::FCFIDS)
8692                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8693                                                             : PPCISD::FCFID);
8694   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8695                   ? MVT::f32
8696                   : MVT::f64;
8697
8698   // If we're converting from a float, to an int, and back to a float again,
8699   // then we don't need the store/load pair at all.
8700   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8701        Subtarget.hasFPCVT()) ||
8702       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8703     SDValue Src = Op.getOperand(0).getOperand(0);
8704     if (Src.getValueType() == MVT::f32) {
8705       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8706       DCI.AddToWorklist(Src.getNode());
8707     }
8708
8709     unsigned FCTOp =
8710       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8711                                                         PPCISD::FCTIDUZ;
8712
8713     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8714     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8715
8716     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8717       FP = DAG.getNode(ISD::FP_ROUND, dl,
8718                        MVT::f32, FP, DAG.getIntPtrConstant(0));
8719       DCI.AddToWorklist(FP.getNode());
8720     }
8721
8722     return FP;
8723   }
8724
8725   return SDValue();
8726 }
8727
8728 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8729 // builtins) into loads with swaps.
8730 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8731                                               DAGCombinerInfo &DCI) const {
8732   SelectionDAG &DAG = DCI.DAG;
8733   SDLoc dl(N);
8734   SDValue Chain;
8735   SDValue Base;
8736   MachineMemOperand *MMO;
8737
8738   switch (N->getOpcode()) {
8739   default:
8740     llvm_unreachable("Unexpected opcode for little endian VSX load");
8741   case ISD::LOAD: {
8742     LoadSDNode *LD = cast<LoadSDNode>(N);
8743     Chain = LD->getChain();
8744     Base = LD->getBasePtr();
8745     MMO = LD->getMemOperand();
8746     // If the MMO suggests this isn't a load of a full vector, leave
8747     // things alone.  For a built-in, we have to make the change for
8748     // correctness, so if there is a size problem that will be a bug.
8749     if (MMO->getSize() < 16)
8750       return SDValue();
8751     break;
8752   }
8753   case ISD::INTRINSIC_W_CHAIN: {
8754     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8755     Chain = Intrin->getChain();
8756     Base = Intrin->getBasePtr();
8757     MMO = Intrin->getMemOperand();
8758     break;
8759   }
8760   }
8761
8762   MVT VecTy = N->getValueType(0).getSimpleVT();
8763   SDValue LoadOps[] = { Chain, Base };
8764   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8765                                          DAG.getVTList(VecTy, MVT::Other),
8766                                          LoadOps, VecTy, MMO);
8767   DCI.AddToWorklist(Load.getNode());
8768   Chain = Load.getValue(1);
8769   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8770                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8771   DCI.AddToWorklist(Swap.getNode());
8772   return Swap;
8773 }
8774
8775 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8776 // builtins) into stores with swaps.
8777 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8778                                                DAGCombinerInfo &DCI) const {
8779   SelectionDAG &DAG = DCI.DAG;
8780   SDLoc dl(N);
8781   SDValue Chain;
8782   SDValue Base;
8783   unsigned SrcOpnd;
8784   MachineMemOperand *MMO;
8785
8786   switch (N->getOpcode()) {
8787   default:
8788     llvm_unreachable("Unexpected opcode for little endian VSX store");
8789   case ISD::STORE: {
8790     StoreSDNode *ST = cast<StoreSDNode>(N);
8791     Chain = ST->getChain();
8792     Base = ST->getBasePtr();
8793     MMO = ST->getMemOperand();
8794     SrcOpnd = 1;
8795     // If the MMO suggests this isn't a store of a full vector, leave
8796     // things alone.  For a built-in, we have to make the change for
8797     // correctness, so if there is a size problem that will be a bug.
8798     if (MMO->getSize() < 16)
8799       return SDValue();
8800     break;
8801   }
8802   case ISD::INTRINSIC_VOID: {
8803     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8804     Chain = Intrin->getChain();
8805     // Intrin->getBasePtr() oddly does not get what we want.
8806     Base = Intrin->getOperand(3);
8807     MMO = Intrin->getMemOperand();
8808     SrcOpnd = 2;
8809     break;
8810   }
8811   }
8812
8813   SDValue Src = N->getOperand(SrcOpnd);
8814   MVT VecTy = Src.getValueType().getSimpleVT();
8815   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8816                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8817   DCI.AddToWorklist(Swap.getNode());
8818   Chain = Swap.getValue(1);
8819   SDValue StoreOps[] = { Chain, Swap, Base };
8820   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8821                                           DAG.getVTList(MVT::Other),
8822                                           StoreOps, VecTy, MMO);
8823   DCI.AddToWorklist(Store.getNode());
8824   return Store;
8825 }
8826
8827 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8828                                              DAGCombinerInfo &DCI) const {
8829   SelectionDAG &DAG = DCI.DAG;
8830   SDLoc dl(N);
8831   switch (N->getOpcode()) {
8832   default: break;
8833   case PPCISD::SHL:
8834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8835       if (C->isNullValue())   // 0 << V -> 0.
8836         return N->getOperand(0);
8837     }
8838     break;
8839   case PPCISD::SRL:
8840     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8841       if (C->isNullValue())   // 0 >>u V -> 0.
8842         return N->getOperand(0);
8843     }
8844     break;
8845   case PPCISD::SRA:
8846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8847       if (C->isNullValue() ||   //  0 >>s V -> 0.
8848           C->isAllOnesValue())    // -1 >>s V -> -1.
8849         return N->getOperand(0);
8850     }
8851     break;
8852   case ISD::SIGN_EXTEND:
8853   case ISD::ZERO_EXTEND:
8854   case ISD::ANY_EXTEND: 
8855     return DAGCombineExtBoolTrunc(N, DCI);
8856   case ISD::TRUNCATE:
8857   case ISD::SETCC:
8858   case ISD::SELECT_CC:
8859     return DAGCombineTruncBoolExt(N, DCI);
8860   case ISD::SINT_TO_FP:
8861   case ISD::UINT_TO_FP:
8862     return combineFPToIntToFP(N, DCI);
8863   case ISD::STORE: {
8864     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8865     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
8866         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8867         N->getOperand(1).getValueType() == MVT::i32 &&
8868         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8869       SDValue Val = N->getOperand(1).getOperand(0);
8870       if (Val.getValueType() == MVT::f32) {
8871         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8872         DCI.AddToWorklist(Val.getNode());
8873       }
8874       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8875       DCI.AddToWorklist(Val.getNode());
8876
8877       SDValue Ops[] = {
8878         N->getOperand(0), Val, N->getOperand(2),
8879         DAG.getValueType(N->getOperand(1).getValueType())
8880       };
8881
8882       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8883               DAG.getVTList(MVT::Other), Ops,
8884               cast<StoreSDNode>(N)->getMemoryVT(),
8885               cast<StoreSDNode>(N)->getMemOperand());
8886       DCI.AddToWorklist(Val.getNode());
8887       return Val;
8888     }
8889
8890     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8891     if (cast<StoreSDNode>(N)->isUnindexed() &&
8892         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8893         N->getOperand(1).getNode()->hasOneUse() &&
8894         (N->getOperand(1).getValueType() == MVT::i32 ||
8895          N->getOperand(1).getValueType() == MVT::i16 ||
8896          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
8897           N->getOperand(1).getValueType() == MVT::i64))) {
8898       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8899       // Do an any-extend to 32-bits if this is a half-word input.
8900       if (BSwapOp.getValueType() == MVT::i16)
8901         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8902
8903       SDValue Ops[] = {
8904         N->getOperand(0), BSwapOp, N->getOperand(2),
8905         DAG.getValueType(N->getOperand(1).getValueType())
8906       };
8907       return
8908         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8909                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8910                                 cast<StoreSDNode>(N)->getMemOperand());
8911     }
8912
8913     // For little endian, VSX stores require generating xxswapd/lxvd2x.
8914     EVT VT = N->getOperand(1).getValueType();
8915     if (VT.isSimple()) {
8916       MVT StoreVT = VT.getSimpleVT();
8917       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8918           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8919            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8920         return expandVSXStoreForLE(N, DCI);
8921     }
8922     break;
8923   }
8924   case ISD::LOAD: {
8925     LoadSDNode *LD = cast<LoadSDNode>(N);
8926     EVT VT = LD->getValueType(0);
8927
8928     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8929     if (VT.isSimple()) {
8930       MVT LoadVT = VT.getSimpleVT();
8931       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
8932           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8933            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8934         return expandVSXLoadForLE(N, DCI);
8935     }
8936
8937     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8938     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8939     if (ISD::isNON_EXTLoad(N) && VT.isVector() && Subtarget.hasAltivec() &&
8940         // P8 and later hardware should just use LOAD.
8941         !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8942                                      VT == MVT::v4i32 || VT == MVT::v4f32) &&
8943         LD->getAlignment() < ABIAlignment) {
8944       // This is a type-legal unaligned Altivec load.
8945       SDValue Chain = LD->getChain();
8946       SDValue Ptr = LD->getBasePtr();
8947       bool isLittleEndian = Subtarget.isLittleEndian();
8948
8949       // This implements the loading of unaligned vectors as described in
8950       // the venerable Apple Velocity Engine overview. Specifically:
8951       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8952       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8953       //
8954       // The general idea is to expand a sequence of one or more unaligned
8955       // loads into an alignment-based permutation-control instruction (lvsl
8956       // or lvsr), a series of regular vector loads (which always truncate
8957       // their input address to an aligned address), and a series of
8958       // permutations.  The results of these permutations are the requested
8959       // loaded values.  The trick is that the last "extra" load is not taken
8960       // from the address you might suspect (sizeof(vector) bytes after the
8961       // last requested load), but rather sizeof(vector) - 1 bytes after the
8962       // last requested vector. The point of this is to avoid a page fault if
8963       // the base address happened to be aligned. This works because if the
8964       // base address is aligned, then adding less than a full vector length
8965       // will cause the last vector in the sequence to be (re)loaded.
8966       // Otherwise, the next vector will be fetched as you might suspect was
8967       // necessary.
8968
8969       // We might be able to reuse the permutation generation from
8970       // a different base address offset from this one by an aligned amount.
8971       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8972       // optimization later.
8973       Intrinsic::ID Intr = (isLittleEndian ?
8974                             Intrinsic::ppc_altivec_lvsr :
8975                             Intrinsic::ppc_altivec_lvsl);
8976       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8977
8978       // Create the new MMO for the new base load. It is like the original MMO,
8979       // but represents an area in memory almost twice the vector size centered
8980       // on the original address. If the address is unaligned, we might start
8981       // reading up to (sizeof(vector)-1) bytes below the address of the
8982       // original unaligned load.
8983       MachineFunction &MF = DAG.getMachineFunction();
8984       MachineMemOperand *BaseMMO =
8985         MF.getMachineMemOperand(LD->getMemOperand(),
8986                                 -LD->getMemoryVT().getStoreSize()+1,
8987                                 2*LD->getMemoryVT().getStoreSize()-1);
8988
8989       // Create the new base load.
8990       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8991                                                getPointerTy());
8992       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8993       SDValue BaseLoad =
8994         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8995                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8996                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8997
8998       // Note that the value of IncOffset (which is provided to the next
8999       // load's pointer info offset value, and thus used to calculate the
9000       // alignment), and the value of IncValue (which is actually used to
9001       // increment the pointer value) are different! This is because we
9002       // require the next load to appear to be aligned, even though it
9003       // is actually offset from the base pointer by a lesser amount.
9004       int IncOffset = VT.getSizeInBits() / 8;
9005       int IncValue = IncOffset;
9006
9007       // Walk (both up and down) the chain looking for another load at the real
9008       // (aligned) offset (the alignment of the other load does not matter in
9009       // this case). If found, then do not use the offset reduction trick, as
9010       // that will prevent the loads from being later combined (as they would
9011       // otherwise be duplicates).
9012       if (!findConsecutiveLoad(LD, DAG))
9013         --IncValue;
9014
9015       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9016       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9017
9018       MachineMemOperand *ExtraMMO =
9019         MF.getMachineMemOperand(LD->getMemOperand(),
9020                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
9021       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9022       SDValue ExtraLoad =
9023         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9024                                 DAG.getVTList(MVT::v4i32, MVT::Other),
9025                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
9026
9027       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9028         BaseLoad.getValue(1), ExtraLoad.getValue(1));
9029
9030       // Because vperm has a big-endian bias, we must reverse the order
9031       // of the input vectors and complement the permute control vector
9032       // when generating little endian code.  We have already handled the
9033       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9034       // and ExtraLoad here.
9035       SDValue Perm;
9036       if (isLittleEndian)
9037         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9038                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9039       else
9040         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
9041                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9042
9043       if (VT != MVT::v4i32)
9044         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
9045
9046       // The output of the permutation is our loaded result, the TokenFactor is
9047       // our new chain.
9048       DCI.CombineTo(N, Perm, TF);
9049       return SDValue(N, 0);
9050     }
9051     }
9052     break;
9053     case ISD::INTRINSIC_WO_CHAIN: {
9054       bool isLittleEndian = Subtarget.isLittleEndian();
9055       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
9056                                            : Intrinsic::ppc_altivec_lvsl);
9057       if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
9058           N->getOperand(1)->getOpcode() == ISD::ADD) {
9059         SDValue Add = N->getOperand(1);
9060
9061         if (DAG.MaskedValueIsZero(
9062                 Add->getOperand(1),
9063                 APInt::getAllOnesValue(4 /* 16 byte alignment */)
9064                     .zext(
9065                         Add.getValueType().getScalarType().getSizeInBits()))) {
9066           SDNode *BasePtr = Add->getOperand(0).getNode();
9067           for (SDNode::use_iterator UI = BasePtr->use_begin(),
9068                                     UE = BasePtr->use_end();
9069                UI != UE; ++UI) {
9070             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9071                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
9072                     Intr) {
9073               // We've found another LVSL/LVSR, and this address is an aligned
9074               // multiple of that one. The results will be the same, so use the
9075               // one we've just found instead.
9076
9077               return SDValue(*UI, 0);
9078             }
9079           }
9080         }
9081       }
9082     }
9083
9084     break;
9085   case ISD::INTRINSIC_W_CHAIN: {
9086     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9087     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9088       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9089       default:
9090         break;
9091       case Intrinsic::ppc_vsx_lxvw4x:
9092       case Intrinsic::ppc_vsx_lxvd2x:
9093         return expandVSXLoadForLE(N, DCI);
9094       }
9095     }
9096     break;
9097   }
9098   case ISD::INTRINSIC_VOID: {
9099     // For little endian, VSX stores require generating xxswapd/stxvd2x.
9100     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
9101       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9102       default:
9103         break;
9104       case Intrinsic::ppc_vsx_stxvw4x:
9105       case Intrinsic::ppc_vsx_stxvd2x:
9106         return expandVSXStoreForLE(N, DCI);
9107       }
9108     }
9109     break;
9110   }
9111   case ISD::BSWAP:
9112     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
9113     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
9114         N->getOperand(0).hasOneUse() &&
9115         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
9116          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9117           N->getValueType(0) == MVT::i64))) {
9118       SDValue Load = N->getOperand(0);
9119       LoadSDNode *LD = cast<LoadSDNode>(Load);
9120       // Create the byte-swapping load.
9121       SDValue Ops[] = {
9122         LD->getChain(),    // Chain
9123         LD->getBasePtr(),  // Ptr
9124         DAG.getValueType(N->getValueType(0)) // VT
9125       };
9126       SDValue BSLoad =
9127         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
9128                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
9129                                               MVT::i64 : MVT::i32, MVT::Other),
9130                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9131
9132       // If this is an i16 load, insert the truncate.
9133       SDValue ResVal = BSLoad;
9134       if (N->getValueType(0) == MVT::i16)
9135         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
9136
9137       // First, combine the bswap away.  This makes the value produced by the
9138       // load dead.
9139       DCI.CombineTo(N, ResVal);
9140
9141       // Next, combine the load away, we give it a bogus result value but a real
9142       // chain result.  The result value is dead because the bswap is dead.
9143       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9144
9145       // Return N so it doesn't get rechecked!
9146       return SDValue(N, 0);
9147     }
9148
9149     break;
9150   case PPCISD::VCMP: {
9151     // If a VCMPo node already exists with exactly the same operands as this
9152     // node, use its result instead of this node (VCMPo computes both a CR6 and
9153     // a normal output).
9154     //
9155     if (!N->getOperand(0).hasOneUse() &&
9156         !N->getOperand(1).hasOneUse() &&
9157         !N->getOperand(2).hasOneUse()) {
9158
9159       // Scan all of the users of the LHS, looking for VCMPo's that match.
9160       SDNode *VCMPoNode = nullptr;
9161
9162       SDNode *LHSN = N->getOperand(0).getNode();
9163       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9164            UI != E; ++UI)
9165         if (UI->getOpcode() == PPCISD::VCMPo &&
9166             UI->getOperand(1) == N->getOperand(1) &&
9167             UI->getOperand(2) == N->getOperand(2) &&
9168             UI->getOperand(0) == N->getOperand(0)) {
9169           VCMPoNode = *UI;
9170           break;
9171         }
9172
9173       // If there is no VCMPo node, or if the flag value has a single use, don't
9174       // transform this.
9175       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9176         break;
9177
9178       // Look at the (necessarily single) use of the flag value.  If it has a
9179       // chain, this transformation is more complex.  Note that multiple things
9180       // could use the value result, which we should ignore.
9181       SDNode *FlagUser = nullptr;
9182       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9183            FlagUser == nullptr; ++UI) {
9184         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9185         SDNode *User = *UI;
9186         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9187           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9188             FlagUser = User;
9189             break;
9190           }
9191         }
9192       }
9193
9194       // If the user is a MFOCRF instruction, we know this is safe.
9195       // Otherwise we give up for right now.
9196       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9197         return SDValue(VCMPoNode, 0);
9198     }
9199     break;
9200   }
9201   case ISD::BRCOND: {
9202     SDValue Cond = N->getOperand(1);
9203     SDValue Target = N->getOperand(2);
9204  
9205     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9206         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9207           Intrinsic::ppc_is_decremented_ctr_nonzero) {
9208
9209       // We now need to make the intrinsic dead (it cannot be instruction
9210       // selected).
9211       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9212       assert(Cond.getNode()->hasOneUse() &&
9213              "Counter decrement has more than one use");
9214
9215       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9216                          N->getOperand(0), Target);
9217     }
9218   }
9219   break;
9220   case ISD::BR_CC: {
9221     // If this is a branch on an altivec predicate comparison, lower this so
9222     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
9223     // lowering is done pre-legalize, because the legalizer lowers the predicate
9224     // compare down to code that is difficult to reassemble.
9225     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9226     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9227
9228     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9229     // value. If so, pass-through the AND to get to the intrinsic.
9230     if (LHS.getOpcode() == ISD::AND &&
9231         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9232         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9233           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9234         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9235         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9236           isZero())
9237       LHS = LHS.getOperand(0);
9238
9239     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9240         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9241           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9242         isa<ConstantSDNode>(RHS)) {
9243       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9244              "Counter decrement comparison is not EQ or NE");
9245
9246       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9247       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9248                     (CC == ISD::SETNE && !Val);
9249
9250       // We now need to make the intrinsic dead (it cannot be instruction
9251       // selected).
9252       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9253       assert(LHS.getNode()->hasOneUse() &&
9254              "Counter decrement has more than one use");
9255
9256       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9257                          N->getOperand(0), N->getOperand(4));
9258     }
9259
9260     int CompareOpc;
9261     bool isDot;
9262
9263     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9264         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9265         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9266       assert(isDot && "Can't compare against a vector result!");
9267
9268       // If this is a comparison against something other than 0/1, then we know
9269       // that the condition is never/always true.
9270       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9271       if (Val != 0 && Val != 1) {
9272         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
9273           return N->getOperand(0);
9274         // Always !=, turn it into an unconditional branch.
9275         return DAG.getNode(ISD::BR, dl, MVT::Other,
9276                            N->getOperand(0), N->getOperand(4));
9277       }
9278
9279       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9280
9281       // Create the PPCISD altivec 'dot' comparison node.
9282       SDValue Ops[] = {
9283         LHS.getOperand(2),  // LHS of compare
9284         LHS.getOperand(3),  // RHS of compare
9285         DAG.getConstant(CompareOpc, MVT::i32)
9286       };
9287       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9288       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9289
9290       // Unpack the result based on how the target uses it.
9291       PPC::Predicate CompOpc;
9292       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9293       default:  // Can't happen, don't crash on invalid number though.
9294       case 0:   // Branch on the value of the EQ bit of CR6.
9295         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9296         break;
9297       case 1:   // Branch on the inverted value of the EQ bit of CR6.
9298         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9299         break;
9300       case 2:   // Branch on the value of the LT bit of CR6.
9301         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9302         break;
9303       case 3:   // Branch on the inverted value of the LT bit of CR6.
9304         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9305         break;
9306       }
9307
9308       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9309                          DAG.getConstant(CompOpc, MVT::i32),
9310                          DAG.getRegister(PPC::CR6, MVT::i32),
9311                          N->getOperand(4), CompNode.getValue(1));
9312     }
9313     break;
9314   }
9315   }
9316
9317   return SDValue();
9318 }
9319
9320 SDValue
9321 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9322                                   SelectionDAG &DAG,
9323                                   std::vector<SDNode *> *Created) const {
9324   // fold (sdiv X, pow2)
9325   EVT VT = N->getValueType(0);
9326   if (VT == MVT::i64 && !Subtarget.isPPC64())
9327     return SDValue();
9328   if ((VT != MVT::i32 && VT != MVT::i64) ||
9329       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9330     return SDValue();
9331
9332   SDLoc DL(N);
9333   SDValue N0 = N->getOperand(0);
9334
9335   bool IsNegPow2 = (-Divisor).isPowerOf2();
9336   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9337   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9338
9339   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9340   if (Created)
9341     Created->push_back(Op.getNode());
9342
9343   if (IsNegPow2) {
9344     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9345     if (Created)
9346       Created->push_back(Op.getNode());
9347   }
9348
9349   return Op;
9350 }
9351
9352 //===----------------------------------------------------------------------===//
9353 // Inline Assembly Support
9354 //===----------------------------------------------------------------------===//
9355
9356 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9357                                                       APInt &KnownZero,
9358                                                       APInt &KnownOne,
9359                                                       const SelectionDAG &DAG,
9360                                                       unsigned Depth) const {
9361   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9362   switch (Op.getOpcode()) {
9363   default: break;
9364   case PPCISD::LBRX: {
9365     // lhbrx is known to have the top bits cleared out.
9366     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9367       KnownZero = 0xFFFF0000;
9368     break;
9369   }
9370   case ISD::INTRINSIC_WO_CHAIN: {
9371     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9372     default: break;
9373     case Intrinsic::ppc_altivec_vcmpbfp_p:
9374     case Intrinsic::ppc_altivec_vcmpeqfp_p:
9375     case Intrinsic::ppc_altivec_vcmpequb_p:
9376     case Intrinsic::ppc_altivec_vcmpequh_p:
9377     case Intrinsic::ppc_altivec_vcmpequw_p:
9378     case Intrinsic::ppc_altivec_vcmpgefp_p:
9379     case Intrinsic::ppc_altivec_vcmpgtfp_p:
9380     case Intrinsic::ppc_altivec_vcmpgtsb_p:
9381     case Intrinsic::ppc_altivec_vcmpgtsh_p:
9382     case Intrinsic::ppc_altivec_vcmpgtsw_p:
9383     case Intrinsic::ppc_altivec_vcmpgtub_p:
9384     case Intrinsic::ppc_altivec_vcmpgtuh_p:
9385     case Intrinsic::ppc_altivec_vcmpgtuw_p:
9386       KnownZero = ~1U;  // All bits but the low one are known to be zero.
9387       break;
9388     }
9389   }
9390   }
9391 }
9392
9393 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9394   switch (Subtarget.getDarwinDirective()) {
9395   default: break;
9396   case PPC::DIR_970:
9397   case PPC::DIR_PWR4:
9398   case PPC::DIR_PWR5:
9399   case PPC::DIR_PWR5X:
9400   case PPC::DIR_PWR6:
9401   case PPC::DIR_PWR6X:
9402   case PPC::DIR_PWR7:
9403   case PPC::DIR_PWR8: {
9404     if (!ML)
9405       break;
9406
9407     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
9408
9409     // For small loops (between 5 and 8 instructions), align to a 32-byte
9410     // boundary so that the entire loop fits in one instruction-cache line.
9411     uint64_t LoopSize = 0;
9412     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9413       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9414         LoopSize += TII->GetInstSizeInBytes(J);
9415
9416     if (LoopSize > 16 && LoopSize <= 32)
9417       return 5;
9418
9419     break;
9420   }
9421   }
9422
9423   return TargetLowering::getPrefLoopAlignment(ML);
9424 }
9425
9426 /// getConstraintType - Given a constraint, return the type of
9427 /// constraint it is for this target.
9428 PPCTargetLowering::ConstraintType
9429 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9430   if (Constraint.size() == 1) {
9431     switch (Constraint[0]) {
9432     default: break;
9433     case 'b':
9434     case 'r':
9435     case 'f':
9436     case 'v':
9437     case 'y':
9438       return C_RegisterClass;
9439     case 'Z':
9440       // FIXME: While Z does indicate a memory constraint, it specifically
9441       // indicates an r+r address (used in conjunction with the 'y' modifier
9442       // in the replacement string). Currently, we're forcing the base
9443       // register to be r0 in the asm printer (which is interpreted as zero)
9444       // and forming the complete address in the second register. This is
9445       // suboptimal.
9446       return C_Memory;
9447     }
9448   } else if (Constraint == "wc") { // individual CR bits.
9449     return C_RegisterClass;
9450   } else if (Constraint == "wa" || Constraint == "wd" ||
9451              Constraint == "wf" || Constraint == "ws") {
9452     return C_RegisterClass; // VSX registers.
9453   }
9454   return TargetLowering::getConstraintType(Constraint);
9455 }
9456
9457 /// Examine constraint type and operand type and determine a weight value.
9458 /// This object must already have been set up with the operand type
9459 /// and the current alternative constraint selected.
9460 TargetLowering::ConstraintWeight
9461 PPCTargetLowering::getSingleConstraintMatchWeight(
9462     AsmOperandInfo &info, const char *constraint) const {
9463   ConstraintWeight weight = CW_Invalid;
9464   Value *CallOperandVal = info.CallOperandVal;
9465     // If we don't have a value, we can't do a match,
9466     // but allow it at the lowest weight.
9467   if (!CallOperandVal)
9468     return CW_Default;
9469   Type *type = CallOperandVal->getType();
9470
9471   // Look at the constraint type.
9472   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9473     return CW_Register; // an individual CR bit.
9474   else if ((StringRef(constraint) == "wa" ||
9475             StringRef(constraint) == "wd" ||
9476             StringRef(constraint) == "wf") &&
9477            type->isVectorTy())
9478     return CW_Register;
9479   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9480     return CW_Register;
9481
9482   switch (*constraint) {
9483   default:
9484     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9485     break;
9486   case 'b':
9487     if (type->isIntegerTy())
9488       weight = CW_Register;
9489     break;
9490   case 'f':
9491     if (type->isFloatTy())
9492       weight = CW_Register;
9493     break;
9494   case 'd':
9495     if (type->isDoubleTy())
9496       weight = CW_Register;
9497     break;
9498   case 'v':
9499     if (type->isVectorTy())
9500       weight = CW_Register;
9501     break;
9502   case 'y':
9503     weight = CW_Register;
9504     break;
9505   case 'Z':
9506     weight = CW_Memory;
9507     break;
9508   }
9509   return weight;
9510 }
9511
9512 std::pair<unsigned, const TargetRegisterClass*>
9513 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9514                                                 MVT VT) const {
9515   if (Constraint.size() == 1) {
9516     // GCC RS6000 Constraint Letters
9517     switch (Constraint[0]) {
9518     case 'b':   // R1-R31
9519       if (VT == MVT::i64 && Subtarget.isPPC64())
9520         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9521       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9522     case 'r':   // R0-R31
9523       if (VT == MVT::i64 && Subtarget.isPPC64())
9524         return std::make_pair(0U, &PPC::G8RCRegClass);
9525       return std::make_pair(0U, &PPC::GPRCRegClass);
9526     case 'f':
9527       if (VT == MVT::f32 || VT == MVT::i32)
9528         return std::make_pair(0U, &PPC::F4RCRegClass);
9529       if (VT == MVT::f64 || VT == MVT::i64)
9530         return std::make_pair(0U, &PPC::F8RCRegClass);
9531       break;
9532     case 'v':
9533       return std::make_pair(0U, &PPC::VRRCRegClass);
9534     case 'y':   // crrc
9535       return std::make_pair(0U, &PPC::CRRCRegClass);
9536     }
9537   } else if (Constraint == "wc") { // an individual CR bit.
9538     return std::make_pair(0U, &PPC::CRBITRCRegClass);
9539   } else if (Constraint == "wa" || Constraint == "wd" ||
9540              Constraint == "wf") {
9541     return std::make_pair(0U, &PPC::VSRCRegClass);
9542   } else if (Constraint == "ws") {
9543     return std::make_pair(0U, &PPC::VSFRCRegClass);
9544   }
9545
9546   std::pair<unsigned, const TargetRegisterClass*> R =
9547     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9548
9549   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9550   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9551   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9552   // register.
9553   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9554   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9555   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9556       PPC::GPRCRegClass.contains(R.first)) {
9557     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9558     return std::make_pair(TRI->getMatchingSuperReg(R.first,
9559                             PPC::sub_32, &PPC::G8RCRegClass),
9560                           &PPC::G8RCRegClass);
9561   }
9562
9563   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9564   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9565     R.first = PPC::CR0;
9566     R.second = &PPC::CRRCRegClass;
9567   }
9568
9569   return R;
9570 }
9571
9572
9573 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9574 /// vector.  If it is invalid, don't add anything to Ops.
9575 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9576                                                      std::string &Constraint,
9577                                                      std::vector<SDValue>&Ops,
9578                                                      SelectionDAG &DAG) const {
9579   SDValue Result;
9580
9581   // Only support length 1 constraints.
9582   if (Constraint.length() > 1) return;
9583
9584   char Letter = Constraint[0];
9585   switch (Letter) {
9586   default: break;
9587   case 'I':
9588   case 'J':
9589   case 'K':
9590   case 'L':
9591   case 'M':
9592   case 'N':
9593   case 'O':
9594   case 'P': {
9595     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9596     if (!CST) return; // Must be an immediate to match.
9597     int64_t Value = CST->getSExtValue();
9598     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9599                          // numbers are printed as such.
9600     switch (Letter) {
9601     default: llvm_unreachable("Unknown constraint letter!");
9602     case 'I':  // "I" is a signed 16-bit constant.
9603       if (isInt<16>(Value))
9604         Result = DAG.getTargetConstant(Value, TCVT);
9605       break;
9606     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9607       if (isShiftedUInt<16, 16>(Value))
9608         Result = DAG.getTargetConstant(Value, TCVT);
9609       break;
9610     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9611       if (isShiftedInt<16, 16>(Value))
9612         Result = DAG.getTargetConstant(Value, TCVT);
9613       break;
9614     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9615       if (isUInt<16>(Value))
9616         Result = DAG.getTargetConstant(Value, TCVT);
9617       break;
9618     case 'M':  // "M" is a constant that is greater than 31.
9619       if (Value > 31)
9620         Result = DAG.getTargetConstant(Value, TCVT);
9621       break;
9622     case 'N':  // "N" is a positive constant that is an exact power of two.
9623       if (Value > 0 && isPowerOf2_64(Value))
9624         Result = DAG.getTargetConstant(Value, TCVT);
9625       break;
9626     case 'O':  // "O" is the constant zero.
9627       if (Value == 0)
9628         Result = DAG.getTargetConstant(Value, TCVT);
9629       break;
9630     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9631       if (isInt<16>(-Value))
9632         Result = DAG.getTargetConstant(Value, TCVT);
9633       break;
9634     }
9635     break;
9636   }
9637   }
9638
9639   if (Result.getNode()) {
9640     Ops.push_back(Result);
9641     return;
9642   }
9643
9644   // Handle standard constraint letters.
9645   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9646 }
9647
9648 // isLegalAddressingMode - Return true if the addressing mode represented
9649 // by AM is legal for this target, for a load/store of the specified type.
9650 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9651                                               Type *Ty) const {
9652   // FIXME: PPC does not allow r+i addressing modes for vectors!
9653
9654   // PPC allows a sign-extended 16-bit immediate field.
9655   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9656     return false;
9657
9658   // No global is ever allowed as a base.
9659   if (AM.BaseGV)
9660     return false;
9661
9662   // PPC only support r+r,
9663   switch (AM.Scale) {
9664   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9665     break;
9666   case 1:
9667     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9668       return false;
9669     // Otherwise we have r+r or r+i.
9670     break;
9671   case 2:
9672     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9673       return false;
9674     // Allow 2*r as r+r.
9675     break;
9676   default:
9677     // No other scales are supported.
9678     return false;
9679   }
9680
9681   return true;
9682 }
9683
9684 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9685                                            SelectionDAG &DAG) const {
9686   MachineFunction &MF = DAG.getMachineFunction();
9687   MachineFrameInfo *MFI = MF.getFrameInfo();
9688   MFI->setReturnAddressIsTaken(true);
9689
9690   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9691     return SDValue();
9692
9693   SDLoc dl(Op);
9694   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9695
9696   // Make sure the function does not optimize away the store of the RA to
9697   // the stack.
9698   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9699   FuncInfo->setLRStoreRequired();
9700   bool isPPC64 = Subtarget.isPPC64();
9701   bool isDarwinABI = Subtarget.isDarwinABI();
9702
9703   if (Depth > 0) {
9704     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9705     SDValue Offset =
9706
9707       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9708                       isPPC64? MVT::i64 : MVT::i32);
9709     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9710                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9711                                    FrameAddr, Offset),
9712                        MachinePointerInfo(), false, false, false, 0);
9713   }
9714
9715   // Just load the return address off the stack.
9716   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9717   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9718                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9719 }
9720
9721 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9722                                           SelectionDAG &DAG) const {
9723   SDLoc dl(Op);
9724   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9725
9726   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9727   bool isPPC64 = PtrVT == MVT::i64;
9728
9729   MachineFunction &MF = DAG.getMachineFunction();
9730   MachineFrameInfo *MFI = MF.getFrameInfo();
9731   MFI->setFrameAddressIsTaken(true);
9732
9733   // Naked functions never have a frame pointer, and so we use r1. For all
9734   // other functions, this decision must be delayed until during PEI.
9735   unsigned FrameReg;
9736   if (MF.getFunction()->getAttributes().hasAttribute(
9737         AttributeSet::FunctionIndex, Attribute::Naked))
9738     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9739   else
9740     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9741
9742   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9743                                          PtrVT);
9744   while (Depth--)
9745     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9746                             FrameAddr, MachinePointerInfo(), false, false,
9747                             false, 0);
9748   return FrameAddr;
9749 }
9750
9751 // FIXME? Maybe this could be a TableGen attribute on some registers and
9752 // this table could be generated automatically from RegInfo.
9753 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9754                                               EVT VT) const {
9755   bool isPPC64 = Subtarget.isPPC64();
9756   bool isDarwinABI = Subtarget.isDarwinABI();
9757
9758   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9759       (!isPPC64 && VT != MVT::i32))
9760     report_fatal_error("Invalid register global variable type");
9761
9762   bool is64Bit = isPPC64 && VT == MVT::i64;
9763   unsigned Reg = StringSwitch<unsigned>(RegName)
9764                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9765                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
9766                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9767                                   (is64Bit ? PPC::X13 : PPC::R13))
9768                    .Default(0);
9769
9770   if (Reg)
9771     return Reg;
9772   report_fatal_error("Invalid register name global variable");
9773 }
9774
9775 bool
9776 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9777   // The PowerPC target isn't yet aware of offsets.
9778   return false;
9779 }
9780
9781 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9782                                            const CallInst &I,
9783                                            unsigned Intrinsic) const {
9784
9785   switch (Intrinsic) {
9786   case Intrinsic::ppc_altivec_lvx:
9787   case Intrinsic::ppc_altivec_lvxl:
9788   case Intrinsic::ppc_altivec_lvebx:
9789   case Intrinsic::ppc_altivec_lvehx:
9790   case Intrinsic::ppc_altivec_lvewx:
9791   case Intrinsic::ppc_vsx_lxvd2x:
9792   case Intrinsic::ppc_vsx_lxvw4x: {
9793     EVT VT;
9794     switch (Intrinsic) {
9795     case Intrinsic::ppc_altivec_lvebx:
9796       VT = MVT::i8;
9797       break;
9798     case Intrinsic::ppc_altivec_lvehx:
9799       VT = MVT::i16;
9800       break;
9801     case Intrinsic::ppc_altivec_lvewx:
9802       VT = MVT::i32;
9803       break;
9804     case Intrinsic::ppc_vsx_lxvd2x:
9805       VT = MVT::v2f64;
9806       break;
9807     default:
9808       VT = MVT::v4i32;
9809       break;
9810     }
9811
9812     Info.opc = ISD::INTRINSIC_W_CHAIN;
9813     Info.memVT = VT;
9814     Info.ptrVal = I.getArgOperand(0);
9815     Info.offset = -VT.getStoreSize()+1;
9816     Info.size = 2*VT.getStoreSize()-1;
9817     Info.align = 1;
9818     Info.vol = false;
9819     Info.readMem = true;
9820     Info.writeMem = false;
9821     return true;
9822   }
9823   case Intrinsic::ppc_altivec_stvx:
9824   case Intrinsic::ppc_altivec_stvxl:
9825   case Intrinsic::ppc_altivec_stvebx:
9826   case Intrinsic::ppc_altivec_stvehx:
9827   case Intrinsic::ppc_altivec_stvewx:
9828   case Intrinsic::ppc_vsx_stxvd2x:
9829   case Intrinsic::ppc_vsx_stxvw4x: {
9830     EVT VT;
9831     switch (Intrinsic) {
9832     case Intrinsic::ppc_altivec_stvebx:
9833       VT = MVT::i8;
9834       break;
9835     case Intrinsic::ppc_altivec_stvehx:
9836       VT = MVT::i16;
9837       break;
9838     case Intrinsic::ppc_altivec_stvewx:
9839       VT = MVT::i32;
9840       break;
9841     case Intrinsic::ppc_vsx_stxvd2x:
9842       VT = MVT::v2f64;
9843       break;
9844     default:
9845       VT = MVT::v4i32;
9846       break;
9847     }
9848
9849     Info.opc = ISD::INTRINSIC_VOID;
9850     Info.memVT = VT;
9851     Info.ptrVal = I.getArgOperand(1);
9852     Info.offset = -VT.getStoreSize()+1;
9853     Info.size = 2*VT.getStoreSize()-1;
9854     Info.align = 1;
9855     Info.vol = false;
9856     Info.readMem = false;
9857     Info.writeMem = true;
9858     return true;
9859   }
9860   default:
9861     break;
9862   }
9863
9864   return false;
9865 }
9866
9867 /// getOptimalMemOpType - Returns the target specific optimal type for load
9868 /// and store operations as a result of memset, memcpy, and memmove
9869 /// lowering. If DstAlign is zero that means it's safe to destination
9870 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9871 /// means there isn't a need to check it against alignment requirement,
9872 /// probably because the source does not need to be loaded. If 'IsMemset' is
9873 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9874 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9875 /// source is constant so it does not need to be loaded.
9876 /// It returns EVT::Other if the type should be determined using generic
9877 /// target-independent logic.
9878 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9879                                            unsigned DstAlign, unsigned SrcAlign,
9880                                            bool IsMemset, bool ZeroMemset,
9881                                            bool MemcpyStrSrc,
9882                                            MachineFunction &MF) const {
9883   if (Subtarget.isPPC64()) {
9884     return MVT::i64;
9885   } else {
9886     return MVT::i32;
9887   }
9888 }
9889
9890 /// \brief Returns true if it is beneficial to convert a load of a constant
9891 /// to just the constant itself.
9892 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9893                                                           Type *Ty) const {
9894   assert(Ty->isIntegerTy());
9895
9896   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9897   if (BitSize == 0 || BitSize > 64)
9898     return false;
9899   return true;
9900 }
9901
9902 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9903   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9904     return false;
9905   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9906   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9907   return NumBits1 == 64 && NumBits2 == 32;
9908 }
9909
9910 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9911   if (!VT1.isInteger() || !VT2.isInteger())
9912     return false;
9913   unsigned NumBits1 = VT1.getSizeInBits();
9914   unsigned NumBits2 = VT2.getSizeInBits();
9915   return NumBits1 == 64 && NumBits2 == 32;
9916 }
9917
9918 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9919   // Generally speaking, zexts are not free, but they are free when they can be
9920   // folded with other operations.
9921   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
9922     EVT MemVT = LD->getMemoryVT();
9923     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
9924          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
9925         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
9926          LD->getExtensionType() == ISD::ZEXTLOAD))
9927       return true;
9928   }
9929
9930   // FIXME: Add other cases...
9931   //  - 32-bit shifts with a zext to i64
9932   //  - zext after ctlz, bswap, etc.
9933   //  - zext after and by a constant mask
9934
9935   return TargetLowering::isZExtFree(Val, VT2);
9936 }
9937
9938 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
9939   assert(VT.isFloatingPoint());
9940   return true;
9941 }
9942
9943 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9944   return isInt<16>(Imm) || isUInt<16>(Imm);
9945 }
9946
9947 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9948   return isInt<16>(Imm) || isUInt<16>(Imm);
9949 }
9950
9951 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9952                                                        unsigned,
9953                                                        unsigned,
9954                                                        bool *Fast) const {
9955   if (DisablePPCUnaligned)
9956     return false;
9957
9958   // PowerPC supports unaligned memory access for simple non-vector types.
9959   // Although accessing unaligned addresses is not as efficient as accessing
9960   // aligned addresses, it is generally more efficient than manual expansion,
9961   // and generally only traps for software emulation when crossing page
9962   // boundaries.
9963
9964   if (!VT.isSimple())
9965     return false;
9966
9967   if (VT.getSimpleVT().isVector()) {
9968     if (Subtarget.hasVSX()) {
9969       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9970           VT != MVT::v4f32 && VT != MVT::v4i32)
9971         return false;
9972     } else {
9973       return false;
9974     }
9975   }
9976
9977   if (VT == MVT::ppcf128)
9978     return false;
9979
9980   if (Fast)
9981     *Fast = true;
9982
9983   return true;
9984 }
9985
9986 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9987   VT = VT.getScalarType();
9988
9989   if (!VT.isSimple())
9990     return false;
9991
9992   switch (VT.getSimpleVT().SimpleTy) {
9993   case MVT::f32:
9994   case MVT::f64:
9995     return true;
9996   default:
9997     break;
9998   }
9999
10000   return false;
10001 }
10002
10003 const MCPhysReg *
10004 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
10005   // LR is a callee-save register, but we must treat it as clobbered by any call
10006   // site. Hence we include LR in the scratch registers, which are in turn added
10007   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
10008   // to CTR, which is used by any indirect call.
10009   static const MCPhysReg ScratchRegs[] = {
10010     PPC::X12, PPC::LR8, PPC::CTR8, 0
10011   };
10012
10013   return ScratchRegs;
10014 }
10015
10016 bool
10017 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
10018                      EVT VT , unsigned DefinedValues) const {
10019   if (VT == MVT::v2i64)
10020     return false;
10021
10022   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
10023 }
10024
10025 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
10026   if (DisableILPPref || Subtarget.enableMachineScheduler())
10027     return TargetLowering::getSchedulingPreference(N);
10028
10029   return Sched::ILP;
10030 }
10031
10032 // Create a fast isel object.
10033 FastISel *
10034 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
10035                                   const TargetLibraryInfo *LibInfo) const {
10036   return PPC::createFastISel(FuncInfo, LibInfo);
10037 }