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 "PPCCCState.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCPerfectShuffle.h"
20 #include "PPCTargetMachine.h"
21 #include "PPCTargetObjectFile.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include <list>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "ppc-lowering"
50 
51 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
52 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
53 
54 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
55 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
56 
57 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
58 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
59 
60 static cl::opt<bool> DisableSCO("disable-ppc-sco",
61 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
62 
63 STATISTIC(NumTailCalls, "Number of tail calls");
64 STATISTIC(NumSiblingCalls, "Number of sibling calls");
65 
66 // FIXME: Remove this once the bug has been fixed!
67 extern cl::opt<bool> ANDIGlueBug;
68 
69 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
70                                      const PPCSubtarget &STI)
71     : TargetLowering(TM), Subtarget(STI) {
72   // Use _setjmp/_longjmp instead of setjmp/longjmp.
73   setUseUnderscoreSetJmp(true);
74   setUseUnderscoreLongJmp(true);
75 
76   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77   // arguments are at least 4/8 bytes aligned.
78   bool isPPC64 = Subtarget.isPPC64();
79   setMinStackArgumentAlignment(isPPC64 ? 8:4);
80 
81   // Set up the register classes.
82   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
83   if (!Subtarget.useSoftFloat()) {
84     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
85     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
86   }
87 
88   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
89   for (MVT VT : MVT::integer_valuetypes()) {
90     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
91     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
92   }
93 
94   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
95 
96   // PowerPC has pre-inc load and store's.
97   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
98   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
99   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
100   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
101   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
102   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
103   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
104   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
105   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
106   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
107   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
108   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
110   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
111 
112   if (Subtarget.useCRBits()) {
113     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
114 
115     if (isPPC64 || Subtarget.hasFPCVT()) {
116       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
117       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
118                          isPPC64 ? MVT::i64 : MVT::i32);
119       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
120       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
121                         isPPC64 ? MVT::i64 : MVT::i32);
122     } else {
123       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
124       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
125     }
126 
127     // PowerPC does not support direct load / store of condition registers
128     setOperationAction(ISD::LOAD, MVT::i1, Custom);
129     setOperationAction(ISD::STORE, MVT::i1, Custom);
130 
131     // FIXME: Remove this once the ANDI glue bug is fixed:
132     if (ANDIGlueBug)
133       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
134 
135     for (MVT VT : MVT::integer_valuetypes()) {
136       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
137       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
138       setTruncStoreAction(VT, MVT::i1, Expand);
139     }
140 
141     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
142   }
143 
144   // This is used in the ppcf128->int sequence.  Note it has different semantics
145   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
146   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
147 
148   // We do not currently implement these libm ops for PowerPC.
149   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
150   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
151   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
152   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
153   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
154   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
155 
156   // PowerPC has no SREM/UREM instructions
157   setOperationAction(ISD::SREM, MVT::i32, Expand);
158   setOperationAction(ISD::UREM, MVT::i32, Expand);
159   setOperationAction(ISD::SREM, MVT::i64, Expand);
160   setOperationAction(ISD::UREM, MVT::i64, Expand);
161 
162   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
163   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
164   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
165   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
166   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
167   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
168   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
169   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
170   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
171 
172   // We don't support sin/cos/sqrt/fmod/pow
173   setOperationAction(ISD::FSIN , MVT::f64, Expand);
174   setOperationAction(ISD::FCOS , MVT::f64, Expand);
175   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
176   setOperationAction(ISD::FREM , MVT::f64, Expand);
177   setOperationAction(ISD::FPOW , MVT::f64, Expand);
178   setOperationAction(ISD::FMA  , MVT::f64, Legal);
179   setOperationAction(ISD::FSIN , MVT::f32, Expand);
180   setOperationAction(ISD::FCOS , MVT::f32, Expand);
181   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
182   setOperationAction(ISD::FREM , MVT::f32, Expand);
183   setOperationAction(ISD::FPOW , MVT::f32, Expand);
184   setOperationAction(ISD::FMA  , MVT::f32, Legal);
185 
186   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
187 
188   // If we're enabling GP optimizations, use hardware square root
189   if (!Subtarget.hasFSQRT() &&
190       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
191         Subtarget.hasFRE()))
192     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
193 
194   if (!Subtarget.hasFSQRT() &&
195       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
196         Subtarget.hasFRES()))
197     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
198 
199   if (Subtarget.hasFCPSGN()) {
200     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
201     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
202   } else {
203     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
204     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
205   }
206 
207   if (Subtarget.hasFPRND()) {
208     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
209     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
210     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
211     setOperationAction(ISD::FROUND, MVT::f64, Legal);
212 
213     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
214     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
215     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
216     setOperationAction(ISD::FROUND, MVT::f32, Legal);
217   }
218 
219   // PowerPC does not have BSWAP, CTPOP or CTTZ
220   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
221   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
222   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
223   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
224 
225   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
226     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
227     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
228   } else {
229     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
230     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
231   }
232 
233   // PowerPC does not have ROTR
234   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
235   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
236 
237   if (!Subtarget.useCRBits()) {
238     // PowerPC does not have Select
239     setOperationAction(ISD::SELECT, MVT::i32, Expand);
240     setOperationAction(ISD::SELECT, MVT::i64, Expand);
241     setOperationAction(ISD::SELECT, MVT::f32, Expand);
242     setOperationAction(ISD::SELECT, MVT::f64, Expand);
243   }
244 
245   // PowerPC wants to turn select_cc of FP into fsel when possible.
246   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
247   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
248 
249   // PowerPC wants to optimize integer setcc a bit
250   if (!Subtarget.useCRBits())
251     setOperationAction(ISD::SETCC, MVT::i32, Custom);
252 
253   // PowerPC does not have BRCOND which requires SetCC
254   if (!Subtarget.useCRBits())
255     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
256 
257   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
258 
259   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
260   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261 
262   // PowerPC does not have [U|S]INT_TO_FP
263   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
264   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
265 
266   if (Subtarget.hasDirectMove() && isPPC64) {
267     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
268     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
269     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
270     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
271   } else {
272     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
273     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
274     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
275     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
276   }
277 
278   // We cannot sextinreg(i1).  Expand to shifts.
279   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
280 
281   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
282   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
283   // support continuation, user-level threading, and etc.. As a result, no
284   // other SjLj exception interfaces are implemented and please don't build
285   // your own exception handling based on them.
286   // LLVM/Clang supports zero-cost DWARF exception handling.
287   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
288   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
289 
290   // We want to legalize GlobalAddress and ConstantPool nodes into the
291   // appropriate instructions to materialize the address.
292   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
293   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
294   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
295   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
296   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
297   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
298   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
299   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
300   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
301   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
302 
303   // TRAP is legal.
304   setOperationAction(ISD::TRAP, MVT::Other, Legal);
305 
306   // TRAMPOLINE is custom lowered.
307   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
308   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
309 
310   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
312 
313   if (Subtarget.isSVR4ABI()) {
314     if (isPPC64) {
315       // VAARG always uses double-word chunks, so promote anything smaller.
316       setOperationAction(ISD::VAARG, MVT::i1, Promote);
317       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
318       setOperationAction(ISD::VAARG, MVT::i8, Promote);
319       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
320       setOperationAction(ISD::VAARG, MVT::i16, Promote);
321       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
322       setOperationAction(ISD::VAARG, MVT::i32, Promote);
323       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
324       setOperationAction(ISD::VAARG, MVT::Other, Expand);
325     } else {
326       // VAARG is custom lowered with the 32-bit SVR4 ABI.
327       setOperationAction(ISD::VAARG, MVT::Other, Custom);
328       setOperationAction(ISD::VAARG, MVT::i64, Custom);
329     }
330   } else
331     setOperationAction(ISD::VAARG, MVT::Other, Expand);
332 
333   if (Subtarget.isSVR4ABI() && !isPPC64)
334     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
335     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
336   else
337     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
338 
339   // Use the default implementation.
340   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
341   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
342   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
343   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
344   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
345   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
346   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
347 
348   // We want to custom lower some of our intrinsics.
349   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
350 
351   // To handle counter-based loop conditions.
352   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
353 
354   // Comparisons that require checking two conditions.
355   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
356   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
357   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
358   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
359   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
360   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
361   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
362   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
363   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
364   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
365   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
366   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
367 
368   if (Subtarget.has64BitSupport()) {
369     // They also have instructions for converting between i64 and fp.
370     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
371     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
372     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
373     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
374     // This is just the low 32 bits of a (signed) fp->i64 conversion.
375     // We cannot do this with Promote because i64 is not a legal type.
376     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
377 
378     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
379       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
380   } else {
381     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
382     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
383   }
384 
385   // With the instructions enabled under FPCVT, we can do everything.
386   if (Subtarget.hasFPCVT()) {
387     if (Subtarget.has64BitSupport()) {
388       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
389       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
390       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
391       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
392     }
393 
394     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
395     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
396     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
397     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
398   }
399 
400   if (Subtarget.use64BitRegs()) {
401     // 64-bit PowerPC implementations can support i64 types directly
402     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
403     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
404     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
405     // 64-bit PowerPC wants to expand i128 shifts itself.
406     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
407     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
408     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
409   } else {
410     // 32-bit PowerPC wants to expand i64 shifts itself.
411     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
412     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
413     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
414   }
415 
416   if (Subtarget.hasAltivec()) {
417     // First set operation action for all vector types to expand. Then we
418     // will selectively turn on ones that can be effectively codegen'd.
419     for (MVT VT : MVT::vector_valuetypes()) {
420       // add/sub are legal for all supported vector VT's.
421       setOperationAction(ISD::ADD, VT, Legal);
422       setOperationAction(ISD::SUB, VT, Legal);
423 
424       // Vector instructions introduced in P8
425       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
426         setOperationAction(ISD::CTPOP, VT, Legal);
427         setOperationAction(ISD::CTLZ, VT, Legal);
428       }
429       else {
430         setOperationAction(ISD::CTPOP, VT, Expand);
431         setOperationAction(ISD::CTLZ, VT, Expand);
432       }
433 
434       // We promote all shuffles to v16i8.
435       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
436       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
437 
438       // We promote all non-typed operations to v4i32.
439       setOperationAction(ISD::AND   , VT, Promote);
440       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
441       setOperationAction(ISD::OR    , VT, Promote);
442       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
443       setOperationAction(ISD::XOR   , VT, Promote);
444       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
445       setOperationAction(ISD::LOAD  , VT, Promote);
446       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
447       setOperationAction(ISD::SELECT, VT, Promote);
448       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
449       setOperationAction(ISD::SELECT_CC, VT, Promote);
450       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
451       setOperationAction(ISD::STORE, VT, Promote);
452       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
453 
454       // No other operations are legal.
455       setOperationAction(ISD::MUL , VT, Expand);
456       setOperationAction(ISD::SDIV, VT, Expand);
457       setOperationAction(ISD::SREM, VT, Expand);
458       setOperationAction(ISD::UDIV, VT, Expand);
459       setOperationAction(ISD::UREM, VT, Expand);
460       setOperationAction(ISD::FDIV, VT, Expand);
461       setOperationAction(ISD::FREM, VT, Expand);
462       setOperationAction(ISD::FNEG, VT, Expand);
463       setOperationAction(ISD::FSQRT, VT, Expand);
464       setOperationAction(ISD::FLOG, VT, Expand);
465       setOperationAction(ISD::FLOG10, VT, Expand);
466       setOperationAction(ISD::FLOG2, VT, Expand);
467       setOperationAction(ISD::FEXP, VT, Expand);
468       setOperationAction(ISD::FEXP2, VT, Expand);
469       setOperationAction(ISD::FSIN, VT, Expand);
470       setOperationAction(ISD::FCOS, VT, Expand);
471       setOperationAction(ISD::FABS, VT, Expand);
472       setOperationAction(ISD::FPOWI, VT, Expand);
473       setOperationAction(ISD::FFLOOR, VT, Expand);
474       setOperationAction(ISD::FCEIL,  VT, Expand);
475       setOperationAction(ISD::FTRUNC, VT, Expand);
476       setOperationAction(ISD::FRINT,  VT, Expand);
477       setOperationAction(ISD::FNEARBYINT, VT, Expand);
478       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
479       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
480       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
481       setOperationAction(ISD::MULHU, VT, Expand);
482       setOperationAction(ISD::MULHS, VT, Expand);
483       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
484       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
485       setOperationAction(ISD::UDIVREM, VT, Expand);
486       setOperationAction(ISD::SDIVREM, VT, Expand);
487       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
488       setOperationAction(ISD::FPOW, VT, Expand);
489       setOperationAction(ISD::BSWAP, VT, Expand);
490       setOperationAction(ISD::CTTZ, VT, Expand);
491       setOperationAction(ISD::VSELECT, VT, Expand);
492       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
493       setOperationAction(ISD::ROTL, VT, Expand);
494       setOperationAction(ISD::ROTR, VT, Expand);
495 
496       for (MVT InnerVT : MVT::vector_valuetypes()) {
497         setTruncStoreAction(VT, InnerVT, Expand);
498         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
499         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
500         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
501       }
502     }
503 
504     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
505     // with merges, splats, etc.
506     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
507 
508     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
509     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
510     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
511     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
512     setOperationAction(ISD::SELECT, MVT::v4i32,
513                        Subtarget.useCRBits() ? Legal : Expand);
514     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
515     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
516     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
517     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
518     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
519     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
520     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
521     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
523 
524     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
525     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
526     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
527     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
528 
529     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
530     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
531 
532     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
533       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
534       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
535     }
536 
537     if (Subtarget.hasP8Altivec())
538       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
539     else
540       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
541 
542     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
543     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
544 
545     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
546     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
547 
548     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
549     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
550     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
551     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
552 
553     // Altivec does not contain unordered floating-point compare instructions
554     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
555     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
556     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
557     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
558 
559     if (Subtarget.hasVSX()) {
560       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
561       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
562       if (Subtarget.hasP8Vector()) {
563         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
564         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
565       }
566       if (Subtarget.hasDirectMove() && isPPC64) {
567         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
568         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
569         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
570         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
571         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
572         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
573         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
574         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
575       }
576       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
577 
578       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
579       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
580       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
581       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
582       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
583 
584       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
585 
586       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
587       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
588 
589       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
590       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
591 
592       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
593       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
594       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
595       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
596       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
597 
598       // Share the Altivec comparison restrictions.
599       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
600       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
601       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
602       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
603 
604       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
605       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
606 
607       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
608 
609       if (Subtarget.hasP8Vector())
610         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
611 
612       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
613 
614       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
615       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
616       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
617 
618       if (Subtarget.hasP8Altivec()) {
619         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
620         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
621         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
622 
623         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
624       }
625       else {
626         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
627         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
628         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
629 
630         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
631 
632         // VSX v2i64 only supports non-arithmetic operations.
633         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
634         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
635       }
636 
637       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
638       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
639       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
640       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
641 
642       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
643 
644       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
645       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
646       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
647       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
648 
649       // Vector operation legalization checks the result type of
650       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
651       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
652       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
653       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
654       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
655 
656       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
657       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
658       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
659       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
660 
661       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
662     }
663 
664     if (Subtarget.hasP8Altivec()) {
665       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
666       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
667     }
668   }
669 
670   if (Subtarget.hasQPX()) {
671     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
672     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
673     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
674     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
675 
676     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
677     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
678 
679     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
680     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
681 
682     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
683     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
684 
685     if (!Subtarget.useCRBits())
686       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
687     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
688 
689     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
690     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
691     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
692     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
693     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
694     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
695     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
696 
697     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
698     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
699 
700     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
701     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
702     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
703 
704     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
705     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
706     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
707     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
708     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
709     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
710     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
711     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
712     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
713     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
714     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
715 
716     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
717     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
718 
719     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
720     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
721 
722     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
723 
724     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
725     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
726     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
727     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
728 
729     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
730     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
731 
732     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
733     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
734 
735     if (!Subtarget.useCRBits())
736       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
737     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
738 
739     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
740     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
741     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
742     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
743     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
744     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
745     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
746 
747     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
748     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
749 
750     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
751     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
752     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
753     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
754     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
755     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
756     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
757     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
758     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
759     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
760     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
761 
762     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
763     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
764 
765     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
766     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
767 
768     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
769 
770     setOperationAction(ISD::AND , MVT::v4i1, Legal);
771     setOperationAction(ISD::OR , MVT::v4i1, Legal);
772     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
773 
774     if (!Subtarget.useCRBits())
775       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
776     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
777 
778     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
779     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
780 
781     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
782     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
783     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
784     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
785     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
786     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
787     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
788 
789     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
790     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
791 
792     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
793 
794     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
795     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
796     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
797     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
798 
799     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
800     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
801     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
802     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
803 
804     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
805     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
806 
807     // These need to set FE_INEXACT, and so cannot be vectorized here.
808     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
809     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
810 
811     if (TM.Options.UnsafeFPMath) {
812       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
813       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
814 
815       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
816       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
817     } else {
818       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
819       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
820 
821       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
822       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
823     }
824   }
825 
826   if (Subtarget.has64BitSupport())
827     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
828 
829   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
830 
831   if (!isPPC64) {
832     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
833     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
834   }
835 
836   setBooleanContents(ZeroOrOneBooleanContent);
837 
838   if (Subtarget.hasAltivec()) {
839     // Altivec instructions set fields to all zeros or all ones.
840     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
841   }
842 
843   if (!isPPC64) {
844     // These libcalls are not available in 32-bit.
845     setLibcallName(RTLIB::SHL_I128, nullptr);
846     setLibcallName(RTLIB::SRL_I128, nullptr);
847     setLibcallName(RTLIB::SRA_I128, nullptr);
848   }
849 
850   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
851 
852   // We have target-specific dag combine patterns for the following nodes:
853   setTargetDAGCombine(ISD::SINT_TO_FP);
854   if (Subtarget.hasFPCVT())
855     setTargetDAGCombine(ISD::UINT_TO_FP);
856   setTargetDAGCombine(ISD::LOAD);
857   setTargetDAGCombine(ISD::STORE);
858   setTargetDAGCombine(ISD::BR_CC);
859   if (Subtarget.useCRBits())
860     setTargetDAGCombine(ISD::BRCOND);
861   setTargetDAGCombine(ISD::BSWAP);
862   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
863   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
864   setTargetDAGCombine(ISD::INTRINSIC_VOID);
865 
866   setTargetDAGCombine(ISD::SIGN_EXTEND);
867   setTargetDAGCombine(ISD::ZERO_EXTEND);
868   setTargetDAGCombine(ISD::ANY_EXTEND);
869 
870   if (Subtarget.useCRBits()) {
871     setTargetDAGCombine(ISD::TRUNCATE);
872     setTargetDAGCombine(ISD::SETCC);
873     setTargetDAGCombine(ISD::SELECT_CC);
874   }
875 
876   // Use reciprocal estimates.
877   if (TM.Options.UnsafeFPMath) {
878     setTargetDAGCombine(ISD::FDIV);
879     setTargetDAGCombine(ISD::FSQRT);
880   }
881 
882   // Darwin long double math library functions have $LDBL128 appended.
883   if (Subtarget.isDarwin()) {
884     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
885     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
886     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
887     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
888     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
889     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
890     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
891     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
892     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
893     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
894   }
895 
896   // With 32 condition bits, we don't need to sink (and duplicate) compares
897   // aggressively in CodeGenPrep.
898   if (Subtarget.useCRBits()) {
899     setHasMultipleConditionRegisters();
900     setJumpIsExpensive();
901   }
902 
903   setMinFunctionAlignment(2);
904   if (Subtarget.isDarwin())
905     setPrefFunctionAlignment(4);
906 
907   switch (Subtarget.getDarwinDirective()) {
908   default: break;
909   case PPC::DIR_970:
910   case PPC::DIR_A2:
911   case PPC::DIR_E500mc:
912   case PPC::DIR_E5500:
913   case PPC::DIR_PWR4:
914   case PPC::DIR_PWR5:
915   case PPC::DIR_PWR5X:
916   case PPC::DIR_PWR6:
917   case PPC::DIR_PWR6X:
918   case PPC::DIR_PWR7:
919   case PPC::DIR_PWR8:
920   case PPC::DIR_PWR9:
921     setPrefFunctionAlignment(4);
922     setPrefLoopAlignment(4);
923     break;
924   }
925 
926 
927   if (Subtarget.enableMachineScheduler())
928     setSchedulingPreference(Sched::Source);
929   else
930     setSchedulingPreference(Sched::Hybrid);
931 
932   computeRegisterProperties(STI.getRegisterInfo());
933 
934   // The Freescale cores do better with aggressive inlining of memcpy and
935   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
936   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
937       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
938     MaxStoresPerMemset = 32;
939     MaxStoresPerMemsetOptSize = 16;
940     MaxStoresPerMemcpy = 32;
941     MaxStoresPerMemcpyOptSize = 8;
942     MaxStoresPerMemmove = 32;
943     MaxStoresPerMemmoveOptSize = 8;
944   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
945     // The A2 also benefits from (very) aggressive inlining of memcpy and
946     // friends. The overhead of a the function call, even when warm, can be
947     // over one hundred cycles.
948     MaxStoresPerMemset = 128;
949     MaxStoresPerMemcpy = 128;
950     MaxStoresPerMemmove = 128;
951   }
952 }
953 
954 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
955 /// the desired ByVal argument alignment.
956 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
957                              unsigned MaxMaxAlign) {
958   if (MaxAlign == MaxMaxAlign)
959     return;
960   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
961     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
962       MaxAlign = 32;
963     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
964       MaxAlign = 16;
965   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
966     unsigned EltAlign = 0;
967     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
968     if (EltAlign > MaxAlign)
969       MaxAlign = EltAlign;
970   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
971     for (auto *EltTy : STy->elements()) {
972       unsigned EltAlign = 0;
973       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
974       if (EltAlign > MaxAlign)
975         MaxAlign = EltAlign;
976       if (MaxAlign == MaxMaxAlign)
977         break;
978     }
979   }
980 }
981 
982 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
983 /// function arguments in the caller parameter area.
984 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
985                                                   const DataLayout &DL) const {
986   // Darwin passes everything on 4 byte boundary.
987   if (Subtarget.isDarwin())
988     return 4;
989 
990   // 16byte and wider vectors are passed on 16byte boundary.
991   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
992   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
993   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
994     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
995   return Align;
996 }
997 
998 bool PPCTargetLowering::useSoftFloat() const {
999   return Subtarget.useSoftFloat();
1000 }
1001 
1002 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1003   switch ((PPCISD::NodeType)Opcode) {
1004   case PPCISD::FIRST_NUMBER:    break;
1005   case PPCISD::FSEL:            return "PPCISD::FSEL";
1006   case PPCISD::FCFID:           return "PPCISD::FCFID";
1007   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1008   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1009   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1010   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1011   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1012   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1013   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1014   case PPCISD::FRE:             return "PPCISD::FRE";
1015   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1016   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1017   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1018   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1019   case PPCISD::VPERM:           return "PPCISD::VPERM";
1020   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1021   case PPCISD::CMPB:            return "PPCISD::CMPB";
1022   case PPCISD::Hi:              return "PPCISD::Hi";
1023   case PPCISD::Lo:              return "PPCISD::Lo";
1024   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1025   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1026   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1027   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1028   case PPCISD::SRL:             return "PPCISD::SRL";
1029   case PPCISD::SRA:             return "PPCISD::SRA";
1030   case PPCISD::SHL:             return "PPCISD::SHL";
1031   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1032   case PPCISD::CALL:            return "PPCISD::CALL";
1033   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1034   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1035   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1036   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1037   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1038   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1039   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1040   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1041   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1042   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1043   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1044   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1045   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1046   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1047   case PPCISD::VCMP:            return "PPCISD::VCMP";
1048   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1049   case PPCISD::LBRX:            return "PPCISD::LBRX";
1050   case PPCISD::STBRX:           return "PPCISD::STBRX";
1051   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1052   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1053   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1054   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1055   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1056   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1057   case PPCISD::BDZ:             return "PPCISD::BDZ";
1058   case PPCISD::MFFS:            return "PPCISD::MFFS";
1059   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1060   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1061   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1062   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1063   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1064   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1065   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1066   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1067   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1068   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1069   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1070   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1071   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1072   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1073   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1074   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1075   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1076   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1077   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1078   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1079   case PPCISD::SC:              return "PPCISD::SC";
1080   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1081   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1082   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1083   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1084   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1085   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1086   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1087   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1088   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1089   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1090   }
1091   return nullptr;
1092 }
1093 
1094 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1095                                           EVT VT) const {
1096   if (!VT.isVector())
1097     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1098 
1099   if (Subtarget.hasQPX())
1100     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1101 
1102   return VT.changeVectorElementTypeToInteger();
1103 }
1104 
1105 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1106   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1107   return true;
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 // Node matching predicates, for use by the tblgen matching code.
1112 //===----------------------------------------------------------------------===//
1113 
1114 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1115 static bool isFloatingPointZero(SDValue Op) {
1116   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1117     return CFP->getValueAPF().isZero();
1118   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1119     // Maybe this has already been legalized into the constant pool?
1120     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1121       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1122         return CFP->getValueAPF().isZero();
1123   }
1124   return false;
1125 }
1126 
1127 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1128 /// true if Op is undef or if it matches the specified value.
1129 static bool isConstantOrUndef(int Op, int Val) {
1130   return Op < 0 || Op == Val;
1131 }
1132 
1133 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1134 /// VPKUHUM instruction.
1135 /// The ShuffleKind distinguishes between big-endian operations with
1136 /// two different inputs (0), either-endian operations with two identical
1137 /// inputs (1), and little-endian operations with two different inputs (2).
1138 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1139 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1140                                SelectionDAG &DAG) {
1141   bool IsLE = DAG.getDataLayout().isLittleEndian();
1142   if (ShuffleKind == 0) {
1143     if (IsLE)
1144       return false;
1145     for (unsigned i = 0; i != 16; ++i)
1146       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1147         return false;
1148   } else if (ShuffleKind == 2) {
1149     if (!IsLE)
1150       return false;
1151     for (unsigned i = 0; i != 16; ++i)
1152       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1153         return false;
1154   } else if (ShuffleKind == 1) {
1155     unsigned j = IsLE ? 0 : 1;
1156     for (unsigned i = 0; i != 8; ++i)
1157       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1158           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1159         return false;
1160   }
1161   return true;
1162 }
1163 
1164 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1165 /// VPKUWUM instruction.
1166 /// The ShuffleKind distinguishes between big-endian operations with
1167 /// two different inputs (0), either-endian operations with two identical
1168 /// inputs (1), and little-endian operations with two different inputs (2).
1169 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1170 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1171                                SelectionDAG &DAG) {
1172   bool IsLE = DAG.getDataLayout().isLittleEndian();
1173   if (ShuffleKind == 0) {
1174     if (IsLE)
1175       return false;
1176     for (unsigned i = 0; i != 16; i += 2)
1177       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1178           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1179         return false;
1180   } else if (ShuffleKind == 2) {
1181     if (!IsLE)
1182       return false;
1183     for (unsigned i = 0; i != 16; i += 2)
1184       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1185           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1186         return false;
1187   } else if (ShuffleKind == 1) {
1188     unsigned j = IsLE ? 0 : 2;
1189     for (unsigned i = 0; i != 8; i += 2)
1190       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1191           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1192           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1193           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1194         return false;
1195   }
1196   return true;
1197 }
1198 
1199 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1200 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1201 /// current subtarget.
1202 ///
1203 /// The ShuffleKind distinguishes between big-endian operations with
1204 /// two different inputs (0), either-endian operations with two identical
1205 /// inputs (1), and little-endian operations with two different inputs (2).
1206 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1207 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1208                                SelectionDAG &DAG) {
1209   const PPCSubtarget& Subtarget =
1210     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1211   if (!Subtarget.hasP8Vector())
1212     return false;
1213 
1214   bool IsLE = DAG.getDataLayout().isLittleEndian();
1215   if (ShuffleKind == 0) {
1216     if (IsLE)
1217       return false;
1218     for (unsigned i = 0; i != 16; i += 4)
1219       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1220           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1221           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1222           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1223         return false;
1224   } else if (ShuffleKind == 2) {
1225     if (!IsLE)
1226       return false;
1227     for (unsigned i = 0; i != 16; i += 4)
1228       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1229           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1230           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1231           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1232         return false;
1233   } else if (ShuffleKind == 1) {
1234     unsigned j = IsLE ? 0 : 4;
1235     for (unsigned i = 0; i != 8; i += 4)
1236       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1237           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1238           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1239           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1240           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1241           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1242           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1243           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1244         return false;
1245   }
1246   return true;
1247 }
1248 
1249 /// isVMerge - Common function, used to match vmrg* shuffles.
1250 ///
1251 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1252                      unsigned LHSStart, unsigned RHSStart) {
1253   if (N->getValueType(0) != MVT::v16i8)
1254     return false;
1255   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1256          "Unsupported merge size!");
1257 
1258   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1259     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1260       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1261                              LHSStart+j+i*UnitSize) ||
1262           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1263                              RHSStart+j+i*UnitSize))
1264         return false;
1265     }
1266   return true;
1267 }
1268 
1269 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1270 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1271 /// The ShuffleKind distinguishes between big-endian merges with two
1272 /// different inputs (0), either-endian merges with two identical inputs (1),
1273 /// and little-endian merges with two different inputs (2).  For the latter,
1274 /// the input operands are swapped (see PPCInstrAltivec.td).
1275 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1276                              unsigned ShuffleKind, SelectionDAG &DAG) {
1277   if (DAG.getDataLayout().isLittleEndian()) {
1278     if (ShuffleKind == 1) // unary
1279       return isVMerge(N, UnitSize, 0, 0);
1280     else if (ShuffleKind == 2) // swapped
1281       return isVMerge(N, UnitSize, 0, 16);
1282     else
1283       return false;
1284   } else {
1285     if (ShuffleKind == 1) // unary
1286       return isVMerge(N, UnitSize, 8, 8);
1287     else if (ShuffleKind == 0) // normal
1288       return isVMerge(N, UnitSize, 8, 24);
1289     else
1290       return false;
1291   }
1292 }
1293 
1294 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1295 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1296 /// The ShuffleKind distinguishes between big-endian merges with two
1297 /// different inputs (0), either-endian merges with two identical inputs (1),
1298 /// and little-endian merges with two different inputs (2).  For the latter,
1299 /// the input operands are swapped (see PPCInstrAltivec.td).
1300 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1301                              unsigned ShuffleKind, SelectionDAG &DAG) {
1302   if (DAG.getDataLayout().isLittleEndian()) {
1303     if (ShuffleKind == 1) // unary
1304       return isVMerge(N, UnitSize, 8, 8);
1305     else if (ShuffleKind == 2) // swapped
1306       return isVMerge(N, UnitSize, 8, 24);
1307     else
1308       return false;
1309   } else {
1310     if (ShuffleKind == 1) // unary
1311       return isVMerge(N, UnitSize, 0, 0);
1312     else if (ShuffleKind == 0) // normal
1313       return isVMerge(N, UnitSize, 0, 16);
1314     else
1315       return false;
1316   }
1317 }
1318 
1319 /**
1320  * \brief Common function used to match vmrgew and vmrgow shuffles
1321  *
1322  * The indexOffset determines whether to look for even or odd words in
1323  * the shuffle mask. This is based on the of the endianness of the target
1324  * machine.
1325  *   - Little Endian:
1326  *     - Use offset of 0 to check for odd elements
1327  *     - Use offset of 4 to check for even elements
1328  *   - Big Endian:
1329  *     - Use offset of 0 to check for even elements
1330  *     - Use offset of 4 to check for odd elements
1331  * A detailed description of the vector element ordering for little endian and
1332  * big endian can be found at
1333  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1334  * Targeting your applications - what little endian and big endian IBM XL C/C++
1335  * compiler differences mean to you
1336  *
1337  * The mask to the shuffle vector instruction specifies the indices of the
1338  * elements from the two input vectors to place in the result. The elements are
1339  * numbered in array-access order, starting with the first vector. These vectors
1340  * are always of type v16i8, thus each vector will contain 16 elements of size
1341  * 8. More info on the shuffle vector can be found in the
1342  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1343  * Language Reference.
1344  *
1345  * The RHSStartValue indicates whether the same input vectors are used (unary)
1346  * or two different input vectors are used, based on the following:
1347  *   - If the instruction uses the same vector for both inputs, the range of the
1348  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1349  *     be 0.
1350  *   - If the instruction has two different vectors then the range of the
1351  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1352  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1353  *     to 31 specify elements in the second vector).
1354  *
1355  * \param[in] N The shuffle vector SD Node to analyze
1356  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1357  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1358  * vector to the shuffle_vector instruction
1359  * \return true iff this shuffle vector represents an even or odd word merge
1360  */
1361 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1362                      unsigned RHSStartValue) {
1363   if (N->getValueType(0) != MVT::v16i8)
1364     return false;
1365 
1366   for (unsigned i = 0; i < 2; ++i)
1367     for (unsigned j = 0; j < 4; ++j)
1368       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1369                              i*RHSStartValue+j+IndexOffset) ||
1370           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1371                              i*RHSStartValue+j+IndexOffset+8))
1372         return false;
1373   return true;
1374 }
1375 
1376 /**
1377  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1378  * vmrgow instructions.
1379  *
1380  * \param[in] N The shuffle vector SD Node to analyze
1381  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1382  * \param[in] ShuffleKind Identify the type of merge:
1383  *   - 0 = big-endian merge with two different inputs;
1384  *   - 1 = either-endian merge with two identical inputs;
1385  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1386  *     little-endian merges).
1387  * \param[in] DAG The current SelectionDAG
1388  * \return true iff this shuffle mask
1389  */
1390 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1391                               unsigned ShuffleKind, SelectionDAG &DAG) {
1392   if (DAG.getDataLayout().isLittleEndian()) {
1393     unsigned indexOffset = CheckEven ? 4 : 0;
1394     if (ShuffleKind == 1) // Unary
1395       return isVMerge(N, indexOffset, 0);
1396     else if (ShuffleKind == 2) // swapped
1397       return isVMerge(N, indexOffset, 16);
1398     else
1399       return false;
1400   }
1401   else {
1402     unsigned indexOffset = CheckEven ? 0 : 4;
1403     if (ShuffleKind == 1) // Unary
1404       return isVMerge(N, indexOffset, 0);
1405     else if (ShuffleKind == 0) // Normal
1406       return isVMerge(N, indexOffset, 16);
1407     else
1408       return false;
1409   }
1410   return false;
1411 }
1412 
1413 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1414 /// amount, otherwise return -1.
1415 /// The ShuffleKind distinguishes between big-endian operations with two
1416 /// different inputs (0), either-endian operations with two identical inputs
1417 /// (1), and little-endian operations with two different inputs (2).  For the
1418 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1419 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1420                              SelectionDAG &DAG) {
1421   if (N->getValueType(0) != MVT::v16i8)
1422     return -1;
1423 
1424   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1425 
1426   // Find the first non-undef value in the shuffle mask.
1427   unsigned i;
1428   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1429     /*search*/;
1430 
1431   if (i == 16) return -1;  // all undef.
1432 
1433   // Otherwise, check to see if the rest of the elements are consecutively
1434   // numbered from this value.
1435   unsigned ShiftAmt = SVOp->getMaskElt(i);
1436   if (ShiftAmt < i) return -1;
1437 
1438   ShiftAmt -= i;
1439   bool isLE = DAG.getDataLayout().isLittleEndian();
1440 
1441   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1442     // Check the rest of the elements to see if they are consecutive.
1443     for (++i; i != 16; ++i)
1444       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1445         return -1;
1446   } else if (ShuffleKind == 1) {
1447     // Check the rest of the elements to see if they are consecutive.
1448     for (++i; i != 16; ++i)
1449       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1450         return -1;
1451   } else
1452     return -1;
1453 
1454   if (isLE)
1455     ShiftAmt = 16 - ShiftAmt;
1456 
1457   return ShiftAmt;
1458 }
1459 
1460 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1461 /// specifies a splat of a single element that is suitable for input to
1462 /// VSPLTB/VSPLTH/VSPLTW.
1463 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1464   assert(N->getValueType(0) == MVT::v16i8 &&
1465          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1466 
1467   // The consecutive indices need to specify an element, not part of two
1468   // different elements.  So abandon ship early if this isn't the case.
1469   if (N->getMaskElt(0) % EltSize != 0)
1470     return false;
1471 
1472   // This is a splat operation if each element of the permute is the same, and
1473   // if the value doesn't reference the second vector.
1474   unsigned ElementBase = N->getMaskElt(0);
1475 
1476   // FIXME: Handle UNDEF elements too!
1477   if (ElementBase >= 16)
1478     return false;
1479 
1480   // Check that the indices are consecutive, in the case of a multi-byte element
1481   // splatted with a v16i8 mask.
1482   for (unsigned i = 1; i != EltSize; ++i)
1483     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1484       return false;
1485 
1486   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1487     if (N->getMaskElt(i) < 0) continue;
1488     for (unsigned j = 0; j != EltSize; ++j)
1489       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1490         return false;
1491   }
1492   return true;
1493 }
1494 
1495 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1496 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1497 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1498                                 SelectionDAG &DAG) {
1499   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1500   assert(isSplatShuffleMask(SVOp, EltSize));
1501   if (DAG.getDataLayout().isLittleEndian())
1502     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1503   else
1504     return SVOp->getMaskElt(0) / EltSize;
1505 }
1506 
1507 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1508 /// by using a vspltis[bhw] instruction of the specified element size, return
1509 /// the constant being splatted.  The ByteSize field indicates the number of
1510 /// bytes of each element [124] -> [bhw].
1511 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1512   SDValue OpVal(nullptr, 0);
1513 
1514   // If ByteSize of the splat is bigger than the element size of the
1515   // build_vector, then we have a case where we are checking for a splat where
1516   // multiple elements of the buildvector are folded together into a single
1517   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1518   unsigned EltSize = 16/N->getNumOperands();
1519   if (EltSize < ByteSize) {
1520     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1521     SDValue UniquedVals[4];
1522     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1523 
1524     // See if all of the elements in the buildvector agree across.
1525     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1526       if (N->getOperand(i).isUndef()) continue;
1527       // If the element isn't a constant, bail fully out.
1528       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1529 
1530 
1531       if (!UniquedVals[i&(Multiple-1)].getNode())
1532         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1533       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1534         return SDValue();  // no match.
1535     }
1536 
1537     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1538     // either constant or undef values that are identical for each chunk.  See
1539     // if these chunks can form into a larger vspltis*.
1540 
1541     // Check to see if all of the leading entries are either 0 or -1.  If
1542     // neither, then this won't fit into the immediate field.
1543     bool LeadingZero = true;
1544     bool LeadingOnes = true;
1545     for (unsigned i = 0; i != Multiple-1; ++i) {
1546       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1547 
1548       LeadingZero &= isNullConstant(UniquedVals[i]);
1549       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1550     }
1551     // Finally, check the least significant entry.
1552     if (LeadingZero) {
1553       if (!UniquedVals[Multiple-1].getNode())
1554         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1555       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1556       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1557         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1558     }
1559     if (LeadingOnes) {
1560       if (!UniquedVals[Multiple-1].getNode())
1561         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1562       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1563       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1564         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1565     }
1566 
1567     return SDValue();
1568   }
1569 
1570   // Check to see if this buildvec has a single non-undef value in its elements.
1571   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1572     if (N->getOperand(i).isUndef()) continue;
1573     if (!OpVal.getNode())
1574       OpVal = N->getOperand(i);
1575     else if (OpVal != N->getOperand(i))
1576       return SDValue();
1577   }
1578 
1579   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1580 
1581   unsigned ValSizeInBytes = EltSize;
1582   uint64_t Value = 0;
1583   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1584     Value = CN->getZExtValue();
1585   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1586     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1587     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1588   }
1589 
1590   // If the splat value is larger than the element value, then we can never do
1591   // this splat.  The only case that we could fit the replicated bits into our
1592   // immediate field for would be zero, and we prefer to use vxor for it.
1593   if (ValSizeInBytes < ByteSize) return SDValue();
1594 
1595   // If the element value is larger than the splat value, check if it consists
1596   // of a repeated bit pattern of size ByteSize.
1597   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1598     return SDValue();
1599 
1600   // Properly sign extend the value.
1601   int MaskVal = SignExtend32(Value, ByteSize * 8);
1602 
1603   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1604   if (MaskVal == 0) return SDValue();
1605 
1606   // Finally, if this value fits in a 5 bit sext field, return it
1607   if (SignExtend32<5>(MaskVal) == MaskVal)
1608     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1609   return SDValue();
1610 }
1611 
1612 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1613 /// amount, otherwise return -1.
1614 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1615   EVT VT = N->getValueType(0);
1616   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1617     return -1;
1618 
1619   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1620 
1621   // Find the first non-undef value in the shuffle mask.
1622   unsigned i;
1623   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1624     /*search*/;
1625 
1626   if (i == 4) return -1;  // all undef.
1627 
1628   // Otherwise, check to see if the rest of the elements are consecutively
1629   // numbered from this value.
1630   unsigned ShiftAmt = SVOp->getMaskElt(i);
1631   if (ShiftAmt < i) return -1;
1632   ShiftAmt -= i;
1633 
1634   // Check the rest of the elements to see if they are consecutive.
1635   for (++i; i != 4; ++i)
1636     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1637       return -1;
1638 
1639   return ShiftAmt;
1640 }
1641 
1642 //===----------------------------------------------------------------------===//
1643 //  Addressing Mode Selection
1644 //===----------------------------------------------------------------------===//
1645 
1646 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1647 /// or 64-bit immediate, and if the value can be accurately represented as a
1648 /// sign extension from a 16-bit value.  If so, this returns true and the
1649 /// immediate.
1650 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1651   if (!isa<ConstantSDNode>(N))
1652     return false;
1653 
1654   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1655   if (N->getValueType(0) == MVT::i32)
1656     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1657   else
1658     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1659 }
1660 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1661   return isIntS16Immediate(Op.getNode(), Imm);
1662 }
1663 
1664 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1665 /// can be represented as an indexed [r+r] operation.  Returns false if it
1666 /// can be more efficiently represented with [r+imm].
1667 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1668                                             SDValue &Index,
1669                                             SelectionDAG &DAG) const {
1670   short imm = 0;
1671   if (N.getOpcode() == ISD::ADD) {
1672     if (isIntS16Immediate(N.getOperand(1), imm))
1673       return false;    // r+i
1674     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1675       return false;    // r+i
1676 
1677     Base = N.getOperand(0);
1678     Index = N.getOperand(1);
1679     return true;
1680   } else if (N.getOpcode() == ISD::OR) {
1681     if (isIntS16Immediate(N.getOperand(1), imm))
1682       return false;    // r+i can fold it if we can.
1683 
1684     // If this is an or of disjoint bitfields, we can codegen this as an add
1685     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1686     // disjoint.
1687     APInt LHSKnownZero, LHSKnownOne;
1688     APInt RHSKnownZero, RHSKnownOne;
1689     DAG.computeKnownBits(N.getOperand(0),
1690                          LHSKnownZero, LHSKnownOne);
1691 
1692     if (LHSKnownZero.getBoolValue()) {
1693       DAG.computeKnownBits(N.getOperand(1),
1694                            RHSKnownZero, RHSKnownOne);
1695       // If all of the bits are known zero on the LHS or RHS, the add won't
1696       // carry.
1697       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1698         Base = N.getOperand(0);
1699         Index = N.getOperand(1);
1700         return true;
1701       }
1702     }
1703   }
1704 
1705   return false;
1706 }
1707 
1708 // If we happen to be doing an i64 load or store into a stack slot that has
1709 // less than a 4-byte alignment, then the frame-index elimination may need to
1710 // use an indexed load or store instruction (because the offset may not be a
1711 // multiple of 4). The extra register needed to hold the offset comes from the
1712 // register scavenger, and it is possible that the scavenger will need to use
1713 // an emergency spill slot. As a result, we need to make sure that a spill slot
1714 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1715 // stack slot.
1716 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1717   // FIXME: This does not handle the LWA case.
1718   if (VT != MVT::i64)
1719     return;
1720 
1721   // NOTE: We'll exclude negative FIs here, which come from argument
1722   // lowering, because there are no known test cases triggering this problem
1723   // using packed structures (or similar). We can remove this exclusion if
1724   // we find such a test case. The reason why this is so test-case driven is
1725   // because this entire 'fixup' is only to prevent crashes (from the
1726   // register scavenger) on not-really-valid inputs. For example, if we have:
1727   //   %a = alloca i1
1728   //   %b = bitcast i1* %a to i64*
1729   //   store i64* a, i64 b
1730   // then the store should really be marked as 'align 1', but is not. If it
1731   // were marked as 'align 1' then the indexed form would have been
1732   // instruction-selected initially, and the problem this 'fixup' is preventing
1733   // won't happen regardless.
1734   if (FrameIdx < 0)
1735     return;
1736 
1737   MachineFunction &MF = DAG.getMachineFunction();
1738   MachineFrameInfo *MFI = MF.getFrameInfo();
1739 
1740   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1741   if (Align >= 4)
1742     return;
1743 
1744   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1745   FuncInfo->setHasNonRISpills();
1746 }
1747 
1748 /// Returns true if the address N can be represented by a base register plus
1749 /// a signed 16-bit displacement [r+imm], and if it is not better
1750 /// represented as reg+reg.  If Aligned is true, only accept displacements
1751 /// suitable for STD and friends, i.e. multiples of 4.
1752 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1753                                             SDValue &Base,
1754                                             SelectionDAG &DAG,
1755                                             bool Aligned) const {
1756   // FIXME dl should come from parent load or store, not from address
1757   SDLoc dl(N);
1758   // If this can be more profitably realized as r+r, fail.
1759   if (SelectAddressRegReg(N, Disp, Base, DAG))
1760     return false;
1761 
1762   if (N.getOpcode() == ISD::ADD) {
1763     short imm = 0;
1764     if (isIntS16Immediate(N.getOperand(1), imm) &&
1765         (!Aligned || (imm & 3) == 0)) {
1766       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1767       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1768         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1769         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1770       } else {
1771         Base = N.getOperand(0);
1772       }
1773       return true; // [r+i]
1774     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1775       // Match LOAD (ADD (X, Lo(G))).
1776       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1777              && "Cannot handle constant offsets yet!");
1778       Disp = N.getOperand(1).getOperand(0);  // The global address.
1779       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1780              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1781              Disp.getOpcode() == ISD::TargetConstantPool ||
1782              Disp.getOpcode() == ISD::TargetJumpTable);
1783       Base = N.getOperand(0);
1784       return true;  // [&g+r]
1785     }
1786   } else if (N.getOpcode() == ISD::OR) {
1787     short imm = 0;
1788     if (isIntS16Immediate(N.getOperand(1), imm) &&
1789         (!Aligned || (imm & 3) == 0)) {
1790       // If this is an or of disjoint bitfields, we can codegen this as an add
1791       // (for better address arithmetic) if the LHS and RHS of the OR are
1792       // provably disjoint.
1793       APInt LHSKnownZero, LHSKnownOne;
1794       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1795 
1796       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1797         // If all of the bits are known zero on the LHS or RHS, the add won't
1798         // carry.
1799         if (FrameIndexSDNode *FI =
1800               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1801           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1802           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1803         } else {
1804           Base = N.getOperand(0);
1805         }
1806         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1807         return true;
1808       }
1809     }
1810   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1811     // Loading from a constant address.
1812 
1813     // If this address fits entirely in a 16-bit sext immediate field, codegen
1814     // this as "d, 0"
1815     short Imm;
1816     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1817       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1818       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1819                              CN->getValueType(0));
1820       return true;
1821     }
1822 
1823     // Handle 32-bit sext immediates with LIS + addr mode.
1824     if ((CN->getValueType(0) == MVT::i32 ||
1825          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1826         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1827       int Addr = (int)CN->getZExtValue();
1828 
1829       // Otherwise, break this down into an LIS + disp.
1830       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1831 
1832       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1833                                    MVT::i32);
1834       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1835       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1836       return true;
1837     }
1838   }
1839 
1840   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1841   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1842     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1843     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1844   } else
1845     Base = N;
1846   return true;      // [r+0]
1847 }
1848 
1849 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1850 /// represented as an indexed [r+r] operation.
1851 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1852                                                 SDValue &Index,
1853                                                 SelectionDAG &DAG) const {
1854   // Check to see if we can easily represent this as an [r+r] address.  This
1855   // will fail if it thinks that the address is more profitably represented as
1856   // reg+imm, e.g. where imm = 0.
1857   if (SelectAddressRegReg(N, Base, Index, DAG))
1858     return true;
1859 
1860   // If the operand is an addition, always emit this as [r+r], since this is
1861   // better (for code size, and execution, as the memop does the add for free)
1862   // than emitting an explicit add.
1863   if (N.getOpcode() == ISD::ADD) {
1864     Base = N.getOperand(0);
1865     Index = N.getOperand(1);
1866     return true;
1867   }
1868 
1869   // Otherwise, do it the hard way, using R0 as the base register.
1870   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1871                          N.getValueType());
1872   Index = N;
1873   return true;
1874 }
1875 
1876 /// getPreIndexedAddressParts - returns true by value, base pointer and
1877 /// offset pointer and addressing mode by reference if the node's address
1878 /// can be legally represented as pre-indexed load / store address.
1879 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1880                                                   SDValue &Offset,
1881                                                   ISD::MemIndexedMode &AM,
1882                                                   SelectionDAG &DAG) const {
1883   if (DisablePPCPreinc) return false;
1884 
1885   bool isLoad = true;
1886   SDValue Ptr;
1887   EVT VT;
1888   unsigned Alignment;
1889   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1890     Ptr = LD->getBasePtr();
1891     VT = LD->getMemoryVT();
1892     Alignment = LD->getAlignment();
1893   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1894     Ptr = ST->getBasePtr();
1895     VT  = ST->getMemoryVT();
1896     Alignment = ST->getAlignment();
1897     isLoad = false;
1898   } else
1899     return false;
1900 
1901   // PowerPC doesn't have preinc load/store instructions for vectors (except
1902   // for QPX, which does have preinc r+r forms).
1903   if (VT.isVector()) {
1904     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1905       return false;
1906     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1907       AM = ISD::PRE_INC;
1908       return true;
1909     }
1910   }
1911 
1912   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1913 
1914     // Common code will reject creating a pre-inc form if the base pointer
1915     // is a frame index, or if N is a store and the base pointer is either
1916     // the same as or a predecessor of the value being stored.  Check for
1917     // those situations here, and try with swapped Base/Offset instead.
1918     bool Swap = false;
1919 
1920     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1921       Swap = true;
1922     else if (!isLoad) {
1923       SDValue Val = cast<StoreSDNode>(N)->getValue();
1924       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1925         Swap = true;
1926     }
1927 
1928     if (Swap)
1929       std::swap(Base, Offset);
1930 
1931     AM = ISD::PRE_INC;
1932     return true;
1933   }
1934 
1935   // LDU/STU can only handle immediates that are a multiple of 4.
1936   if (VT != MVT::i64) {
1937     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1938       return false;
1939   } else {
1940     // LDU/STU need an address with at least 4-byte alignment.
1941     if (Alignment < 4)
1942       return false;
1943 
1944     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1945       return false;
1946   }
1947 
1948   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1949     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1950     // sext i32 to i64 when addr mode is r+i.
1951     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1952         LD->getExtensionType() == ISD::SEXTLOAD &&
1953         isa<ConstantSDNode>(Offset))
1954       return false;
1955   }
1956 
1957   AM = ISD::PRE_INC;
1958   return true;
1959 }
1960 
1961 //===----------------------------------------------------------------------===//
1962 //  LowerOperation implementation
1963 //===----------------------------------------------------------------------===//
1964 
1965 /// GetLabelAccessInfo - Return true if we should reference labels using a
1966 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1967 static bool GetLabelAccessInfo(const TargetMachine &TM,
1968                                const PPCSubtarget &Subtarget,
1969                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1970                                const GlobalValue *GV = nullptr) {
1971   HiOpFlags = PPCII::MO_HA;
1972   LoOpFlags = PPCII::MO_LO;
1973 
1974   // Don't use the pic base if not in PIC relocation model.
1975   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1976 
1977   if (isPIC) {
1978     HiOpFlags |= PPCII::MO_PIC_FLAG;
1979     LoOpFlags |= PPCII::MO_PIC_FLAG;
1980   }
1981 
1982   // If this is a reference to a global value that requires a non-lazy-ptr, make
1983   // sure that instruction lowering adds it.
1984   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1985     HiOpFlags |= PPCII::MO_NLP_FLAG;
1986     LoOpFlags |= PPCII::MO_NLP_FLAG;
1987 
1988     if (GV->hasHiddenVisibility()) {
1989       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1990       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1991     }
1992   }
1993 
1994   return isPIC;
1995 }
1996 
1997 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1998                              SelectionDAG &DAG) {
1999   SDLoc DL(HiPart);
2000   EVT PtrVT = HiPart.getValueType();
2001   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2002 
2003   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2004   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2005 
2006   // With PIC, the first instruction is actually "GR+hi(&G)".
2007   if (isPIC)
2008     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2009                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2010 
2011   // Generate non-pic code that has direct accesses to the constant pool.
2012   // The address of the global is just (hi(&g)+lo(&g)).
2013   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2014 }
2015 
2016 static void setUsesTOCBasePtr(MachineFunction &MF) {
2017   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2018   FuncInfo->setUsesTOCBasePtr();
2019 }
2020 
2021 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2022   setUsesTOCBasePtr(DAG.getMachineFunction());
2023 }
2024 
2025 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
2026                            SDValue GA) {
2027   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2028   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2029                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2030 
2031   SDValue Ops[] = { GA, Reg };
2032   return DAG.getMemIntrinsicNode(
2033       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2034       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2035       false, 0);
2036 }
2037 
2038 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2039                                              SelectionDAG &DAG) const {
2040   EVT PtrVT = Op.getValueType();
2041   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2042   const Constant *C = CP->getConstVal();
2043 
2044   // 64-bit SVR4 ABI code is always position-independent.
2045   // The actual address of the GlobalValue is stored in the TOC.
2046   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2047     setUsesTOCBasePtr(DAG);
2048     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2049     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2050   }
2051 
2052   unsigned MOHiFlag, MOLoFlag;
2053   bool isPIC =
2054       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2055 
2056   if (isPIC && Subtarget.isSVR4ABI()) {
2057     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2058                                            PPCII::MO_PIC_FLAG);
2059     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2060   }
2061 
2062   SDValue CPIHi =
2063     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2064   SDValue CPILo =
2065     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2066   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
2067 }
2068 
2069 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2070   EVT PtrVT = Op.getValueType();
2071   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2072 
2073   // 64-bit SVR4 ABI code is always position-independent.
2074   // The actual address of the GlobalValue is stored in the TOC.
2075   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2076     setUsesTOCBasePtr(DAG);
2077     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2078     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2079   }
2080 
2081   unsigned MOHiFlag, MOLoFlag;
2082   bool isPIC =
2083       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2084 
2085   if (isPIC && Subtarget.isSVR4ABI()) {
2086     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2087                                         PPCII::MO_PIC_FLAG);
2088     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2089   }
2090 
2091   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2092   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2093   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
2094 }
2095 
2096 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2097                                              SelectionDAG &DAG) const {
2098   EVT PtrVT = Op.getValueType();
2099   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2100   const BlockAddress *BA = BASDN->getBlockAddress();
2101 
2102   // 64-bit SVR4 ABI code is always position-independent.
2103   // The actual BlockAddress is stored in the TOC.
2104   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2105     setUsesTOCBasePtr(DAG);
2106     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2107     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2108   }
2109 
2110   unsigned MOHiFlag, MOLoFlag;
2111   bool isPIC =
2112       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2113   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2114   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2115   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
2116 }
2117 
2118 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2119                                               SelectionDAG &DAG) const {
2120 
2121   // FIXME: TLS addresses currently use medium model code sequences,
2122   // which is the most useful form.  Eventually support for small and
2123   // large models could be added if users need it, at the cost of
2124   // additional complexity.
2125   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2126   if (DAG.getTarget().Options.EmulatedTLS)
2127     return LowerToTLSEmulatedModel(GA, DAG);
2128 
2129   SDLoc dl(GA);
2130   const GlobalValue *GV = GA->getGlobal();
2131   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2132   bool is64bit = Subtarget.isPPC64();
2133   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2134   PICLevel::Level picLevel = M->getPICLevel();
2135 
2136   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2137 
2138   if (Model == TLSModel::LocalExec) {
2139     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2140                                                PPCII::MO_TPREL_HA);
2141     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2142                                                PPCII::MO_TPREL_LO);
2143     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2144                                      is64bit ? MVT::i64 : MVT::i32);
2145     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2146     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2147   }
2148 
2149   if (Model == TLSModel::InitialExec) {
2150     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2151     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2152                                                 PPCII::MO_TLS);
2153     SDValue GOTPtr;
2154     if (is64bit) {
2155       setUsesTOCBasePtr(DAG);
2156       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2157       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2158                            PtrVT, GOTReg, TGA);
2159     } else
2160       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2161     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2162                                    PtrVT, TGA, GOTPtr);
2163     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2164   }
2165 
2166   if (Model == TLSModel::GeneralDynamic) {
2167     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2168     SDValue GOTPtr;
2169     if (is64bit) {
2170       setUsesTOCBasePtr(DAG);
2171       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2172       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2173                                    GOTReg, TGA);
2174     } else {
2175       if (picLevel == PICLevel::Small)
2176         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2177       else
2178         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2179     }
2180     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2181                        GOTPtr, TGA, TGA);
2182   }
2183 
2184   if (Model == TLSModel::LocalDynamic) {
2185     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2186     SDValue GOTPtr;
2187     if (is64bit) {
2188       setUsesTOCBasePtr(DAG);
2189       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2190       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2191                            GOTReg, TGA);
2192     } else {
2193       if (picLevel == PICLevel::Small)
2194         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2195       else
2196         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2197     }
2198     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2199                                   PtrVT, GOTPtr, TGA, TGA);
2200     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2201                                       PtrVT, TLSAddr, TGA);
2202     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2203   }
2204 
2205   llvm_unreachable("Unknown TLS model!");
2206 }
2207 
2208 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2209                                               SelectionDAG &DAG) const {
2210   EVT PtrVT = Op.getValueType();
2211   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2212   SDLoc DL(GSDN);
2213   const GlobalValue *GV = GSDN->getGlobal();
2214 
2215   // 64-bit SVR4 ABI code is always position-independent.
2216   // The actual address of the GlobalValue is stored in the TOC.
2217   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2218     setUsesTOCBasePtr(DAG);
2219     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2220     return getTOCEntry(DAG, DL, true, GA);
2221   }
2222 
2223   unsigned MOHiFlag, MOLoFlag;
2224   bool isPIC =
2225       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2226 
2227   if (isPIC && Subtarget.isSVR4ABI()) {
2228     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2229                                             GSDN->getOffset(),
2230                                             PPCII::MO_PIC_FLAG);
2231     return getTOCEntry(DAG, DL, false, GA);
2232   }
2233 
2234   SDValue GAHi =
2235     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2236   SDValue GALo =
2237     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2238 
2239   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2240 
2241   // If the global reference is actually to a non-lazy-pointer, we have to do an
2242   // extra load to get the address of the global.
2243   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2244     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2245                       false, false, false, 0);
2246   return Ptr;
2247 }
2248 
2249 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2250   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2251   SDLoc dl(Op);
2252 
2253   if (Op.getValueType() == MVT::v2i64) {
2254     // When the operands themselves are v2i64 values, we need to do something
2255     // special because VSX has no underlying comparison operations for these.
2256     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2257       // Equality can be handled by casting to the legal type for Altivec
2258       // comparisons, everything else needs to be expanded.
2259       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2260         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2261                  DAG.getSetCC(dl, MVT::v4i32,
2262                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2263                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2264                    CC));
2265       }
2266 
2267       return SDValue();
2268     }
2269 
2270     // We handle most of these in the usual way.
2271     return Op;
2272   }
2273 
2274   // If we're comparing for equality to zero, expose the fact that this is
2275   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2276   // fold the new nodes.
2277   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2278     if (C->isNullValue() && CC == ISD::SETEQ) {
2279       EVT VT = Op.getOperand(0).getValueType();
2280       SDValue Zext = Op.getOperand(0);
2281       if (VT.bitsLT(MVT::i32)) {
2282         VT = MVT::i32;
2283         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2284       }
2285       unsigned Log2b = Log2_32(VT.getSizeInBits());
2286       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2287       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2288                                 DAG.getConstant(Log2b, dl, MVT::i32));
2289       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2290     }
2291     // Leave comparisons against 0 and -1 alone for now, since they're usually
2292     // optimized.  FIXME: revisit this when we can custom lower all setcc
2293     // optimizations.
2294     if (C->isAllOnesValue() || C->isNullValue())
2295       return SDValue();
2296   }
2297 
2298   // If we have an integer seteq/setne, turn it into a compare against zero
2299   // by xor'ing the rhs with the lhs, which is faster than setting a
2300   // condition register, reading it back out, and masking the correct bit.  The
2301   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2302   // the result to other bit-twiddling opportunities.
2303   EVT LHSVT = Op.getOperand(0).getValueType();
2304   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2305     EVT VT = Op.getValueType();
2306     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2307                                 Op.getOperand(1));
2308     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2309   }
2310   return SDValue();
2311 }
2312 
2313 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2314                                       const PPCSubtarget &Subtarget) const {
2315   SDNode *Node = Op.getNode();
2316   EVT VT = Node->getValueType(0);
2317   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2318   SDValue InChain = Node->getOperand(0);
2319   SDValue VAListPtr = Node->getOperand(1);
2320   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2321   SDLoc dl(Node);
2322 
2323   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2324 
2325   // gpr_index
2326   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2327                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2328                                     false, false, false, 0);
2329   InChain = GprIndex.getValue(1);
2330 
2331   if (VT == MVT::i64) {
2332     // Check if GprIndex is even
2333     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2334                                  DAG.getConstant(1, dl, MVT::i32));
2335     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2336                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2337     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2338                                           DAG.getConstant(1, dl, MVT::i32));
2339     // Align GprIndex to be even if it isn't
2340     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2341                            GprIndex);
2342   }
2343 
2344   // fpr index is 1 byte after gpr
2345   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2346                                DAG.getConstant(1, dl, MVT::i32));
2347 
2348   // fpr
2349   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2350                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2351                                     false, false, false, 0);
2352   InChain = FprIndex.getValue(1);
2353 
2354   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2355                                        DAG.getConstant(8, dl, MVT::i32));
2356 
2357   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2358                                         DAG.getConstant(4, dl, MVT::i32));
2359 
2360   // areas
2361   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2362                                      MachinePointerInfo(), false, false,
2363                                      false, 0);
2364   InChain = OverflowArea.getValue(1);
2365 
2366   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2367                                     MachinePointerInfo(), false, false,
2368                                     false, 0);
2369   InChain = RegSaveArea.getValue(1);
2370 
2371   // select overflow_area if index > 8
2372   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2373                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2374 
2375   // adjustment constant gpr_index * 4/8
2376   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2377                                     VT.isInteger() ? GprIndex : FprIndex,
2378                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2379                                                     MVT::i32));
2380 
2381   // OurReg = RegSaveArea + RegConstant
2382   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2383                                RegConstant);
2384 
2385   // Floating types are 32 bytes into RegSaveArea
2386   if (VT.isFloatingPoint())
2387     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2388                          DAG.getConstant(32, dl, MVT::i32));
2389 
2390   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2391   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2392                                    VT.isInteger() ? GprIndex : FprIndex,
2393                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2394                                                    MVT::i32));
2395 
2396   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2397                               VT.isInteger() ? VAListPtr : FprPtr,
2398                               MachinePointerInfo(SV),
2399                               MVT::i8, false, false, 0);
2400 
2401   // determine if we should load from reg_save_area or overflow_area
2402   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2403 
2404   // increase overflow_area by 4/8 if gpr/fpr > 8
2405   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2406                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2407                                           dl, MVT::i32));
2408 
2409   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2410                              OverflowAreaPlusN);
2411 
2412   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2413                               OverflowAreaPtr,
2414                               MachinePointerInfo(),
2415                               MVT::i32, false, false, 0);
2416 
2417   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2418                      false, false, false, 0);
2419 }
2420 
2421 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2422                                        const PPCSubtarget &Subtarget) const {
2423   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2424 
2425   // We have to copy the entire va_list struct:
2426   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2427   return DAG.getMemcpy(Op.getOperand(0), Op,
2428                        Op.getOperand(1), Op.getOperand(2),
2429                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2430                        false, MachinePointerInfo(), MachinePointerInfo());
2431 }
2432 
2433 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2434                                                   SelectionDAG &DAG) const {
2435   return Op.getOperand(0);
2436 }
2437 
2438 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2439                                                 SelectionDAG &DAG) const {
2440   SDValue Chain = Op.getOperand(0);
2441   SDValue Trmp = Op.getOperand(1); // trampoline
2442   SDValue FPtr = Op.getOperand(2); // nested function
2443   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2444   SDLoc dl(Op);
2445 
2446   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2447   bool isPPC64 = (PtrVT == MVT::i64);
2448   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2449 
2450   TargetLowering::ArgListTy Args;
2451   TargetLowering::ArgListEntry Entry;
2452 
2453   Entry.Ty = IntPtrTy;
2454   Entry.Node = Trmp; Args.push_back(Entry);
2455 
2456   // TrampSize == (isPPC64 ? 48 : 40);
2457   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2458                                isPPC64 ? MVT::i64 : MVT::i32);
2459   Args.push_back(Entry);
2460 
2461   Entry.Node = FPtr; Args.push_back(Entry);
2462   Entry.Node = Nest; Args.push_back(Entry);
2463 
2464   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2465   TargetLowering::CallLoweringInfo CLI(DAG);
2466   CLI.setDebugLoc(dl).setChain(Chain)
2467     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2468                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2469                std::move(Args), 0);
2470 
2471   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2472   return CallResult.second;
2473 }
2474 
2475 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2476                                         const PPCSubtarget &Subtarget) const {
2477   MachineFunction &MF = DAG.getMachineFunction();
2478   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2479 
2480   SDLoc dl(Op);
2481 
2482   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2483     // vastart just stores the address of the VarArgsFrameIndex slot into the
2484     // memory location argument.
2485     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2486     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2487     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2488     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2489                         MachinePointerInfo(SV),
2490                         false, false, 0);
2491   }
2492 
2493   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2494   // We suppose the given va_list is already allocated.
2495   //
2496   // typedef struct {
2497   //  char gpr;     /* index into the array of 8 GPRs
2498   //                 * stored in the register save area
2499   //                 * gpr=0 corresponds to r3,
2500   //                 * gpr=1 to r4, etc.
2501   //                 */
2502   //  char fpr;     /* index into the array of 8 FPRs
2503   //                 * stored in the register save area
2504   //                 * fpr=0 corresponds to f1,
2505   //                 * fpr=1 to f2, etc.
2506   //                 */
2507   //  char *overflow_arg_area;
2508   //                /* location on stack that holds
2509   //                 * the next overflow argument
2510   //                 */
2511   //  char *reg_save_area;
2512   //               /* where r3:r10 and f1:f8 (if saved)
2513   //                * are stored
2514   //                */
2515   // } va_list[1];
2516 
2517   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2518   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2519 
2520   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2521 
2522   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2523                                             PtrVT);
2524   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2525                                  PtrVT);
2526 
2527   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2528   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2529 
2530   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2531   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2532 
2533   uint64_t FPROffset = 1;
2534   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2535 
2536   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2537 
2538   // Store first byte : number of int regs
2539   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2540                                          Op.getOperand(1),
2541                                          MachinePointerInfo(SV),
2542                                          MVT::i8, false, false, 0);
2543   uint64_t nextOffset = FPROffset;
2544   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2545                                   ConstFPROffset);
2546 
2547   // Store second byte : number of float regs
2548   SDValue secondStore =
2549     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2550                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2551                       false, false, 0);
2552   nextOffset += StackOffset;
2553   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2554 
2555   // Store second word : arguments given on stack
2556   SDValue thirdStore =
2557     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2558                  MachinePointerInfo(SV, nextOffset),
2559                  false, false, 0);
2560   nextOffset += FrameOffset;
2561   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2562 
2563   // Store third word : arguments given in registers
2564   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2565                       MachinePointerInfo(SV, nextOffset),
2566                       false, false, 0);
2567 
2568 }
2569 
2570 #include "PPCGenCallingConv.inc"
2571 
2572 // Function whose sole purpose is to kill compiler warnings
2573 // stemming from unused functions included from PPCGenCallingConv.inc.
2574 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2575   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2576 }
2577 
2578 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2579                                       CCValAssign::LocInfo &LocInfo,
2580                                       ISD::ArgFlagsTy &ArgFlags,
2581                                       CCState &State) {
2582   return true;
2583 }
2584 
2585 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2586                                              MVT &LocVT,
2587                                              CCValAssign::LocInfo &LocInfo,
2588                                              ISD::ArgFlagsTy &ArgFlags,
2589                                              CCState &State) {
2590   static const MCPhysReg ArgRegs[] = {
2591     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2592     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2593   };
2594   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2595 
2596   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2597 
2598   // Skip one register if the first unallocated register has an even register
2599   // number and there are still argument registers available which have not been
2600   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2601   // need to skip a register if RegNum is odd.
2602   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2603     State.AllocateReg(ArgRegs[RegNum]);
2604   }
2605 
2606   // Always return false here, as this function only makes sure that the first
2607   // unallocated register has an odd register number and does not actually
2608   // allocate a register for the current argument.
2609   return false;
2610 }
2611 
2612 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2613                                                MVT &LocVT,
2614                                                CCValAssign::LocInfo &LocInfo,
2615                                                ISD::ArgFlagsTy &ArgFlags,
2616                                                CCState &State) {
2617   static const MCPhysReg ArgRegs[] = {
2618     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2619     PPC::F8
2620   };
2621 
2622   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2623 
2624   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2625 
2626   // If there is only one Floating-point register left we need to put both f64
2627   // values of a split ppc_fp128 value on the stack.
2628   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2629     State.AllocateReg(ArgRegs[RegNum]);
2630   }
2631 
2632   // Always return false here, as this function only makes sure that the two f64
2633   // values a ppc_fp128 value is split into are both passed in registers or both
2634   // passed on the stack and does not actually allocate a register for the
2635   // current argument.
2636   return false;
2637 }
2638 
2639 /// FPR - The set of FP registers that should be allocated for arguments,
2640 /// on Darwin.
2641 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2642                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2643                                 PPC::F11, PPC::F12, PPC::F13};
2644 
2645 /// QFPR - The set of QPX registers that should be allocated for arguments.
2646 static const MCPhysReg QFPR[] = {
2647     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2648     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2649 
2650 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2651 /// the stack.
2652 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2653                                        unsigned PtrByteSize) {
2654   unsigned ArgSize = ArgVT.getStoreSize();
2655   if (Flags.isByVal())
2656     ArgSize = Flags.getByValSize();
2657 
2658   // Round up to multiples of the pointer size, except for array members,
2659   // which are always packed.
2660   if (!Flags.isInConsecutiveRegs())
2661     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2662 
2663   return ArgSize;
2664 }
2665 
2666 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2667 /// on the stack.
2668 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2669                                             ISD::ArgFlagsTy Flags,
2670                                             unsigned PtrByteSize) {
2671   unsigned Align = PtrByteSize;
2672 
2673   // Altivec parameters are padded to a 16 byte boundary.
2674   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2675       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2676       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2677       ArgVT == MVT::v1i128)
2678     Align = 16;
2679   // QPX vector types stored in double-precision are padded to a 32 byte
2680   // boundary.
2681   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2682     Align = 32;
2683 
2684   // ByVal parameters are aligned as requested.
2685   if (Flags.isByVal()) {
2686     unsigned BVAlign = Flags.getByValAlign();
2687     if (BVAlign > PtrByteSize) {
2688       if (BVAlign % PtrByteSize != 0)
2689           llvm_unreachable(
2690             "ByVal alignment is not a multiple of the pointer size");
2691 
2692       Align = BVAlign;
2693     }
2694   }
2695 
2696   // Array members are always packed to their original alignment.
2697   if (Flags.isInConsecutiveRegs()) {
2698     // If the array member was split into multiple registers, the first
2699     // needs to be aligned to the size of the full type.  (Except for
2700     // ppcf128, which is only aligned as its f64 components.)
2701     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2702       Align = OrigVT.getStoreSize();
2703     else
2704       Align = ArgVT.getStoreSize();
2705   }
2706 
2707   return Align;
2708 }
2709 
2710 /// CalculateStackSlotUsed - Return whether this argument will use its
2711 /// stack slot (instead of being passed in registers).  ArgOffset,
2712 /// AvailableFPRs, and AvailableVRs must hold the current argument
2713 /// position, and will be updated to account for this argument.
2714 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2715                                    ISD::ArgFlagsTy Flags,
2716                                    unsigned PtrByteSize,
2717                                    unsigned LinkageSize,
2718                                    unsigned ParamAreaSize,
2719                                    unsigned &ArgOffset,
2720                                    unsigned &AvailableFPRs,
2721                                    unsigned &AvailableVRs, bool HasQPX) {
2722   bool UseMemory = false;
2723 
2724   // Respect alignment of argument on the stack.
2725   unsigned Align =
2726     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2727   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2728   // If there's no space left in the argument save area, we must
2729   // use memory (this check also catches zero-sized arguments).
2730   if (ArgOffset >= LinkageSize + ParamAreaSize)
2731     UseMemory = true;
2732 
2733   // Allocate argument on the stack.
2734   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2735   if (Flags.isInConsecutiveRegsLast())
2736     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2737   // If we overran the argument save area, we must use memory
2738   // (this check catches arguments passed partially in memory)
2739   if (ArgOffset > LinkageSize + ParamAreaSize)
2740     UseMemory = true;
2741 
2742   // However, if the argument is actually passed in an FPR or a VR,
2743   // we don't use memory after all.
2744   if (!Flags.isByVal()) {
2745     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2746         // QPX registers overlap with the scalar FP registers.
2747         (HasQPX && (ArgVT == MVT::v4f32 ||
2748                     ArgVT == MVT::v4f64 ||
2749                     ArgVT == MVT::v4i1)))
2750       if (AvailableFPRs > 0) {
2751         --AvailableFPRs;
2752         return false;
2753       }
2754     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2755         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2756         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2757         ArgVT == MVT::v1i128)
2758       if (AvailableVRs > 0) {
2759         --AvailableVRs;
2760         return false;
2761       }
2762   }
2763 
2764   return UseMemory;
2765 }
2766 
2767 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2768 /// ensure minimum alignment required for target.
2769 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2770                                      unsigned NumBytes) {
2771   unsigned TargetAlign = Lowering->getStackAlignment();
2772   unsigned AlignMask = TargetAlign - 1;
2773   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2774   return NumBytes;
2775 }
2776 
2777 SDValue
2778 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2779                                         CallingConv::ID CallConv, bool isVarArg,
2780                                         const SmallVectorImpl<ISD::InputArg>
2781                                           &Ins,
2782                                         SDLoc dl, SelectionDAG &DAG,
2783                                         SmallVectorImpl<SDValue> &InVals)
2784                                           const {
2785   if (Subtarget.isSVR4ABI()) {
2786     if (Subtarget.isPPC64())
2787       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2788                                          dl, DAG, InVals);
2789     else
2790       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2791                                          dl, DAG, InVals);
2792   } else {
2793     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2794                                        dl, DAG, InVals);
2795   }
2796 }
2797 
2798 SDValue
2799 PPCTargetLowering::LowerFormalArguments_32SVR4(
2800                                       SDValue Chain,
2801                                       CallingConv::ID CallConv, bool isVarArg,
2802                                       const SmallVectorImpl<ISD::InputArg>
2803                                         &Ins,
2804                                       SDLoc dl, SelectionDAG &DAG,
2805                                       SmallVectorImpl<SDValue> &InVals) const {
2806 
2807   // 32-bit SVR4 ABI Stack Frame Layout:
2808   //              +-----------------------------------+
2809   //        +-->  |            Back chain             |
2810   //        |     +-----------------------------------+
2811   //        |     | Floating-point register save area |
2812   //        |     +-----------------------------------+
2813   //        |     |    General register save area     |
2814   //        |     +-----------------------------------+
2815   //        |     |          CR save word             |
2816   //        |     +-----------------------------------+
2817   //        |     |         VRSAVE save word          |
2818   //        |     +-----------------------------------+
2819   //        |     |         Alignment padding         |
2820   //        |     +-----------------------------------+
2821   //        |     |     Vector register save area     |
2822   //        |     +-----------------------------------+
2823   //        |     |       Local variable space        |
2824   //        |     +-----------------------------------+
2825   //        |     |        Parameter list area        |
2826   //        |     +-----------------------------------+
2827   //        |     |           LR save word            |
2828   //        |     +-----------------------------------+
2829   // SP-->  +---  |            Back chain             |
2830   //              +-----------------------------------+
2831   //
2832   // Specifications:
2833   //   System V Application Binary Interface PowerPC Processor Supplement
2834   //   AltiVec Technology Programming Interface Manual
2835 
2836   MachineFunction &MF = DAG.getMachineFunction();
2837   MachineFrameInfo *MFI = MF.getFrameInfo();
2838   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2839 
2840   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2841   // Potential tail calls could cause overwriting of argument stack slots.
2842   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2843                        (CallConv == CallingConv::Fast));
2844   unsigned PtrByteSize = 4;
2845 
2846   // Assign locations to all of the incoming arguments.
2847   SmallVector<CCValAssign, 16> ArgLocs;
2848   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2849                  *DAG.getContext());
2850 
2851   // Reserve space for the linkage area on the stack.
2852   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2853   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2854   if (Subtarget.useSoftFloat())
2855     CCInfo.PreAnalyzeFormalArguments(Ins);
2856 
2857   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2858   CCInfo.clearWasPPCF128();
2859 
2860   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2861     CCValAssign &VA = ArgLocs[i];
2862 
2863     // Arguments stored in registers.
2864     if (VA.isRegLoc()) {
2865       const TargetRegisterClass *RC;
2866       EVT ValVT = VA.getValVT();
2867 
2868       switch (ValVT.getSimpleVT().SimpleTy) {
2869         default:
2870           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2871         case MVT::i1:
2872         case MVT::i32:
2873           RC = &PPC::GPRCRegClass;
2874           break;
2875         case MVT::f32:
2876           if (Subtarget.hasP8Vector())
2877             RC = &PPC::VSSRCRegClass;
2878           else
2879             RC = &PPC::F4RCRegClass;
2880           break;
2881         case MVT::f64:
2882           if (Subtarget.hasVSX())
2883             RC = &PPC::VSFRCRegClass;
2884           else
2885             RC = &PPC::F8RCRegClass;
2886           break;
2887         case MVT::v16i8:
2888         case MVT::v8i16:
2889         case MVT::v4i32:
2890           RC = &PPC::VRRCRegClass;
2891           break;
2892         case MVT::v4f32:
2893           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2894           break;
2895         case MVT::v2f64:
2896         case MVT::v2i64:
2897           RC = &PPC::VSHRCRegClass;
2898           break;
2899         case MVT::v4f64:
2900           RC = &PPC::QFRCRegClass;
2901           break;
2902         case MVT::v4i1:
2903           RC = &PPC::QBRCRegClass;
2904           break;
2905       }
2906 
2907       // Transform the arguments stored in physical registers into virtual ones.
2908       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2909       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2910                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2911 
2912       if (ValVT == MVT::i1)
2913         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2914 
2915       InVals.push_back(ArgValue);
2916     } else {
2917       // Argument stored in memory.
2918       assert(VA.isMemLoc());
2919 
2920       unsigned ArgSize = VA.getLocVT().getStoreSize();
2921       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2922                                       isImmutable);
2923 
2924       // Create load nodes to retrieve arguments from the stack.
2925       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2926       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2927                                    MachinePointerInfo(),
2928                                    false, false, false, 0));
2929     }
2930   }
2931 
2932   // Assign locations to all of the incoming aggregate by value arguments.
2933   // Aggregates passed by value are stored in the local variable space of the
2934   // caller's stack frame, right above the parameter list area.
2935   SmallVector<CCValAssign, 16> ByValArgLocs;
2936   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2937                       ByValArgLocs, *DAG.getContext());
2938 
2939   // Reserve stack space for the allocations in CCInfo.
2940   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2941 
2942   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2943 
2944   // Area that is at least reserved in the caller of this function.
2945   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2946   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2947 
2948   // Set the size that is at least reserved in caller of this function.  Tail
2949   // call optimized function's reserved stack space needs to be aligned so that
2950   // taking the difference between two stack areas will result in an aligned
2951   // stack.
2952   MinReservedArea =
2953       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2954   FuncInfo->setMinReservedArea(MinReservedArea);
2955 
2956   SmallVector<SDValue, 8> MemOps;
2957 
2958   // If the function takes variable number of arguments, make a frame index for
2959   // the start of the first vararg value... for expansion of llvm.va_start.
2960   if (isVarArg) {
2961     static const MCPhysReg GPArgRegs[] = {
2962       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2963       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2964     };
2965     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2966 
2967     static const MCPhysReg FPArgRegs[] = {
2968       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2969       PPC::F8
2970     };
2971     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2972 
2973     if (Subtarget.useSoftFloat())
2974        NumFPArgRegs = 0;
2975 
2976     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2977     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2978 
2979     // Make room for NumGPArgRegs and NumFPArgRegs.
2980     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2981                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2982 
2983     FuncInfo->setVarArgsStackOffset(
2984       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2985                              CCInfo.getNextStackOffset(), true));
2986 
2987     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2988     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2989 
2990     // The fixed integer arguments of a variadic function are stored to the
2991     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2992     // the result of va_next.
2993     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2994       // Get an existing live-in vreg, or add a new one.
2995       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2996       if (!VReg)
2997         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2998 
2999       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3000       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3001                                    MachinePointerInfo(), false, false, 0);
3002       MemOps.push_back(Store);
3003       // Increment the address by four for the next argument to store
3004       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3005       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3006     }
3007 
3008     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3009     // is set.
3010     // The double arguments are stored to the VarArgsFrameIndex
3011     // on the stack.
3012     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3013       // Get an existing live-in vreg, or add a new one.
3014       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3015       if (!VReg)
3016         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3017 
3018       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3019       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3020                                    MachinePointerInfo(), false, false, 0);
3021       MemOps.push_back(Store);
3022       // Increment the address by eight for the next argument to store
3023       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3024                                          PtrVT);
3025       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3026     }
3027   }
3028 
3029   if (!MemOps.empty())
3030     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3031 
3032   return Chain;
3033 }
3034 
3035 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3036 // value to MVT::i64 and then truncate to the correct register size.
3037 SDValue
3038 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
3039                                      SelectionDAG &DAG, SDValue ArgVal,
3040                                      SDLoc dl) const {
3041   if (Flags.isSExt())
3042     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3043                          DAG.getValueType(ObjectVT));
3044   else if (Flags.isZExt())
3045     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3046                          DAG.getValueType(ObjectVT));
3047 
3048   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3049 }
3050 
3051 SDValue
3052 PPCTargetLowering::LowerFormalArguments_64SVR4(
3053                                       SDValue Chain,
3054                                       CallingConv::ID CallConv, bool isVarArg,
3055                                       const SmallVectorImpl<ISD::InputArg>
3056                                         &Ins,
3057                                       SDLoc dl, SelectionDAG &DAG,
3058                                       SmallVectorImpl<SDValue> &InVals) const {
3059   // TODO: add description of PPC stack frame format, or at least some docs.
3060   //
3061   bool isELFv2ABI = Subtarget.isELFv2ABI();
3062   bool isLittleEndian = Subtarget.isLittleEndian();
3063   MachineFunction &MF = DAG.getMachineFunction();
3064   MachineFrameInfo *MFI = MF.getFrameInfo();
3065   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3066 
3067   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3068          "fastcc not supported on varargs functions");
3069 
3070   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3071   // Potential tail calls could cause overwriting of argument stack slots.
3072   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3073                        (CallConv == CallingConv::Fast));
3074   unsigned PtrByteSize = 8;
3075   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3076 
3077   static const MCPhysReg GPR[] = {
3078     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3079     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3080   };
3081   static const MCPhysReg VR[] = {
3082     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3083     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3084   };
3085   static const MCPhysReg VSRH[] = {
3086     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3087     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3088   };
3089 
3090   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3091   const unsigned Num_FPR_Regs = 13;
3092   const unsigned Num_VR_Regs  = array_lengthof(VR);
3093   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3094 
3095   // Do a first pass over the arguments to determine whether the ABI
3096   // guarantees that our caller has allocated the parameter save area
3097   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3098   // in the ELFv2 ABI, it is true if this is a vararg function or if
3099   // any parameter is located in a stack slot.
3100 
3101   bool HasParameterArea = !isELFv2ABI || isVarArg;
3102   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3103   unsigned NumBytes = LinkageSize;
3104   unsigned AvailableFPRs = Num_FPR_Regs;
3105   unsigned AvailableVRs = Num_VR_Regs;
3106   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3107     if (Ins[i].Flags.isNest())
3108       continue;
3109 
3110     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3111                                PtrByteSize, LinkageSize, ParamAreaSize,
3112                                NumBytes, AvailableFPRs, AvailableVRs,
3113                                Subtarget.hasQPX()))
3114       HasParameterArea = true;
3115   }
3116 
3117   // Add DAG nodes to load the arguments or copy them out of registers.  On
3118   // entry to a function on PPC, the arguments start after the linkage area,
3119   // although the first ones are often in registers.
3120 
3121   unsigned ArgOffset = LinkageSize;
3122   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3123   unsigned &QFPR_idx = FPR_idx;
3124   SmallVector<SDValue, 8> MemOps;
3125   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3126   unsigned CurArgIdx = 0;
3127   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3128     SDValue ArgVal;
3129     bool needsLoad = false;
3130     EVT ObjectVT = Ins[ArgNo].VT;
3131     EVT OrigVT = Ins[ArgNo].ArgVT;
3132     unsigned ObjSize = ObjectVT.getStoreSize();
3133     unsigned ArgSize = ObjSize;
3134     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3135     if (Ins[ArgNo].isOrigArg()) {
3136       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3137       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3138     }
3139     // We re-align the argument offset for each argument, except when using the
3140     // fast calling convention, when we need to make sure we do that only when
3141     // we'll actually use a stack slot.
3142     unsigned CurArgOffset, Align;
3143     auto ComputeArgOffset = [&]() {
3144       /* Respect alignment of argument on the stack.  */
3145       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3146       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3147       CurArgOffset = ArgOffset;
3148     };
3149 
3150     if (CallConv != CallingConv::Fast) {
3151       ComputeArgOffset();
3152 
3153       /* Compute GPR index associated with argument offset.  */
3154       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3155       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3156     }
3157 
3158     // FIXME the codegen can be much improved in some cases.
3159     // We do not have to keep everything in memory.
3160     if (Flags.isByVal()) {
3161       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3162 
3163       if (CallConv == CallingConv::Fast)
3164         ComputeArgOffset();
3165 
3166       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3167       ObjSize = Flags.getByValSize();
3168       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3169       // Empty aggregate parameters do not take up registers.  Examples:
3170       //   struct { } a;
3171       //   union  { } b;
3172       //   int c[0];
3173       // etc.  However, we have to provide a place-holder in InVals, so
3174       // pretend we have an 8-byte item at the current address for that
3175       // purpose.
3176       if (!ObjSize) {
3177         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3178         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3179         InVals.push_back(FIN);
3180         continue;
3181       }
3182 
3183       // Create a stack object covering all stack doublewords occupied
3184       // by the argument.  If the argument is (fully or partially) on
3185       // the stack, or if the argument is fully in registers but the
3186       // caller has allocated the parameter save anyway, we can refer
3187       // directly to the caller's stack frame.  Otherwise, create a
3188       // local copy in our own frame.
3189       int FI;
3190       if (HasParameterArea ||
3191           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3192         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3193       else
3194         FI = MFI->CreateStackObject(ArgSize, Align, false);
3195       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3196 
3197       // Handle aggregates smaller than 8 bytes.
3198       if (ObjSize < PtrByteSize) {
3199         // The value of the object is its address, which differs from the
3200         // address of the enclosing doubleword on big-endian systems.
3201         SDValue Arg = FIN;
3202         if (!isLittleEndian) {
3203           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3204           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3205         }
3206         InVals.push_back(Arg);
3207 
3208         if (GPR_idx != Num_GPR_Regs) {
3209           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3210           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3211           SDValue Store;
3212 
3213           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3214             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3215                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3216             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3217                                       MachinePointerInfo(&*FuncArg), ObjType,
3218                                       false, false, 0);
3219           } else {
3220             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3221             // store the whole register as-is to the parameter save area
3222             // slot.
3223             Store =
3224                 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3225                              MachinePointerInfo(&*FuncArg), false, false, 0);
3226           }
3227 
3228           MemOps.push_back(Store);
3229         }
3230         // Whether we copied from a register or not, advance the offset
3231         // into the parameter save area by a full doubleword.
3232         ArgOffset += PtrByteSize;
3233         continue;
3234       }
3235 
3236       // The value of the object is its address, which is the address of
3237       // its first stack doubleword.
3238       InVals.push_back(FIN);
3239 
3240       // Store whatever pieces of the object are in registers to memory.
3241       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3242         if (GPR_idx == Num_GPR_Regs)
3243           break;
3244 
3245         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3246         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3247         SDValue Addr = FIN;
3248         if (j) {
3249           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3250           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3251         }
3252         SDValue Store =
3253             DAG.getStore(Val.getValue(1), dl, Val, Addr,
3254                          MachinePointerInfo(&*FuncArg, j), false, false, 0);
3255         MemOps.push_back(Store);
3256         ++GPR_idx;
3257       }
3258       ArgOffset += ArgSize;
3259       continue;
3260     }
3261 
3262     switch (ObjectVT.getSimpleVT().SimpleTy) {
3263     default: llvm_unreachable("Unhandled argument type!");
3264     case MVT::i1:
3265     case MVT::i32:
3266     case MVT::i64:
3267       if (Flags.isNest()) {
3268         // The 'nest' parameter, if any, is passed in R11.
3269         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3270         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3271 
3272         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3273           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3274 
3275         break;
3276       }
3277 
3278       // These can be scalar arguments or elements of an integer array type
3279       // passed directly.  Clang may use those instead of "byval" aggregate
3280       // types to avoid forcing arguments to memory unnecessarily.
3281       if (GPR_idx != Num_GPR_Regs) {
3282         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3283         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3284 
3285         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3286           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3287           // value to MVT::i64 and then truncate to the correct register size.
3288           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3289       } else {
3290         if (CallConv == CallingConv::Fast)
3291           ComputeArgOffset();
3292 
3293         needsLoad = true;
3294         ArgSize = PtrByteSize;
3295       }
3296       if (CallConv != CallingConv::Fast || needsLoad)
3297         ArgOffset += 8;
3298       break;
3299 
3300     case MVT::f32:
3301     case MVT::f64:
3302       // These can be scalar arguments or elements of a float array type
3303       // passed directly.  The latter are used to implement ELFv2 homogenous
3304       // float aggregates.
3305       if (FPR_idx != Num_FPR_Regs) {
3306         unsigned VReg;
3307 
3308         if (ObjectVT == MVT::f32)
3309           VReg = MF.addLiveIn(FPR[FPR_idx],
3310                               Subtarget.hasP8Vector()
3311                                   ? &PPC::VSSRCRegClass
3312                                   : &PPC::F4RCRegClass);
3313         else
3314           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3315                                                 ? &PPC::VSFRCRegClass
3316                                                 : &PPC::F8RCRegClass);
3317 
3318         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3319         ++FPR_idx;
3320       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3321         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3322         // once we support fp <-> gpr moves.
3323 
3324         // This can only ever happen in the presence of f32 array types,
3325         // since otherwise we never run out of FPRs before running out
3326         // of GPRs.
3327         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3328         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3329 
3330         if (ObjectVT == MVT::f32) {
3331           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3332             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3333                                  DAG.getConstant(32, dl, MVT::i32));
3334           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3335         }
3336 
3337         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3338       } else {
3339         if (CallConv == CallingConv::Fast)
3340           ComputeArgOffset();
3341 
3342         needsLoad = true;
3343       }
3344 
3345       // When passing an array of floats, the array occupies consecutive
3346       // space in the argument area; only round up to the next doubleword
3347       // at the end of the array.  Otherwise, each float takes 8 bytes.
3348       if (CallConv != CallingConv::Fast || needsLoad) {
3349         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3350         ArgOffset += ArgSize;
3351         if (Flags.isInConsecutiveRegsLast())
3352           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3353       }
3354       break;
3355     case MVT::v4f32:
3356     case MVT::v4i32:
3357     case MVT::v8i16:
3358     case MVT::v16i8:
3359     case MVT::v2f64:
3360     case MVT::v2i64:
3361     case MVT::v1i128:
3362       if (!Subtarget.hasQPX()) {
3363       // These can be scalar arguments or elements of a vector array type
3364       // passed directly.  The latter are used to implement ELFv2 homogenous
3365       // vector aggregates.
3366       if (VR_idx != Num_VR_Regs) {
3367         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3368                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3369                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3370         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3371         ++VR_idx;
3372       } else {
3373         if (CallConv == CallingConv::Fast)
3374           ComputeArgOffset();
3375 
3376         needsLoad = true;
3377       }
3378       if (CallConv != CallingConv::Fast || needsLoad)
3379         ArgOffset += 16;
3380       break;
3381       } // not QPX
3382 
3383       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3384              "Invalid QPX parameter type");
3385       /* fall through */
3386 
3387     case MVT::v4f64:
3388     case MVT::v4i1:
3389       // QPX vectors are treated like their scalar floating-point subregisters
3390       // (except that they're larger).
3391       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3392       if (QFPR_idx != Num_QFPR_Regs) {
3393         const TargetRegisterClass *RC;
3394         switch (ObjectVT.getSimpleVT().SimpleTy) {
3395         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3396         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3397         default:         RC = &PPC::QBRCRegClass; break;
3398         }
3399 
3400         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3401         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3402         ++QFPR_idx;
3403       } else {
3404         if (CallConv == CallingConv::Fast)
3405           ComputeArgOffset();
3406         needsLoad = true;
3407       }
3408       if (CallConv != CallingConv::Fast || needsLoad)
3409         ArgOffset += Sz;
3410       break;
3411     }
3412 
3413     // We need to load the argument to a virtual register if we determined
3414     // above that we ran out of physical registers of the appropriate type.
3415     if (needsLoad) {
3416       if (ObjSize < ArgSize && !isLittleEndian)
3417         CurArgOffset += ArgSize - ObjSize;
3418       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3419       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3420       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3421                            false, false, false, 0);
3422     }
3423 
3424     InVals.push_back(ArgVal);
3425   }
3426 
3427   // Area that is at least reserved in the caller of this function.
3428   unsigned MinReservedArea;
3429   if (HasParameterArea)
3430     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3431   else
3432     MinReservedArea = LinkageSize;
3433 
3434   // Set the size that is at least reserved in caller of this function.  Tail
3435   // call optimized functions' reserved stack space needs to be aligned so that
3436   // taking the difference between two stack areas will result in an aligned
3437   // stack.
3438   MinReservedArea =
3439       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3440   FuncInfo->setMinReservedArea(MinReservedArea);
3441 
3442   // If the function takes variable number of arguments, make a frame index for
3443   // the start of the first vararg value... for expansion of llvm.va_start.
3444   if (isVarArg) {
3445     int Depth = ArgOffset;
3446 
3447     FuncInfo->setVarArgsFrameIndex(
3448       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3449     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3450 
3451     // If this function is vararg, store any remaining integer argument regs
3452     // to their spots on the stack so that they may be loaded by deferencing the
3453     // result of va_next.
3454     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3455          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3456       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3457       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3458       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3459                                    MachinePointerInfo(), false, false, 0);
3460       MemOps.push_back(Store);
3461       // Increment the address by four for the next argument to store
3462       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3463       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3464     }
3465   }
3466 
3467   if (!MemOps.empty())
3468     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3469 
3470   return Chain;
3471 }
3472 
3473 SDValue
3474 PPCTargetLowering::LowerFormalArguments_Darwin(
3475                                       SDValue Chain,
3476                                       CallingConv::ID CallConv, bool isVarArg,
3477                                       const SmallVectorImpl<ISD::InputArg>
3478                                         &Ins,
3479                                       SDLoc dl, SelectionDAG &DAG,
3480                                       SmallVectorImpl<SDValue> &InVals) const {
3481   // TODO: add description of PPC stack frame format, or at least some docs.
3482   //
3483   MachineFunction &MF = DAG.getMachineFunction();
3484   MachineFrameInfo *MFI = MF.getFrameInfo();
3485   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3486 
3487   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3488   bool isPPC64 = PtrVT == MVT::i64;
3489   // Potential tail calls could cause overwriting of argument stack slots.
3490   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3491                        (CallConv == CallingConv::Fast));
3492   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3493   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3494   unsigned ArgOffset = LinkageSize;
3495   // Area that is at least reserved in caller of this function.
3496   unsigned MinReservedArea = ArgOffset;
3497 
3498   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3499     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3500     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3501   };
3502   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3503     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3504     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3505   };
3506   static const MCPhysReg VR[] = {
3507     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3508     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3509   };
3510 
3511   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3512   const unsigned Num_FPR_Regs = 13;
3513   const unsigned Num_VR_Regs  = array_lengthof( VR);
3514 
3515   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3516 
3517   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3518 
3519   // In 32-bit non-varargs functions, the stack space for vectors is after the
3520   // stack space for non-vectors.  We do not use this space unless we have
3521   // too many vectors to fit in registers, something that only occurs in
3522   // constructed examples:), but we have to walk the arglist to figure
3523   // that out...for the pathological case, compute VecArgOffset as the
3524   // start of the vector parameter area.  Computing VecArgOffset is the
3525   // entire point of the following loop.
3526   unsigned VecArgOffset = ArgOffset;
3527   if (!isVarArg && !isPPC64) {
3528     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3529          ++ArgNo) {
3530       EVT ObjectVT = Ins[ArgNo].VT;
3531       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3532 
3533       if (Flags.isByVal()) {
3534         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3535         unsigned ObjSize = Flags.getByValSize();
3536         unsigned ArgSize =
3537                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3538         VecArgOffset += ArgSize;
3539         continue;
3540       }
3541 
3542       switch(ObjectVT.getSimpleVT().SimpleTy) {
3543       default: llvm_unreachable("Unhandled argument type!");
3544       case MVT::i1:
3545       case MVT::i32:
3546       case MVT::f32:
3547         VecArgOffset += 4;
3548         break;
3549       case MVT::i64:  // PPC64
3550       case MVT::f64:
3551         // FIXME: We are guaranteed to be !isPPC64 at this point.
3552         // Does MVT::i64 apply?
3553         VecArgOffset += 8;
3554         break;
3555       case MVT::v4f32:
3556       case MVT::v4i32:
3557       case MVT::v8i16:
3558       case MVT::v16i8:
3559         // Nothing to do, we're only looking at Nonvector args here.
3560         break;
3561       }
3562     }
3563   }
3564   // We've found where the vector parameter area in memory is.  Skip the
3565   // first 12 parameters; these don't use that memory.
3566   VecArgOffset = ((VecArgOffset+15)/16)*16;
3567   VecArgOffset += 12*16;
3568 
3569   // Add DAG nodes to load the arguments or copy them out of registers.  On
3570   // entry to a function on PPC, the arguments start after the linkage area,
3571   // although the first ones are often in registers.
3572 
3573   SmallVector<SDValue, 8> MemOps;
3574   unsigned nAltivecParamsAtEnd = 0;
3575   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3576   unsigned CurArgIdx = 0;
3577   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3578     SDValue ArgVal;
3579     bool needsLoad = false;
3580     EVT ObjectVT = Ins[ArgNo].VT;
3581     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3582     unsigned ArgSize = ObjSize;
3583     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3584     if (Ins[ArgNo].isOrigArg()) {
3585       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3586       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3587     }
3588     unsigned CurArgOffset = ArgOffset;
3589 
3590     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3591     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3592         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3593       if (isVarArg || isPPC64) {
3594         MinReservedArea = ((MinReservedArea+15)/16)*16;
3595         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3596                                                   Flags,
3597                                                   PtrByteSize);
3598       } else  nAltivecParamsAtEnd++;
3599     } else
3600       // Calculate min reserved area.
3601       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3602                                                 Flags,
3603                                                 PtrByteSize);
3604 
3605     // FIXME the codegen can be much improved in some cases.
3606     // We do not have to keep everything in memory.
3607     if (Flags.isByVal()) {
3608       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3609 
3610       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3611       ObjSize = Flags.getByValSize();
3612       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3613       // Objects of size 1 and 2 are right justified, everything else is
3614       // left justified.  This means the memory address is adjusted forwards.
3615       if (ObjSize==1 || ObjSize==2) {
3616         CurArgOffset = CurArgOffset + (4 - ObjSize);
3617       }
3618       // The value of the object is its address.
3619       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3620       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3621       InVals.push_back(FIN);
3622       if (ObjSize==1 || ObjSize==2) {
3623         if (GPR_idx != Num_GPR_Regs) {
3624           unsigned VReg;
3625           if (isPPC64)
3626             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3627           else
3628             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3629           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3630           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3631           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3632                                             MachinePointerInfo(&*FuncArg),
3633                                             ObjType, false, false, 0);
3634           MemOps.push_back(Store);
3635           ++GPR_idx;
3636         }
3637 
3638         ArgOffset += PtrByteSize;
3639 
3640         continue;
3641       }
3642       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3643         // Store whatever pieces of the object are in registers
3644         // to memory.  ArgOffset will be the address of the beginning
3645         // of the object.
3646         if (GPR_idx != Num_GPR_Regs) {
3647           unsigned VReg;
3648           if (isPPC64)
3649             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3650           else
3651             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3652           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3653           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3654           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3655           SDValue Store =
3656               DAG.getStore(Val.getValue(1), dl, Val, FIN,
3657                            MachinePointerInfo(&*FuncArg, j), false, false, 0);
3658           MemOps.push_back(Store);
3659           ++GPR_idx;
3660           ArgOffset += PtrByteSize;
3661         } else {
3662           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3663           break;
3664         }
3665       }
3666       continue;
3667     }
3668 
3669     switch (ObjectVT.getSimpleVT().SimpleTy) {
3670     default: llvm_unreachable("Unhandled argument type!");
3671     case MVT::i1:
3672     case MVT::i32:
3673       if (!isPPC64) {
3674         if (GPR_idx != Num_GPR_Regs) {
3675           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3676           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3677 
3678           if (ObjectVT == MVT::i1)
3679             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3680 
3681           ++GPR_idx;
3682         } else {
3683           needsLoad = true;
3684           ArgSize = PtrByteSize;
3685         }
3686         // All int arguments reserve stack space in the Darwin ABI.
3687         ArgOffset += PtrByteSize;
3688         break;
3689       }
3690       // FALLTHROUGH
3691     case MVT::i64:  // PPC64
3692       if (GPR_idx != Num_GPR_Regs) {
3693         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3694         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3695 
3696         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3697           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3698           // value to MVT::i64 and then truncate to the correct register size.
3699           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3700 
3701         ++GPR_idx;
3702       } else {
3703         needsLoad = true;
3704         ArgSize = PtrByteSize;
3705       }
3706       // All int arguments reserve stack space in the Darwin ABI.
3707       ArgOffset += 8;
3708       break;
3709 
3710     case MVT::f32:
3711     case MVT::f64:
3712       // Every 4 bytes of argument space consumes one of the GPRs available for
3713       // argument passing.
3714       if (GPR_idx != Num_GPR_Regs) {
3715         ++GPR_idx;
3716         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3717           ++GPR_idx;
3718       }
3719       if (FPR_idx != Num_FPR_Regs) {
3720         unsigned VReg;
3721 
3722         if (ObjectVT == MVT::f32)
3723           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3724         else
3725           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3726 
3727         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3728         ++FPR_idx;
3729       } else {
3730         needsLoad = true;
3731       }
3732 
3733       // All FP arguments reserve stack space in the Darwin ABI.
3734       ArgOffset += isPPC64 ? 8 : ObjSize;
3735       break;
3736     case MVT::v4f32:
3737     case MVT::v4i32:
3738     case MVT::v8i16:
3739     case MVT::v16i8:
3740       // Note that vector arguments in registers don't reserve stack space,
3741       // except in varargs functions.
3742       if (VR_idx != Num_VR_Regs) {
3743         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3744         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3745         if (isVarArg) {
3746           while ((ArgOffset % 16) != 0) {
3747             ArgOffset += PtrByteSize;
3748             if (GPR_idx != Num_GPR_Regs)
3749               GPR_idx++;
3750           }
3751           ArgOffset += 16;
3752           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3753         }
3754         ++VR_idx;
3755       } else {
3756         if (!isVarArg && !isPPC64) {
3757           // Vectors go after all the nonvectors.
3758           CurArgOffset = VecArgOffset;
3759           VecArgOffset += 16;
3760         } else {
3761           // Vectors are aligned.
3762           ArgOffset = ((ArgOffset+15)/16)*16;
3763           CurArgOffset = ArgOffset;
3764           ArgOffset += 16;
3765         }
3766         needsLoad = true;
3767       }
3768       break;
3769     }
3770 
3771     // We need to load the argument to a virtual register if we determined above
3772     // that we ran out of physical registers of the appropriate type.
3773     if (needsLoad) {
3774       int FI = MFI->CreateFixedObject(ObjSize,
3775                                       CurArgOffset + (ArgSize - ObjSize),
3776                                       isImmutable);
3777       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3778       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3779                            false, false, false, 0);
3780     }
3781 
3782     InVals.push_back(ArgVal);
3783   }
3784 
3785   // Allow for Altivec parameters at the end, if needed.
3786   if (nAltivecParamsAtEnd) {
3787     MinReservedArea = ((MinReservedArea+15)/16)*16;
3788     MinReservedArea += 16*nAltivecParamsAtEnd;
3789   }
3790 
3791   // Area that is at least reserved in the caller of this function.
3792   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3793 
3794   // Set the size that is at least reserved in caller of this function.  Tail
3795   // call optimized functions' reserved stack space needs to be aligned so that
3796   // taking the difference between two stack areas will result in an aligned
3797   // stack.
3798   MinReservedArea =
3799       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3800   FuncInfo->setMinReservedArea(MinReservedArea);
3801 
3802   // If the function takes variable number of arguments, make a frame index for
3803   // the start of the first vararg value... for expansion of llvm.va_start.
3804   if (isVarArg) {
3805     int Depth = ArgOffset;
3806 
3807     FuncInfo->setVarArgsFrameIndex(
3808       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3809                              Depth, true));
3810     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3811 
3812     // If this function is vararg, store any remaining integer argument regs
3813     // to their spots on the stack so that they may be loaded by deferencing the
3814     // result of va_next.
3815     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3816       unsigned VReg;
3817 
3818       if (isPPC64)
3819         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3820       else
3821         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3822 
3823       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3824       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3825                                    MachinePointerInfo(), false, false, 0);
3826       MemOps.push_back(Store);
3827       // Increment the address by four for the next argument to store
3828       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3829       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3830     }
3831   }
3832 
3833   if (!MemOps.empty())
3834     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3835 
3836   return Chain;
3837 }
3838 
3839 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3840 /// adjusted to accommodate the arguments for the tailcall.
3841 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3842                                    unsigned ParamSize) {
3843 
3844   if (!isTailCall) return 0;
3845 
3846   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3847   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3848   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3849   // Remember only if the new adjustement is bigger.
3850   if (SPDiff < FI->getTailCallSPDelta())
3851     FI->setTailCallSPDelta(SPDiff);
3852 
3853   return SPDiff;
3854 }
3855 
3856 static bool isFunctionGlobalAddress(SDValue Callee);
3857 
3858 static bool
3859 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3860   // If !G, Callee can be an external symbol.
3861   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3862   if (!G) return false;
3863 
3864   const GlobalValue *GV = G->getGlobal();
3865 
3866   if (GV->isDeclaration()) return false;
3867 
3868   switch(GV->getLinkage()) {
3869   default: llvm_unreachable("unknow linkage type");
3870   case GlobalValue::AvailableExternallyLinkage:
3871   case GlobalValue::ExternalWeakLinkage:
3872     return false;
3873 
3874   // Callee with weak linkage is allowed if it has hidden or protected
3875   // visibility
3876   case GlobalValue::LinkOnceAnyLinkage:
3877   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3878   case GlobalValue::WeakAnyLinkage:
3879   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3880     if (GV->hasDefaultVisibility())
3881       return false;
3882 
3883   case GlobalValue::ExternalLinkage:
3884   case GlobalValue::InternalLinkage:
3885   case GlobalValue::PrivateLinkage:
3886     break;
3887   }
3888 
3889   // With '-fPIC', calling default visiblity function need insert 'nop' after
3890   // function call, no matter that function resides in same module or not, so
3891   // we treat it as in different module.
3892   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3893     return false;
3894 
3895   return true;
3896 }
3897 
3898 static bool
3899 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3900                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3901   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3902 
3903   const unsigned PtrByteSize = 8;
3904   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3905 
3906   static const MCPhysReg GPR[] = {
3907     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3908     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3909   };
3910   static const MCPhysReg VR[] = {
3911     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3912     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3913   };
3914 
3915   const unsigned NumGPRs = array_lengthof(GPR);
3916   const unsigned NumFPRs = 13;
3917   const unsigned NumVRs = array_lengthof(VR);
3918   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3919 
3920   unsigned NumBytes = LinkageSize;
3921   unsigned AvailableFPRs = NumFPRs;
3922   unsigned AvailableVRs = NumVRs;
3923 
3924   for (const ISD::OutputArg& Param : Outs) {
3925     if (Param.Flags.isNest()) continue;
3926 
3927     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3928                                PtrByteSize, LinkageSize, ParamAreaSize,
3929                                NumBytes, AvailableFPRs, AvailableVRs,
3930                                Subtarget.hasQPX()))
3931       return true;
3932   }
3933   return false;
3934 }
3935 
3936 static bool
3937 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
3938   if (CS->arg_size() != CallerFn->getArgumentList().size())
3939     return false;
3940 
3941   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
3942   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
3943   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
3944 
3945   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
3946     const Value* CalleeArg = *CalleeArgIter;
3947     const Value* CallerArg = &(*CallerArgIter);
3948     if (CalleeArg == CallerArg)
3949       continue;
3950 
3951     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
3952     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
3953     //      }
3954     // 1st argument of callee is undef and has the same type as caller.
3955     if (CalleeArg->getType() == CallerArg->getType() &&
3956         isa<UndefValue>(CalleeArg))
3957       continue;
3958 
3959     return false;
3960   }
3961 
3962   return true;
3963 }
3964 
3965 bool
3966 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
3967                                     SDValue Callee,
3968                                     CallingConv::ID CalleeCC,
3969                                     ImmutableCallSite *CS,
3970                                     bool isVarArg,
3971                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3972                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3973                                     SelectionDAG& DAG) const {
3974   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
3975 
3976   if (DisableSCO && !TailCallOpt) return false;
3977 
3978   // Variadic argument functions are not supported.
3979   if (isVarArg) return false;
3980 
3981   MachineFunction &MF = DAG.getMachineFunction();
3982   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3983 
3984   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
3985   // the same calling convention
3986   if (CallerCC != CalleeCC) return false;
3987 
3988   // SCO support C calling convention
3989   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
3990     return false;
3991 
3992   // Functions containing by val parameters are not supported.
3993   if (std::any_of(Ins.begin(), Ins.end(),
3994                   [](const ISD::InputArg& IA) { return IA.Flags.isByVal(); }))
3995     return false;
3996 
3997   // No TCO/SCO on indirect call because Caller have to restore its TOC
3998   if (!isFunctionGlobalAddress(Callee) &&
3999       !isa<ExternalSymbolSDNode>(Callee))
4000     return false;
4001 
4002   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4003   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4004   // module.
4005   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4006   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4007     return false;
4008 
4009   // TCO allows altering callee ABI, so we don't have to check further.
4010   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4011     return true;
4012 
4013   if (DisableSCO) return false;
4014 
4015   // If callee use the same argument list that caller is using, then we can
4016   // apply SCO on this case. If it is not, then we need to check if callee needs
4017   // stack for passing arguments.
4018   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4019       needStackSlotPassParameters(Subtarget, Outs)) {
4020     return false;
4021   }
4022 
4023   return true;
4024 }
4025 
4026 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4027 /// for tail call optimization. Targets which want to do tail call
4028 /// optimization should implement this function.
4029 bool
4030 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4031                                                      CallingConv::ID CalleeCC,
4032                                                      bool isVarArg,
4033                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4034                                                      SelectionDAG& DAG) const {
4035   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4036     return false;
4037 
4038   // Variable argument functions are not supported.
4039   if (isVarArg)
4040     return false;
4041 
4042   MachineFunction &MF = DAG.getMachineFunction();
4043   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4044   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4045     // Functions containing by val parameters are not supported.
4046     for (unsigned i = 0; i != Ins.size(); i++) {
4047        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4048        if (Flags.isByVal()) return false;
4049     }
4050 
4051     // Non-PIC/GOT tail calls are supported.
4052     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4053       return true;
4054 
4055     // At the moment we can only do local tail calls (in same module, hidden
4056     // or protected) if we are generating PIC.
4057     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4058       return G->getGlobal()->hasHiddenVisibility()
4059           || G->getGlobal()->hasProtectedVisibility();
4060   }
4061 
4062   return false;
4063 }
4064 
4065 /// isCallCompatibleAddress - Return the immediate to use if the specified
4066 /// 32-bit value is representable in the immediate field of a BxA instruction.
4067 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4068   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4069   if (!C) return nullptr;
4070 
4071   int Addr = C->getZExtValue();
4072   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4073       SignExtend32<26>(Addr) != Addr)
4074     return nullptr;  // Top 6 bits have to be sext of immediate.
4075 
4076   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
4077                          DAG.getTargetLoweringInfo().getPointerTy(
4078                              DAG.getDataLayout())).getNode();
4079 }
4080 
4081 namespace {
4082 
4083 struct TailCallArgumentInfo {
4084   SDValue Arg;
4085   SDValue FrameIdxOp;
4086   int       FrameIdx;
4087 
4088   TailCallArgumentInfo() : FrameIdx(0) {}
4089 };
4090 }
4091 
4092 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4093 static void
4094 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
4095                                            SDValue Chain,
4096                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4097                    SmallVectorImpl<SDValue> &MemOpChains,
4098                    SDLoc dl) {
4099   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4100     SDValue Arg = TailCallArgs[i].Arg;
4101     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4102     int FI = TailCallArgs[i].FrameIdx;
4103     // Store relative to framepointer.
4104     MemOpChains.push_back(DAG.getStore(
4105         Chain, dl, Arg, FIN,
4106         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
4107         false, 0));
4108   }
4109 }
4110 
4111 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4112 /// the appropriate stack slot for the tail call optimized function call.
4113 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
4114                                                MachineFunction &MF,
4115                                                SDValue Chain,
4116                                                SDValue OldRetAddr,
4117                                                SDValue OldFP,
4118                                                int SPDiff,
4119                                                bool isPPC64,
4120                                                bool isDarwinABI,
4121                                                SDLoc dl) {
4122   if (SPDiff) {
4123     // Calculate the new stack slot for the return address.
4124     int SlotSize = isPPC64 ? 8 : 4;
4125     const PPCFrameLowering *FL =
4126         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
4127     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4128     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
4129                                                           NewRetAddrLoc, true);
4130     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4131     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4132     Chain = DAG.getStore(
4133         Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4134         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewRetAddr),
4135         false, false, 0);
4136 
4137     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4138     // slot as the FP is never overwritten.
4139     if (isDarwinABI) {
4140       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4141       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
4142                                                           true);
4143       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4144       Chain = DAG.getStore(
4145           Chain, dl, OldFP, NewFramePtrIdx,
4146           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx),
4147           false, false, 0);
4148     }
4149   }
4150   return Chain;
4151 }
4152 
4153 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4154 /// the position of the argument.
4155 static void
4156 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4157                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4158                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4159   int Offset = ArgOffset + SPDiff;
4160   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4161   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
4162   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4163   SDValue FIN = DAG.getFrameIndex(FI, VT);
4164   TailCallArgumentInfo Info;
4165   Info.Arg = Arg;
4166   Info.FrameIdxOp = FIN;
4167   Info.FrameIdx = FI;
4168   TailCallArguments.push_back(Info);
4169 }
4170 
4171 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4172 /// stack slot. Returns the chain as result and the loaded frame pointers in
4173 /// LROpOut/FPOpout. Used when tail calling.
4174 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
4175                                                         int SPDiff,
4176                                                         SDValue Chain,
4177                                                         SDValue &LROpOut,
4178                                                         SDValue &FPOpOut,
4179                                                         bool isDarwinABI,
4180                                                         SDLoc dl) const {
4181   if (SPDiff) {
4182     // Load the LR and FP stack slot for later adjusting.
4183     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4184     LROpOut = getReturnAddrFrameIndex(DAG);
4185     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
4186                           false, false, false, 0);
4187     Chain = SDValue(LROpOut.getNode(), 1);
4188 
4189     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4190     // slot as the FP is never overwritten.
4191     if (isDarwinABI) {
4192       FPOpOut = getFramePointerFrameIndex(DAG);
4193       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
4194                             false, false, false, 0);
4195       Chain = SDValue(FPOpOut.getNode(), 1);
4196     }
4197   }
4198   return Chain;
4199 }
4200 
4201 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4202 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4203 /// specified by the specific parameter attribute. The copy will be passed as
4204 /// a byval function parameter.
4205 /// Sometimes what we are copying is the end of a larger object, the part that
4206 /// does not fit in registers.
4207 static SDValue
4208 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
4209                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
4210                           SDLoc dl) {
4211   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4212   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4213                        false, false, false, MachinePointerInfo(),
4214                        MachinePointerInfo());
4215 }
4216 
4217 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4218 /// tail calls.
4219 static void
4220 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
4221                  SDValue Arg, SDValue PtrOff, int SPDiff,
4222                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
4223                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4224                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
4225                  SDLoc dl) {
4226   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4227   if (!isTailCall) {
4228     if (isVector) {
4229       SDValue StackPtr;
4230       if (isPPC64)
4231         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4232       else
4233         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4234       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4235                            DAG.getConstant(ArgOffset, dl, PtrVT));
4236     }
4237     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4238                                        MachinePointerInfo(), false, false, 0));
4239   // Calculate and remember argument location.
4240   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4241                                   TailCallArguments);
4242 }
4243 
4244 static
4245 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4246                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
4247                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
4248                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4249   MachineFunction &MF = DAG.getMachineFunction();
4250 
4251   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4252   // might overwrite each other in case of tail call optimization.
4253   SmallVector<SDValue, 8> MemOpChains2;
4254   // Do not flag preceding copytoreg stuff together with the following stuff.
4255   InFlag = SDValue();
4256   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4257                                     MemOpChains2, dl);
4258   if (!MemOpChains2.empty())
4259     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4260 
4261   // Store the return address to the appropriate stack slot.
4262   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
4263                                         isPPC64, isDarwinABI, dl);
4264 
4265   // Emit callseq_end just before tailcall node.
4266   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4267                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4268   InFlag = Chain.getValue(1);
4269 }
4270 
4271 // Is this global address that of a function that can be called by name? (as
4272 // opposed to something that must hold a descriptor for an indirect call).
4273 static bool isFunctionGlobalAddress(SDValue Callee) {
4274   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4275     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4276         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4277       return false;
4278 
4279     return G->getGlobal()->getValueType()->isFunctionTy();
4280   }
4281 
4282   return false;
4283 }
4284 
4285 static
4286 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
4287                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
4288                      bool isTailCall, bool IsPatchPoint, bool hasNest,
4289                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
4290                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4291                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4292 
4293   bool isPPC64 = Subtarget.isPPC64();
4294   bool isSVR4ABI = Subtarget.isSVR4ABI();
4295   bool isELFv2ABI = Subtarget.isELFv2ABI();
4296 
4297   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4298   NodeTys.push_back(MVT::Other);   // Returns a chain
4299   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4300 
4301   unsigned CallOpc = PPCISD::CALL;
4302 
4303   bool needIndirectCall = true;
4304   if (!isSVR4ABI || !isPPC64)
4305     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4306       // If this is an absolute destination address, use the munged value.
4307       Callee = SDValue(Dest, 0);
4308       needIndirectCall = false;
4309     }
4310 
4311   if (isFunctionGlobalAddress(Callee)) {
4312     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4313     // A call to a TLS address is actually an indirect call to a
4314     // thread-specific pointer.
4315     unsigned OpFlags = 0;
4316     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4317          (Subtarget.getTargetTriple().isMacOSX() &&
4318           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
4319          !G->getGlobal()->isStrongDefinitionForLinker()) ||
4320         (Subtarget.isTargetELF() && !isPPC64 &&
4321          !G->getGlobal()->hasLocalLinkage() &&
4322          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4323       // PC-relative references to external symbols should go through $stub,
4324       // unless we're building with the leopard linker or later, which
4325       // automatically synthesizes these stubs.
4326       OpFlags = PPCII::MO_PLT_OR_STUB;
4327     }
4328 
4329     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4330     // every direct call is) turn it into a TargetGlobalAddress /
4331     // TargetExternalSymbol node so that legalize doesn't hack it.
4332     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4333                                         Callee.getValueType(), 0, OpFlags);
4334     needIndirectCall = false;
4335   }
4336 
4337   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4338     unsigned char OpFlags = 0;
4339 
4340     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4341          (Subtarget.getTargetTriple().isMacOSX() &&
4342           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4343         (Subtarget.isTargetELF() && !isPPC64 &&
4344          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4345       // PC-relative references to external symbols should go through $stub,
4346       // unless we're building with the leopard linker or later, which
4347       // automatically synthesizes these stubs.
4348       OpFlags = PPCII::MO_PLT_OR_STUB;
4349     }
4350 
4351     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4352                                          OpFlags);
4353     needIndirectCall = false;
4354   }
4355 
4356   if (IsPatchPoint) {
4357     // We'll form an invalid direct call when lowering a patchpoint; the full
4358     // sequence for an indirect call is complicated, and many of the
4359     // instructions introduced might have side effects (and, thus, can't be
4360     // removed later). The call itself will be removed as soon as the
4361     // argument/return lowering is complete, so the fact that it has the wrong
4362     // kind of operands should not really matter.
4363     needIndirectCall = false;
4364   }
4365 
4366   if (needIndirectCall) {
4367     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4368     // to do the call, we can't use PPCISD::CALL.
4369     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4370 
4371     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4372       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4373       // entry point, but to the function descriptor (the function entry point
4374       // address is part of the function descriptor though).
4375       // The function descriptor is a three doubleword structure with the
4376       // following fields: function entry point, TOC base address and
4377       // environment pointer.
4378       // Thus for a call through a function pointer, the following actions need
4379       // to be performed:
4380       //   1. Save the TOC of the caller in the TOC save area of its stack
4381       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4382       //   2. Load the address of the function entry point from the function
4383       //      descriptor.
4384       //   3. Load the TOC of the callee from the function descriptor into r2.
4385       //   4. Load the environment pointer from the function descriptor into
4386       //      r11.
4387       //   5. Branch to the function entry point address.
4388       //   6. On return of the callee, the TOC of the caller needs to be
4389       //      restored (this is done in FinishCall()).
4390       //
4391       // The loads are scheduled at the beginning of the call sequence, and the
4392       // register copies are flagged together to ensure that no other
4393       // operations can be scheduled in between. E.g. without flagging the
4394       // copies together, a TOC access in the caller could be scheduled between
4395       // the assignment of the callee TOC and the branch to the callee, which
4396       // results in the TOC access going through the TOC of the callee instead
4397       // of going through the TOC of the caller, which leads to incorrect code.
4398 
4399       // Load the address of the function entry point from the function
4400       // descriptor.
4401       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4402       if (LDChain.getValueType() == MVT::Glue)
4403         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4404 
4405       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4406 
4407       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4408       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4409                                         false, false, LoadsInv, 8);
4410 
4411       // Load environment pointer into r11.
4412       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4413       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4414       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4415                                        MPI.getWithOffset(16), false, false,
4416                                        LoadsInv, 8);
4417 
4418       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4419       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4420       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4421                                    MPI.getWithOffset(8), false, false,
4422                                    LoadsInv, 8);
4423 
4424       setUsesTOCBasePtr(DAG);
4425       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4426                                         InFlag);
4427       Chain = TOCVal.getValue(0);
4428       InFlag = TOCVal.getValue(1);
4429 
4430       // If the function call has an explicit 'nest' parameter, it takes the
4431       // place of the environment pointer.
4432       if (!hasNest) {
4433         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4434                                           InFlag);
4435 
4436         Chain = EnvVal.getValue(0);
4437         InFlag = EnvVal.getValue(1);
4438       }
4439 
4440       MTCTROps[0] = Chain;
4441       MTCTROps[1] = LoadFuncPtr;
4442       MTCTROps[2] = InFlag;
4443     }
4444 
4445     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4446                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4447     InFlag = Chain.getValue(1);
4448 
4449     NodeTys.clear();
4450     NodeTys.push_back(MVT::Other);
4451     NodeTys.push_back(MVT::Glue);
4452     Ops.push_back(Chain);
4453     CallOpc = PPCISD::BCTRL;
4454     Callee.setNode(nullptr);
4455     // Add use of X11 (holding environment pointer)
4456     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4457       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4458     // Add CTR register as callee so a bctr can be emitted later.
4459     if (isTailCall)
4460       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4461   }
4462 
4463   // If this is a direct call, pass the chain and the callee.
4464   if (Callee.getNode()) {
4465     Ops.push_back(Chain);
4466     Ops.push_back(Callee);
4467   }
4468   // If this is a tail call add stack pointer delta.
4469   if (isTailCall)
4470     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4471 
4472   // Add argument registers to the end of the list so that they are known live
4473   // into the call.
4474   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4475     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4476                                   RegsToPass[i].second.getValueType()));
4477 
4478   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4479   // into the call.
4480   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4481     setUsesTOCBasePtr(DAG);
4482     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4483   }
4484 
4485   return CallOpc;
4486 }
4487 
4488 static
4489 bool isLocalCall(const SDValue &Callee)
4490 {
4491   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4492     return G->getGlobal()->isStrongDefinitionForLinker();
4493   return false;
4494 }
4495 
4496 SDValue
4497 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4498                                    CallingConv::ID CallConv, bool isVarArg,
4499                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4500                                    SDLoc dl, SelectionDAG &DAG,
4501                                    SmallVectorImpl<SDValue> &InVals) const {
4502 
4503   SmallVector<CCValAssign, 16> RVLocs;
4504   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4505                     *DAG.getContext());
4506   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4507 
4508   // Copy all of the result registers out of their specified physreg.
4509   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4510     CCValAssign &VA = RVLocs[i];
4511     assert(VA.isRegLoc() && "Can only return in registers!");
4512 
4513     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4514                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4515     Chain = Val.getValue(1);
4516     InFlag = Val.getValue(2);
4517 
4518     switch (VA.getLocInfo()) {
4519     default: llvm_unreachable("Unknown loc info!");
4520     case CCValAssign::Full: break;
4521     case CCValAssign::AExt:
4522       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4523       break;
4524     case CCValAssign::ZExt:
4525       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4526                         DAG.getValueType(VA.getValVT()));
4527       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4528       break;
4529     case CCValAssign::SExt:
4530       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4531                         DAG.getValueType(VA.getValVT()));
4532       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4533       break;
4534     }
4535 
4536     InVals.push_back(Val);
4537   }
4538 
4539   return Chain;
4540 }
4541 
4542 SDValue
4543 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4544                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4545                               bool hasNest, SelectionDAG &DAG,
4546                               SmallVector<std::pair<unsigned, SDValue>, 8>
4547                                 &RegsToPass,
4548                               SDValue InFlag, SDValue Chain,
4549                               SDValue CallSeqStart, SDValue &Callee,
4550                               int SPDiff, unsigned NumBytes,
4551                               const SmallVectorImpl<ISD::InputArg> &Ins,
4552                               SmallVectorImpl<SDValue> &InVals,
4553                               ImmutableCallSite *CS) const {
4554 
4555   std::vector<EVT> NodeTys;
4556   SmallVector<SDValue, 8> Ops;
4557   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4558                                  SPDiff, isTailCall, IsPatchPoint, hasNest,
4559                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4560 
4561   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4562   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4563     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4564 
4565   // When performing tail call optimization the callee pops its arguments off
4566   // the stack. Account for this here so these bytes can be pushed back on in
4567   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4568   int BytesCalleePops =
4569     (CallConv == CallingConv::Fast &&
4570      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4571 
4572   // Add a register mask operand representing the call-preserved registers.
4573   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4574   const uint32_t *Mask =
4575       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4576   assert(Mask && "Missing call preserved mask for calling convention");
4577   Ops.push_back(DAG.getRegisterMask(Mask));
4578 
4579   if (InFlag.getNode())
4580     Ops.push_back(InFlag);
4581 
4582   // Emit tail call.
4583   if (isTailCall) {
4584     assert(((Callee.getOpcode() == ISD::Register &&
4585              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4586             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4587             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4588             isa<ConstantSDNode>(Callee)) &&
4589     "Expecting an global address, external symbol, absolute value or register");
4590 
4591     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4592     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4593   }
4594 
4595   // Add a NOP immediately after the branch instruction when using the 64-bit
4596   // SVR4 ABI. At link time, if caller and callee are in a different module and
4597   // thus have a different TOC, the call will be replaced with a call to a stub
4598   // function which saves the current TOC, loads the TOC of the callee and
4599   // branches to the callee. The NOP will be replaced with a load instruction
4600   // which restores the TOC of the caller from the TOC save slot of the current
4601   // stack frame. If caller and callee belong to the same module (and have the
4602   // same TOC), the NOP will remain unchanged.
4603 
4604   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4605       !IsPatchPoint) {
4606     if (CallOpc == PPCISD::BCTRL) {
4607       // This is a call through a function pointer.
4608       // Restore the caller TOC from the save area into R2.
4609       // See PrepareCall() for more information about calls through function
4610       // pointers in the 64-bit SVR4 ABI.
4611       // We are using a target-specific load with r2 hard coded, because the
4612       // result of a target-independent load would never go directly into r2,
4613       // since r2 is a reserved register (which prevents the register allocator
4614       // from allocating it), resulting in an additional register being
4615       // allocated and an unnecessary move instruction being generated.
4616       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4617 
4618       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4619       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4620       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4621       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4622       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4623 
4624       // The address needs to go after the chain input but before the flag (or
4625       // any other variadic arguments).
4626       Ops.insert(std::next(Ops.begin()), AddTOC);
4627     } else if ((CallOpc == PPCISD::CALL) &&
4628                (!isLocalCall(Callee) ||
4629                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4630       // Otherwise insert NOP for non-local calls.
4631       CallOpc = PPCISD::CALL_NOP;
4632   }
4633 
4634   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4635   InFlag = Chain.getValue(1);
4636 
4637   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4638                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4639                              InFlag, dl);
4640   if (!Ins.empty())
4641     InFlag = Chain.getValue(1);
4642 
4643   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4644                          Ins, dl, DAG, InVals);
4645 }
4646 
4647 SDValue
4648 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4649                              SmallVectorImpl<SDValue> &InVals) const {
4650   SelectionDAG &DAG                     = CLI.DAG;
4651   SDLoc &dl                             = CLI.DL;
4652   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4653   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4654   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4655   SDValue Chain                         = CLI.Chain;
4656   SDValue Callee                        = CLI.Callee;
4657   bool &isTailCall                      = CLI.IsTailCall;
4658   CallingConv::ID CallConv              = CLI.CallConv;
4659   bool isVarArg                         = CLI.IsVarArg;
4660   bool IsPatchPoint                     = CLI.IsPatchPoint;
4661   ImmutableCallSite *CS                 = CLI.CS;
4662 
4663   if (isTailCall) {
4664     if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4665       isTailCall =
4666         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4667                                                  isVarArg, Outs, Ins, DAG);
4668     else
4669       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4670                                                      Ins, DAG);
4671     if (isTailCall) {
4672       ++NumTailCalls;
4673       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4674         ++NumSiblingCalls;
4675 
4676       assert(isa<GlobalAddressSDNode>(Callee) &&
4677              "Callee should be an llvm::Function object.");
4678       DEBUG(
4679         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4680         const unsigned Width = 80 - strlen("TCO caller: ")
4681                                   - strlen(", callee linkage: 0, 0");
4682         dbgs() << "TCO caller: "
4683                << left_justify(DAG.getMachineFunction().getName(), Width)
4684                << ", callee linkage: "
4685                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4686       );
4687     }
4688   }
4689 
4690   if (!isTailCall && CS && CS->isMustTailCall())
4691     report_fatal_error("failed to perform tail call elimination on a call "
4692                        "site marked musttail");
4693 
4694   if (Subtarget.isSVR4ABI()) {
4695     if (Subtarget.isPPC64())
4696       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4697                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4698                               dl, DAG, InVals, CS);
4699     else
4700       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4701                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4702                               dl, DAG, InVals, CS);
4703   }
4704 
4705   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4706                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4707                           dl, DAG, InVals, CS);
4708 }
4709 
4710 SDValue
4711 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4712                                     CallingConv::ID CallConv, bool isVarArg,
4713                                     bool isTailCall, bool IsPatchPoint,
4714                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4715                                     const SmallVectorImpl<SDValue> &OutVals,
4716                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4717                                     SDLoc dl, SelectionDAG &DAG,
4718                                     SmallVectorImpl<SDValue> &InVals,
4719                                     ImmutableCallSite *CS) const {
4720   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4721   // of the 32-bit SVR4 ABI stack frame layout.
4722 
4723   assert((CallConv == CallingConv::C ||
4724           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4725 
4726   unsigned PtrByteSize = 4;
4727 
4728   MachineFunction &MF = DAG.getMachineFunction();
4729 
4730   // Mark this function as potentially containing a function that contains a
4731   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4732   // and restoring the callers stack pointer in this functions epilog. This is
4733   // done because by tail calling the called function might overwrite the value
4734   // in this function's (MF) stack pointer stack slot 0(SP).
4735   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4736       CallConv == CallingConv::Fast)
4737     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4738 
4739   // Count how many bytes are to be pushed on the stack, including the linkage
4740   // area, parameter list area and the part of the local variable space which
4741   // contains copies of aggregates which are passed by value.
4742 
4743   // Assign locations to all of the outgoing arguments.
4744   SmallVector<CCValAssign, 16> ArgLocs;
4745   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4746                  *DAG.getContext());
4747 
4748   // Reserve space for the linkage area on the stack.
4749   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4750                        PtrByteSize);
4751   if (Subtarget.useSoftFloat())
4752     CCInfo.PreAnalyzeCallOperands(Outs);
4753 
4754   if (isVarArg) {
4755     // Handle fixed and variable vector arguments differently.
4756     // Fixed vector arguments go into registers as long as registers are
4757     // available. Variable vector arguments always go into memory.
4758     unsigned NumArgs = Outs.size();
4759 
4760     for (unsigned i = 0; i != NumArgs; ++i) {
4761       MVT ArgVT = Outs[i].VT;
4762       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4763       bool Result;
4764 
4765       if (Outs[i].IsFixed) {
4766         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4767                                CCInfo);
4768       } else {
4769         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4770                                       ArgFlags, CCInfo);
4771       }
4772 
4773       if (Result) {
4774 #ifndef NDEBUG
4775         errs() << "Call operand #" << i << " has unhandled type "
4776              << EVT(ArgVT).getEVTString() << "\n";
4777 #endif
4778         llvm_unreachable(nullptr);
4779       }
4780     }
4781   } else {
4782     // All arguments are treated the same.
4783     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4784   }
4785   CCInfo.clearWasPPCF128();
4786 
4787   // Assign locations to all of the outgoing aggregate by value arguments.
4788   SmallVector<CCValAssign, 16> ByValArgLocs;
4789   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4790                       ByValArgLocs, *DAG.getContext());
4791 
4792   // Reserve stack space for the allocations in CCInfo.
4793   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4794 
4795   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4796 
4797   // Size of the linkage area, parameter list area and the part of the local
4798   // space variable where copies of aggregates which are passed by value are
4799   // stored.
4800   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4801 
4802   // Calculate by how many bytes the stack has to be adjusted in case of tail
4803   // call optimization.
4804   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4805 
4806   // Adjust the stack pointer for the new arguments...
4807   // These operations are automatically eliminated by the prolog/epilog pass
4808   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4809                                dl);
4810   SDValue CallSeqStart = Chain;
4811 
4812   // Load the return address and frame pointer so it can be moved somewhere else
4813   // later.
4814   SDValue LROp, FPOp;
4815   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4816                                        dl);
4817 
4818   // Set up a copy of the stack pointer for use loading and storing any
4819   // arguments that may not fit in the registers available for argument
4820   // passing.
4821   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4822 
4823   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4824   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4825   SmallVector<SDValue, 8> MemOpChains;
4826 
4827   bool seenFloatArg = false;
4828   // Walk the register/memloc assignments, inserting copies/loads.
4829   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4830        i != e;
4831        ++i) {
4832     CCValAssign &VA = ArgLocs[i];
4833     SDValue Arg = OutVals[i];
4834     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4835 
4836     if (Flags.isByVal()) {
4837       // Argument is an aggregate which is passed by value, thus we need to
4838       // create a copy of it in the local variable space of the current stack
4839       // frame (which is the stack frame of the caller) and pass the address of
4840       // this copy to the callee.
4841       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4842       CCValAssign &ByValVA = ByValArgLocs[j++];
4843       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4844 
4845       // Memory reserved in the local variable space of the callers stack frame.
4846       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4847 
4848       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4849       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4850                            StackPtr, PtrOff);
4851 
4852       // Create a copy of the argument in the local area of the current
4853       // stack frame.
4854       SDValue MemcpyCall =
4855         CreateCopyOfByValArgument(Arg, PtrOff,
4856                                   CallSeqStart.getNode()->getOperand(0),
4857                                   Flags, DAG, dl);
4858 
4859       // This must go outside the CALLSEQ_START..END.
4860       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4861                            CallSeqStart.getNode()->getOperand(1),
4862                            SDLoc(MemcpyCall));
4863       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4864                              NewCallSeqStart.getNode());
4865       Chain = CallSeqStart = NewCallSeqStart;
4866 
4867       // Pass the address of the aggregate copy on the stack either in a
4868       // physical register or in the parameter list area of the current stack
4869       // frame to the callee.
4870       Arg = PtrOff;
4871     }
4872 
4873     if (VA.isRegLoc()) {
4874       if (Arg.getValueType() == MVT::i1)
4875         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4876 
4877       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4878       // Put argument in a physical register.
4879       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4880     } else {
4881       // Put argument in the parameter list area of the current stack frame.
4882       assert(VA.isMemLoc());
4883       unsigned LocMemOffset = VA.getLocMemOffset();
4884 
4885       if (!isTailCall) {
4886         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4887         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4888                              StackPtr, PtrOff);
4889 
4890         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4891                                            MachinePointerInfo(),
4892                                            false, false, 0));
4893       } else {
4894         // Calculate and remember argument location.
4895         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4896                                  TailCallArguments);
4897       }
4898     }
4899   }
4900 
4901   if (!MemOpChains.empty())
4902     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4903 
4904   // Build a sequence of copy-to-reg nodes chained together with token chain
4905   // and flag operands which copy the outgoing args into the appropriate regs.
4906   SDValue InFlag;
4907   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4908     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4909                              RegsToPass[i].second, InFlag);
4910     InFlag = Chain.getValue(1);
4911   }
4912 
4913   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4914   // registers.
4915   if (isVarArg) {
4916     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4917     SDValue Ops[] = { Chain, InFlag };
4918 
4919     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4920                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4921 
4922     InFlag = Chain.getValue(1);
4923   }
4924 
4925   if (isTailCall)
4926     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4927                     false, TailCallArguments);
4928 
4929   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
4930                     /* unused except on PPC64 ELFv1 */ false, DAG,
4931                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4932                     NumBytes, Ins, InVals, CS);
4933 }
4934 
4935 // Copy an argument into memory, being careful to do this outside the
4936 // call sequence for the call to which the argument belongs.
4937 SDValue
4938 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4939                                               SDValue CallSeqStart,
4940                                               ISD::ArgFlagsTy Flags,
4941                                               SelectionDAG &DAG,
4942                                               SDLoc dl) const {
4943   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4944                         CallSeqStart.getNode()->getOperand(0),
4945                         Flags, DAG, dl);
4946   // The MEMCPY must go outside the CALLSEQ_START..END.
4947   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4948                              CallSeqStart.getNode()->getOperand(1),
4949                              SDLoc(MemcpyCall));
4950   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4951                          NewCallSeqStart.getNode());
4952   return NewCallSeqStart;
4953 }
4954 
4955 SDValue
4956 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4957                                     CallingConv::ID CallConv, bool isVarArg,
4958                                     bool isTailCall, bool IsPatchPoint,
4959                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4960                                     const SmallVectorImpl<SDValue> &OutVals,
4961                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4962                                     SDLoc dl, SelectionDAG &DAG,
4963                                     SmallVectorImpl<SDValue> &InVals,
4964                                     ImmutableCallSite *CS) const {
4965 
4966   bool isELFv2ABI = Subtarget.isELFv2ABI();
4967   bool isLittleEndian = Subtarget.isLittleEndian();
4968   unsigned NumOps = Outs.size();
4969   bool hasNest = false;
4970   bool IsSibCall = false;
4971 
4972   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4973   unsigned PtrByteSize = 8;
4974 
4975   MachineFunction &MF = DAG.getMachineFunction();
4976 
4977   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
4978     IsSibCall = true;
4979 
4980   // Mark this function as potentially containing a function that contains a
4981   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4982   // and restoring the callers stack pointer in this functions epilog. This is
4983   // done because by tail calling the called function might overwrite the value
4984   // in this function's (MF) stack pointer stack slot 0(SP).
4985   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4986       CallConv == CallingConv::Fast)
4987     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4988 
4989   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4990          "fastcc not supported on varargs functions");
4991 
4992   // Count how many bytes are to be pushed on the stack, including the linkage
4993   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4994   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4995   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4996   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4997   unsigned NumBytes = LinkageSize;
4998   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4999   unsigned &QFPR_idx = FPR_idx;
5000 
5001   static const MCPhysReg GPR[] = {
5002     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5003     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5004   };
5005   static const MCPhysReg VR[] = {
5006     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5007     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5008   };
5009   static const MCPhysReg VSRH[] = {
5010     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
5011     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
5012   };
5013 
5014   const unsigned NumGPRs = array_lengthof(GPR);
5015   const unsigned NumFPRs = 13;
5016   const unsigned NumVRs  = array_lengthof(VR);
5017   const unsigned NumQFPRs = NumFPRs;
5018 
5019   // When using the fast calling convention, we don't provide backing for
5020   // arguments that will be in registers.
5021   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5022 
5023   // Add up all the space actually used.
5024   for (unsigned i = 0; i != NumOps; ++i) {
5025     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5026     EVT ArgVT = Outs[i].VT;
5027     EVT OrigVT = Outs[i].ArgVT;
5028 
5029     if (Flags.isNest())
5030       continue;
5031 
5032     if (CallConv == CallingConv::Fast) {
5033       if (Flags.isByVal())
5034         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5035       else
5036         switch (ArgVT.getSimpleVT().SimpleTy) {
5037         default: llvm_unreachable("Unexpected ValueType for argument!");
5038         case MVT::i1:
5039         case MVT::i32:
5040         case MVT::i64:
5041           if (++NumGPRsUsed <= NumGPRs)
5042             continue;
5043           break;
5044         case MVT::v4i32:
5045         case MVT::v8i16:
5046         case MVT::v16i8:
5047         case MVT::v2f64:
5048         case MVT::v2i64:
5049         case MVT::v1i128:
5050           if (++NumVRsUsed <= NumVRs)
5051             continue;
5052           break;
5053         case MVT::v4f32:
5054           // When using QPX, this is handled like a FP register, otherwise, it
5055           // is an Altivec register.
5056           if (Subtarget.hasQPX()) {
5057             if (++NumFPRsUsed <= NumFPRs)
5058               continue;
5059           } else {
5060             if (++NumVRsUsed <= NumVRs)
5061               continue;
5062           }
5063           break;
5064         case MVT::f32:
5065         case MVT::f64:
5066         case MVT::v4f64: // QPX
5067         case MVT::v4i1:  // QPX
5068           if (++NumFPRsUsed <= NumFPRs)
5069             continue;
5070           break;
5071         }
5072     }
5073 
5074     /* Respect alignment of argument on the stack.  */
5075     unsigned Align =
5076       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5077     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5078 
5079     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5080     if (Flags.isInConsecutiveRegsLast())
5081       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5082   }
5083 
5084   unsigned NumBytesActuallyUsed = NumBytes;
5085 
5086   // The prolog code of the callee may store up to 8 GPR argument registers to
5087   // the stack, allowing va_start to index over them in memory if its varargs.
5088   // Because we cannot tell if this is needed on the caller side, we have to
5089   // conservatively assume that it is needed.  As such, make sure we have at
5090   // least enough stack space for the caller to store the 8 GPRs.
5091   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5092   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5093 
5094   // Tail call needs the stack to be aligned.
5095   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5096       CallConv == CallingConv::Fast)
5097     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5098 
5099   int SPDiff = 0;
5100 
5101   // Calculate by how many bytes the stack has to be adjusted in case of tail
5102   // call optimization.
5103   if (!IsSibCall)
5104     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5105 
5106   // To protect arguments on the stack from being clobbered in a tail call,
5107   // force all the loads to happen before doing any other lowering.
5108   if (isTailCall)
5109     Chain = DAG.getStackArgumentTokenFactor(Chain);
5110 
5111   // Adjust the stack pointer for the new arguments...
5112   // These operations are automatically eliminated by the prolog/epilog pass
5113   if (!IsSibCall)
5114     Chain = DAG.getCALLSEQ_START(Chain,
5115                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5116   SDValue CallSeqStart = Chain;
5117 
5118   // Load the return address and frame pointer so it can be move somewhere else
5119   // later.
5120   SDValue LROp, FPOp;
5121   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5122                                        dl);
5123 
5124   // Set up a copy of the stack pointer for use loading and storing any
5125   // arguments that may not fit in the registers available for argument
5126   // passing.
5127   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5128 
5129   // Figure out which arguments are going to go in registers, and which in
5130   // memory.  Also, if this is a vararg function, floating point operations
5131   // must be stored to our stack, and loaded into integer regs as well, if
5132   // any integer regs are available for argument passing.
5133   unsigned ArgOffset = LinkageSize;
5134 
5135   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5136   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5137 
5138   SmallVector<SDValue, 8> MemOpChains;
5139   for (unsigned i = 0; i != NumOps; ++i) {
5140     SDValue Arg = OutVals[i];
5141     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5142     EVT ArgVT = Outs[i].VT;
5143     EVT OrigVT = Outs[i].ArgVT;
5144 
5145     // PtrOff will be used to store the current argument to the stack if a
5146     // register cannot be found for it.
5147     SDValue PtrOff;
5148 
5149     // We re-align the argument offset for each argument, except when using the
5150     // fast calling convention, when we need to make sure we do that only when
5151     // we'll actually use a stack slot.
5152     auto ComputePtrOff = [&]() {
5153       /* Respect alignment of argument on the stack.  */
5154       unsigned Align =
5155         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5156       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5157 
5158       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5159 
5160       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5161     };
5162 
5163     if (CallConv != CallingConv::Fast) {
5164       ComputePtrOff();
5165 
5166       /* Compute GPR index associated with argument offset.  */
5167       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5168       GPR_idx = std::min(GPR_idx, NumGPRs);
5169     }
5170 
5171     // Promote integers to 64-bit values.
5172     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5173       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5174       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5175       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5176     }
5177 
5178     // FIXME memcpy is used way more than necessary.  Correctness first.
5179     // Note: "by value" is code for passing a structure by value, not
5180     // basic types.
5181     if (Flags.isByVal()) {
5182       // Note: Size includes alignment padding, so
5183       //   struct x { short a; char b; }
5184       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5185       // These are the proper values we need for right-justifying the
5186       // aggregate in a parameter register.
5187       unsigned Size = Flags.getByValSize();
5188 
5189       // An empty aggregate parameter takes up no storage and no
5190       // registers.
5191       if (Size == 0)
5192         continue;
5193 
5194       if (CallConv == CallingConv::Fast)
5195         ComputePtrOff();
5196 
5197       // All aggregates smaller than 8 bytes must be passed right-justified.
5198       if (Size==1 || Size==2 || Size==4) {
5199         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5200         if (GPR_idx != NumGPRs) {
5201           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5202                                         MachinePointerInfo(), VT,
5203                                         false, false, false, 0);
5204           MemOpChains.push_back(Load.getValue(1));
5205           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5206 
5207           ArgOffset += PtrByteSize;
5208           continue;
5209         }
5210       }
5211 
5212       if (GPR_idx == NumGPRs && Size < 8) {
5213         SDValue AddPtr = PtrOff;
5214         if (!isLittleEndian) {
5215           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5216                                           PtrOff.getValueType());
5217           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5218         }
5219         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5220                                                           CallSeqStart,
5221                                                           Flags, DAG, dl);
5222         ArgOffset += PtrByteSize;
5223         continue;
5224       }
5225       // Copy entire object into memory.  There are cases where gcc-generated
5226       // code assumes it is there, even if it could be put entirely into
5227       // registers.  (This is not what the doc says.)
5228 
5229       // FIXME: The above statement is likely due to a misunderstanding of the
5230       // documents.  All arguments must be copied into the parameter area BY
5231       // THE CALLEE in the event that the callee takes the address of any
5232       // formal argument.  That has not yet been implemented.  However, it is
5233       // reasonable to use the stack area as a staging area for the register
5234       // load.
5235 
5236       // Skip this for small aggregates, as we will use the same slot for a
5237       // right-justified copy, below.
5238       if (Size >= 8)
5239         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5240                                                           CallSeqStart,
5241                                                           Flags, DAG, dl);
5242 
5243       // When a register is available, pass a small aggregate right-justified.
5244       if (Size < 8 && GPR_idx != NumGPRs) {
5245         // The easiest way to get this right-justified in a register
5246         // is to copy the structure into the rightmost portion of a
5247         // local variable slot, then load the whole slot into the
5248         // register.
5249         // FIXME: The memcpy seems to produce pretty awful code for
5250         // small aggregates, particularly for packed ones.
5251         // FIXME: It would be preferable to use the slot in the
5252         // parameter save area instead of a new local variable.
5253         SDValue AddPtr = PtrOff;
5254         if (!isLittleEndian) {
5255           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5256           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5257         }
5258         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5259                                                           CallSeqStart,
5260                                                           Flags, DAG, dl);
5261 
5262         // Load the slot into the register.
5263         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5264                                    MachinePointerInfo(),
5265                                    false, false, false, 0);
5266         MemOpChains.push_back(Load.getValue(1));
5267         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5268 
5269         // Done with this argument.
5270         ArgOffset += PtrByteSize;
5271         continue;
5272       }
5273 
5274       // For aggregates larger than PtrByteSize, copy the pieces of the
5275       // object that fit into registers from the parameter save area.
5276       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5277         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5278         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5279         if (GPR_idx != NumGPRs) {
5280           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5281                                      MachinePointerInfo(),
5282                                      false, false, false, 0);
5283           MemOpChains.push_back(Load.getValue(1));
5284           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5285           ArgOffset += PtrByteSize;
5286         } else {
5287           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5288           break;
5289         }
5290       }
5291       continue;
5292     }
5293 
5294     switch (Arg.getSimpleValueType().SimpleTy) {
5295     default: llvm_unreachable("Unexpected ValueType for argument!");
5296     case MVT::i1:
5297     case MVT::i32:
5298     case MVT::i64:
5299       if (Flags.isNest()) {
5300         // The 'nest' parameter, if any, is passed in R11.
5301         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5302         hasNest = true;
5303         break;
5304       }
5305 
5306       // These can be scalar arguments or elements of an integer array type
5307       // passed directly.  Clang may use those instead of "byval" aggregate
5308       // types to avoid forcing arguments to memory unnecessarily.
5309       if (GPR_idx != NumGPRs) {
5310         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5311       } else {
5312         if (CallConv == CallingConv::Fast)
5313           ComputePtrOff();
5314 
5315         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5316                          true, isTailCall, false, MemOpChains,
5317                          TailCallArguments, dl);
5318         if (CallConv == CallingConv::Fast)
5319           ArgOffset += PtrByteSize;
5320       }
5321       if (CallConv != CallingConv::Fast)
5322         ArgOffset += PtrByteSize;
5323       break;
5324     case MVT::f32:
5325     case MVT::f64: {
5326       // These can be scalar arguments or elements of a float array type
5327       // passed directly.  The latter are used to implement ELFv2 homogenous
5328       // float aggregates.
5329 
5330       // Named arguments go into FPRs first, and once they overflow, the
5331       // remaining arguments go into GPRs and then the parameter save area.
5332       // Unnamed arguments for vararg functions always go to GPRs and
5333       // then the parameter save area.  For now, put all arguments to vararg
5334       // routines always in both locations (FPR *and* GPR or stack slot).
5335       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5336       bool NeededLoad = false;
5337 
5338       // First load the argument into the next available FPR.
5339       if (FPR_idx != NumFPRs)
5340         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5341 
5342       // Next, load the argument into GPR or stack slot if needed.
5343       if (!NeedGPROrStack)
5344         ;
5345       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5346         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5347         // once we support fp <-> gpr moves.
5348 
5349         // In the non-vararg case, this can only ever happen in the
5350         // presence of f32 array types, since otherwise we never run
5351         // out of FPRs before running out of GPRs.
5352         SDValue ArgVal;
5353 
5354         // Double values are always passed in a single GPR.
5355         if (Arg.getValueType() != MVT::f32) {
5356           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5357 
5358         // Non-array float values are extended and passed in a GPR.
5359         } else if (!Flags.isInConsecutiveRegs()) {
5360           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5361           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5362 
5363         // If we have an array of floats, we collect every odd element
5364         // together with its predecessor into one GPR.
5365         } else if (ArgOffset % PtrByteSize != 0) {
5366           SDValue Lo, Hi;
5367           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5368           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5369           if (!isLittleEndian)
5370             std::swap(Lo, Hi);
5371           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5372 
5373         // The final element, if even, goes into the first half of a GPR.
5374         } else if (Flags.isInConsecutiveRegsLast()) {
5375           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5376           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5377           if (!isLittleEndian)
5378             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5379                                  DAG.getConstant(32, dl, MVT::i32));
5380 
5381         // Non-final even elements are skipped; they will be handled
5382         // together the with subsequent argument on the next go-around.
5383         } else
5384           ArgVal = SDValue();
5385 
5386         if (ArgVal.getNode())
5387           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5388       } else {
5389         if (CallConv == CallingConv::Fast)
5390           ComputePtrOff();
5391 
5392         // Single-precision floating-point values are mapped to the
5393         // second (rightmost) word of the stack doubleword.
5394         if (Arg.getValueType() == MVT::f32 &&
5395             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5396           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5397           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5398         }
5399 
5400         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5401                          true, isTailCall, false, MemOpChains,
5402                          TailCallArguments, dl);
5403 
5404         NeededLoad = true;
5405       }
5406       // When passing an array of floats, the array occupies consecutive
5407       // space in the argument area; only round up to the next doubleword
5408       // at the end of the array.  Otherwise, each float takes 8 bytes.
5409       if (CallConv != CallingConv::Fast || NeededLoad) {
5410         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5411                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5412         if (Flags.isInConsecutiveRegsLast())
5413           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5414       }
5415       break;
5416     }
5417     case MVT::v4f32:
5418     case MVT::v4i32:
5419     case MVT::v8i16:
5420     case MVT::v16i8:
5421     case MVT::v2f64:
5422     case MVT::v2i64:
5423     case MVT::v1i128:
5424       if (!Subtarget.hasQPX()) {
5425       // These can be scalar arguments or elements of a vector array type
5426       // passed directly.  The latter are used to implement ELFv2 homogenous
5427       // vector aggregates.
5428 
5429       // For a varargs call, named arguments go into VRs or on the stack as
5430       // usual; unnamed arguments always go to the stack or the corresponding
5431       // GPRs when within range.  For now, we always put the value in both
5432       // locations (or even all three).
5433       if (isVarArg) {
5434         // We could elide this store in the case where the object fits
5435         // entirely in R registers.  Maybe later.
5436         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5437                                      MachinePointerInfo(), false, false, 0);
5438         MemOpChains.push_back(Store);
5439         if (VR_idx != NumVRs) {
5440           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5441                                      MachinePointerInfo(),
5442                                      false, false, false, 0);
5443           MemOpChains.push_back(Load.getValue(1));
5444 
5445           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5446                            Arg.getSimpleValueType() == MVT::v2i64) ?
5447                           VSRH[VR_idx] : VR[VR_idx];
5448           ++VR_idx;
5449 
5450           RegsToPass.push_back(std::make_pair(VReg, Load));
5451         }
5452         ArgOffset += 16;
5453         for (unsigned i=0; i<16; i+=PtrByteSize) {
5454           if (GPR_idx == NumGPRs)
5455             break;
5456           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5457                                    DAG.getConstant(i, dl, PtrVT));
5458           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5459                                      false, false, false, 0);
5460           MemOpChains.push_back(Load.getValue(1));
5461           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5462         }
5463         break;
5464       }
5465 
5466       // Non-varargs Altivec params go into VRs or on the stack.
5467       if (VR_idx != NumVRs) {
5468         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5469                          Arg.getSimpleValueType() == MVT::v2i64) ?
5470                         VSRH[VR_idx] : VR[VR_idx];
5471         ++VR_idx;
5472 
5473         RegsToPass.push_back(std::make_pair(VReg, Arg));
5474       } else {
5475         if (CallConv == CallingConv::Fast)
5476           ComputePtrOff();
5477 
5478         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5479                          true, isTailCall, true, MemOpChains,
5480                          TailCallArguments, dl);
5481         if (CallConv == CallingConv::Fast)
5482           ArgOffset += 16;
5483       }
5484 
5485       if (CallConv != CallingConv::Fast)
5486         ArgOffset += 16;
5487       break;
5488       } // not QPX
5489 
5490       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5491              "Invalid QPX parameter type");
5492 
5493       /* fall through */
5494     case MVT::v4f64:
5495     case MVT::v4i1: {
5496       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5497       if (isVarArg) {
5498         // We could elide this store in the case where the object fits
5499         // entirely in R registers.  Maybe later.
5500         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5501                                      MachinePointerInfo(), false, false, 0);
5502         MemOpChains.push_back(Store);
5503         if (QFPR_idx != NumQFPRs) {
5504           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5505                                      Store, PtrOff, MachinePointerInfo(),
5506                                      false, false, false, 0);
5507           MemOpChains.push_back(Load.getValue(1));
5508           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5509         }
5510         ArgOffset += (IsF32 ? 16 : 32);
5511         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5512           if (GPR_idx == NumGPRs)
5513             break;
5514           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5515                                    DAG.getConstant(i, dl, PtrVT));
5516           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5517                                      false, false, false, 0);
5518           MemOpChains.push_back(Load.getValue(1));
5519           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5520         }
5521         break;
5522       }
5523 
5524       // Non-varargs QPX params go into registers or on the stack.
5525       if (QFPR_idx != NumQFPRs) {
5526         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5527       } else {
5528         if (CallConv == CallingConv::Fast)
5529           ComputePtrOff();
5530 
5531         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5532                          true, isTailCall, true, MemOpChains,
5533                          TailCallArguments, dl);
5534         if (CallConv == CallingConv::Fast)
5535           ArgOffset += (IsF32 ? 16 : 32);
5536       }
5537 
5538       if (CallConv != CallingConv::Fast)
5539         ArgOffset += (IsF32 ? 16 : 32);
5540       break;
5541       }
5542     }
5543   }
5544 
5545   assert(NumBytesActuallyUsed == ArgOffset);
5546   (void)NumBytesActuallyUsed;
5547 
5548   if (!MemOpChains.empty())
5549     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5550 
5551   // Check if this is an indirect call (MTCTR/BCTRL).
5552   // See PrepareCall() for more information about calls through function
5553   // pointers in the 64-bit SVR4 ABI.
5554   if (!isTailCall && !IsPatchPoint &&
5555       !isFunctionGlobalAddress(Callee) &&
5556       !isa<ExternalSymbolSDNode>(Callee)) {
5557     // Load r2 into a virtual register and store it to the TOC save area.
5558     setUsesTOCBasePtr(DAG);
5559     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5560     // TOC save area offset.
5561     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5562     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5563     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5564     Chain = DAG.getStore(
5565         Val.getValue(1), dl, Val, AddPtr,
5566         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset),
5567         false, false, 0);
5568     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5569     // This does not mean the MTCTR instruction must use R12; it's easier
5570     // to model this as an extra parameter, so do that.
5571     if (isELFv2ABI && !IsPatchPoint)
5572       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5573   }
5574 
5575   // Build a sequence of copy-to-reg nodes chained together with token chain
5576   // and flag operands which copy the outgoing args into the appropriate regs.
5577   SDValue InFlag;
5578   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5579     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5580                              RegsToPass[i].second, InFlag);
5581     InFlag = Chain.getValue(1);
5582   }
5583 
5584   if (isTailCall && !IsSibCall)
5585     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5586                     FPOp, true, TailCallArguments);
5587 
5588   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, hasNest,
5589                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5590                     SPDiff, NumBytes, Ins, InVals, CS);
5591 }
5592 
5593 SDValue
5594 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5595                                     CallingConv::ID CallConv, bool isVarArg,
5596                                     bool isTailCall, bool IsPatchPoint,
5597                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5598                                     const SmallVectorImpl<SDValue> &OutVals,
5599                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5600                                     SDLoc dl, SelectionDAG &DAG,
5601                                     SmallVectorImpl<SDValue> &InVals,
5602                                     ImmutableCallSite *CS) const {
5603 
5604   unsigned NumOps = Outs.size();
5605 
5606   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5607   bool isPPC64 = PtrVT == MVT::i64;
5608   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5609 
5610   MachineFunction &MF = DAG.getMachineFunction();
5611 
5612   // Mark this function as potentially containing a function that contains a
5613   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5614   // and restoring the callers stack pointer in this functions epilog. This is
5615   // done because by tail calling the called function might overwrite the value
5616   // in this function's (MF) stack pointer stack slot 0(SP).
5617   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5618       CallConv == CallingConv::Fast)
5619     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5620 
5621   // Count how many bytes are to be pushed on the stack, including the linkage
5622   // area, and parameter passing area.  We start with 24/48 bytes, which is
5623   // prereserved space for [SP][CR][LR][3 x unused].
5624   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5625   unsigned NumBytes = LinkageSize;
5626 
5627   // Add up all the space actually used.
5628   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5629   // they all go in registers, but we must reserve stack space for them for
5630   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5631   // assigned stack space in order, with padding so Altivec parameters are
5632   // 16-byte aligned.
5633   unsigned nAltivecParamsAtEnd = 0;
5634   for (unsigned i = 0; i != NumOps; ++i) {
5635     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5636     EVT ArgVT = Outs[i].VT;
5637     // Varargs Altivec parameters are padded to a 16 byte boundary.
5638     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5639         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5640         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5641       if (!isVarArg && !isPPC64) {
5642         // Non-varargs Altivec parameters go after all the non-Altivec
5643         // parameters; handle those later so we know how much padding we need.
5644         nAltivecParamsAtEnd++;
5645         continue;
5646       }
5647       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5648       NumBytes = ((NumBytes+15)/16)*16;
5649     }
5650     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5651   }
5652 
5653   // Allow for Altivec parameters at the end, if needed.
5654   if (nAltivecParamsAtEnd) {
5655     NumBytes = ((NumBytes+15)/16)*16;
5656     NumBytes += 16*nAltivecParamsAtEnd;
5657   }
5658 
5659   // The prolog code of the callee may store up to 8 GPR argument registers to
5660   // the stack, allowing va_start to index over them in memory if its varargs.
5661   // Because we cannot tell if this is needed on the caller side, we have to
5662   // conservatively assume that it is needed.  As such, make sure we have at
5663   // least enough stack space for the caller to store the 8 GPRs.
5664   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5665 
5666   // Tail call needs the stack to be aligned.
5667   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5668       CallConv == CallingConv::Fast)
5669     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5670 
5671   // Calculate by how many bytes the stack has to be adjusted in case of tail
5672   // call optimization.
5673   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5674 
5675   // To protect arguments on the stack from being clobbered in a tail call,
5676   // force all the loads to happen before doing any other lowering.
5677   if (isTailCall)
5678     Chain = DAG.getStackArgumentTokenFactor(Chain);
5679 
5680   // Adjust the stack pointer for the new arguments...
5681   // These operations are automatically eliminated by the prolog/epilog pass
5682   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5683                                dl);
5684   SDValue CallSeqStart = Chain;
5685 
5686   // Load the return address and frame pointer so it can be move somewhere else
5687   // later.
5688   SDValue LROp, FPOp;
5689   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5690                                        dl);
5691 
5692   // Set up a copy of the stack pointer for use loading and storing any
5693   // arguments that may not fit in the registers available for argument
5694   // passing.
5695   SDValue StackPtr;
5696   if (isPPC64)
5697     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5698   else
5699     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5700 
5701   // Figure out which arguments are going to go in registers, and which in
5702   // memory.  Also, if this is a vararg function, floating point operations
5703   // must be stored to our stack, and loaded into integer regs as well, if
5704   // any integer regs are available for argument passing.
5705   unsigned ArgOffset = LinkageSize;
5706   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5707 
5708   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5709     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5710     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5711   };
5712   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5713     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5714     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5715   };
5716   static const MCPhysReg VR[] = {
5717     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5718     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5719   };
5720   const unsigned NumGPRs = array_lengthof(GPR_32);
5721   const unsigned NumFPRs = 13;
5722   const unsigned NumVRs  = array_lengthof(VR);
5723 
5724   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5725 
5726   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5727   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5728 
5729   SmallVector<SDValue, 8> MemOpChains;
5730   for (unsigned i = 0; i != NumOps; ++i) {
5731     SDValue Arg = OutVals[i];
5732     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5733 
5734     // PtrOff will be used to store the current argument to the stack if a
5735     // register cannot be found for it.
5736     SDValue PtrOff;
5737 
5738     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5739 
5740     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5741 
5742     // On PPC64, promote integers to 64-bit values.
5743     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5744       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5745       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5746       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5747     }
5748 
5749     // FIXME memcpy is used way more than necessary.  Correctness first.
5750     // Note: "by value" is code for passing a structure by value, not
5751     // basic types.
5752     if (Flags.isByVal()) {
5753       unsigned Size = Flags.getByValSize();
5754       // Very small objects are passed right-justified.  Everything else is
5755       // passed left-justified.
5756       if (Size==1 || Size==2) {
5757         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5758         if (GPR_idx != NumGPRs) {
5759           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5760                                         MachinePointerInfo(), VT,
5761                                         false, false, false, 0);
5762           MemOpChains.push_back(Load.getValue(1));
5763           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5764 
5765           ArgOffset += PtrByteSize;
5766         } else {
5767           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5768                                           PtrOff.getValueType());
5769           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5770           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5771                                                             CallSeqStart,
5772                                                             Flags, DAG, dl);
5773           ArgOffset += PtrByteSize;
5774         }
5775         continue;
5776       }
5777       // Copy entire object into memory.  There are cases where gcc-generated
5778       // code assumes it is there, even if it could be put entirely into
5779       // registers.  (This is not what the doc says.)
5780       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5781                                                         CallSeqStart,
5782                                                         Flags, DAG, dl);
5783 
5784       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5785       // copy the pieces of the object that fit into registers from the
5786       // parameter save area.
5787       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5788         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5789         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5790         if (GPR_idx != NumGPRs) {
5791           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5792                                      MachinePointerInfo(),
5793                                      false, false, false, 0);
5794           MemOpChains.push_back(Load.getValue(1));
5795           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5796           ArgOffset += PtrByteSize;
5797         } else {
5798           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5799           break;
5800         }
5801       }
5802       continue;
5803     }
5804 
5805     switch (Arg.getSimpleValueType().SimpleTy) {
5806     default: llvm_unreachable("Unexpected ValueType for argument!");
5807     case MVT::i1:
5808     case MVT::i32:
5809     case MVT::i64:
5810       if (GPR_idx != NumGPRs) {
5811         if (Arg.getValueType() == MVT::i1)
5812           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5813 
5814         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5815       } else {
5816         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5817                          isPPC64, isTailCall, false, MemOpChains,
5818                          TailCallArguments, dl);
5819       }
5820       ArgOffset += PtrByteSize;
5821       break;
5822     case MVT::f32:
5823     case MVT::f64:
5824       if (FPR_idx != NumFPRs) {
5825         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5826 
5827         if (isVarArg) {
5828           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5829                                        MachinePointerInfo(), false, false, 0);
5830           MemOpChains.push_back(Store);
5831 
5832           // Float varargs are always shadowed in available integer registers
5833           if (GPR_idx != NumGPRs) {
5834             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5835                                        MachinePointerInfo(), false, false,
5836                                        false, 0);
5837             MemOpChains.push_back(Load.getValue(1));
5838             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5839           }
5840           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5841             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5842             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5843             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5844                                        MachinePointerInfo(),
5845                                        false, false, false, 0);
5846             MemOpChains.push_back(Load.getValue(1));
5847             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5848           }
5849         } else {
5850           // If we have any FPRs remaining, we may also have GPRs remaining.
5851           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5852           // GPRs.
5853           if (GPR_idx != NumGPRs)
5854             ++GPR_idx;
5855           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5856               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5857             ++GPR_idx;
5858         }
5859       } else
5860         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5861                          isPPC64, isTailCall, false, MemOpChains,
5862                          TailCallArguments, dl);
5863       if (isPPC64)
5864         ArgOffset += 8;
5865       else
5866         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5867       break;
5868     case MVT::v4f32:
5869     case MVT::v4i32:
5870     case MVT::v8i16:
5871     case MVT::v16i8:
5872       if (isVarArg) {
5873         // These go aligned on the stack, or in the corresponding R registers
5874         // when within range.  The Darwin PPC ABI doc claims they also go in
5875         // V registers; in fact gcc does this only for arguments that are
5876         // prototyped, not for those that match the ...  We do it for all
5877         // arguments, seems to work.
5878         while (ArgOffset % 16 !=0) {
5879           ArgOffset += PtrByteSize;
5880           if (GPR_idx != NumGPRs)
5881             GPR_idx++;
5882         }
5883         // We could elide this store in the case where the object fits
5884         // entirely in R registers.  Maybe later.
5885         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5886                              DAG.getConstant(ArgOffset, dl, PtrVT));
5887         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5888                                      MachinePointerInfo(), false, false, 0);
5889         MemOpChains.push_back(Store);
5890         if (VR_idx != NumVRs) {
5891           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5892                                      MachinePointerInfo(),
5893                                      false, false, false, 0);
5894           MemOpChains.push_back(Load.getValue(1));
5895           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5896         }
5897         ArgOffset += 16;
5898         for (unsigned i=0; i<16; i+=PtrByteSize) {
5899           if (GPR_idx == NumGPRs)
5900             break;
5901           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5902                                    DAG.getConstant(i, dl, PtrVT));
5903           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5904                                      false, false, false, 0);
5905           MemOpChains.push_back(Load.getValue(1));
5906           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5907         }
5908         break;
5909       }
5910 
5911       // Non-varargs Altivec params generally go in registers, but have
5912       // stack space allocated at the end.
5913       if (VR_idx != NumVRs) {
5914         // Doesn't have GPR space allocated.
5915         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5916       } else if (nAltivecParamsAtEnd==0) {
5917         // We are emitting Altivec params in order.
5918         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5919                          isPPC64, isTailCall, true, MemOpChains,
5920                          TailCallArguments, dl);
5921         ArgOffset += 16;
5922       }
5923       break;
5924     }
5925   }
5926   // If all Altivec parameters fit in registers, as they usually do,
5927   // they get stack space following the non-Altivec parameters.  We
5928   // don't track this here because nobody below needs it.
5929   // If there are more Altivec parameters than fit in registers emit
5930   // the stores here.
5931   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5932     unsigned j = 0;
5933     // Offset is aligned; skip 1st 12 params which go in V registers.
5934     ArgOffset = ((ArgOffset+15)/16)*16;
5935     ArgOffset += 12*16;
5936     for (unsigned i = 0; i != NumOps; ++i) {
5937       SDValue Arg = OutVals[i];
5938       EVT ArgType = Outs[i].VT;
5939       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5940           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5941         if (++j > NumVRs) {
5942           SDValue PtrOff;
5943           // We are emitting Altivec params in order.
5944           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5945                            isPPC64, isTailCall, true, MemOpChains,
5946                            TailCallArguments, dl);
5947           ArgOffset += 16;
5948         }
5949       }
5950     }
5951   }
5952 
5953   if (!MemOpChains.empty())
5954     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5955 
5956   // On Darwin, R12 must contain the address of an indirect callee.  This does
5957   // not mean the MTCTR instruction must use R12; it's easier to model this as
5958   // an extra parameter, so do that.
5959   if (!isTailCall &&
5960       !isFunctionGlobalAddress(Callee) &&
5961       !isa<ExternalSymbolSDNode>(Callee) &&
5962       !isBLACompatibleAddress(Callee, DAG))
5963     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5964                                                    PPC::R12), Callee));
5965 
5966   // Build a sequence of copy-to-reg nodes chained together with token chain
5967   // and flag operands which copy the outgoing args into the appropriate regs.
5968   SDValue InFlag;
5969   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5970     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5971                              RegsToPass[i].second, InFlag);
5972     InFlag = Chain.getValue(1);
5973   }
5974 
5975   if (isTailCall)
5976     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5977                     FPOp, true, TailCallArguments);
5978 
5979   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5980                     /* unused except on PPC64 ELFv1 */ false, DAG,
5981                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5982                     NumBytes, Ins, InVals, CS);
5983 }
5984 
5985 bool
5986 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5987                                   MachineFunction &MF, bool isVarArg,
5988                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5989                                   LLVMContext &Context) const {
5990   SmallVector<CCValAssign, 16> RVLocs;
5991   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5992   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5993 }
5994 
5995 SDValue
5996 PPCTargetLowering::LowerReturn(SDValue Chain,
5997                                CallingConv::ID CallConv, bool isVarArg,
5998                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5999                                const SmallVectorImpl<SDValue> &OutVals,
6000                                SDLoc dl, SelectionDAG &DAG) const {
6001 
6002   SmallVector<CCValAssign, 16> RVLocs;
6003   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6004                  *DAG.getContext());
6005   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6006 
6007   SDValue Flag;
6008   SmallVector<SDValue, 4> RetOps(1, Chain);
6009 
6010   // Copy the result values into the output registers.
6011   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6012     CCValAssign &VA = RVLocs[i];
6013     assert(VA.isRegLoc() && "Can only return in registers!");
6014 
6015     SDValue Arg = OutVals[i];
6016 
6017     switch (VA.getLocInfo()) {
6018     default: llvm_unreachable("Unknown loc info!");
6019     case CCValAssign::Full: break;
6020     case CCValAssign::AExt:
6021       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6022       break;
6023     case CCValAssign::ZExt:
6024       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6025       break;
6026     case CCValAssign::SExt:
6027       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6028       break;
6029     }
6030 
6031     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6032     Flag = Chain.getValue(1);
6033     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6034   }
6035 
6036   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6037   const MCPhysReg *I =
6038     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6039   if (I) {
6040     for (; *I; ++I) {
6041 
6042       if (PPC::G8RCRegClass.contains(*I))
6043         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6044       else if (PPC::F8RCRegClass.contains(*I))
6045         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6046       else if (PPC::CRRCRegClass.contains(*I))
6047         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6048       else if (PPC::VRRCRegClass.contains(*I))
6049         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6050       else
6051         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6052     }
6053   }
6054 
6055   RetOps[0] = Chain;  // Update chain.
6056 
6057   // Add the flag if we have it.
6058   if (Flag.getNode())
6059     RetOps.push_back(Flag);
6060 
6061   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6062 }
6063 
6064 SDValue PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(
6065     SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const {
6066   SDLoc dl(Op);
6067 
6068   // Get the corect type for integers.
6069   EVT IntVT = Op.getValueType();
6070 
6071   // Get the inputs.
6072   SDValue Chain = Op.getOperand(0);
6073   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6074   // Build a DYNAREAOFFSET node.
6075   SDValue Ops[2] = {Chain, FPSIdx};
6076   SDVTList VTs = DAG.getVTList(IntVT);
6077   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6078 }
6079 
6080 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
6081                                    const PPCSubtarget &Subtarget) const {
6082   // When we pop the dynamic allocation we need to restore the SP link.
6083   SDLoc dl(Op);
6084 
6085   // Get the corect type for pointers.
6086   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6087 
6088   // Construct the stack pointer operand.
6089   bool isPPC64 = Subtarget.isPPC64();
6090   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6091   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6092 
6093   // Get the operands for the STACKRESTORE.
6094   SDValue Chain = Op.getOperand(0);
6095   SDValue SaveSP = Op.getOperand(1);
6096 
6097   // Load the old link SP.
6098   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
6099                                    MachinePointerInfo(),
6100                                    false, false, false, 0);
6101 
6102   // Restore the stack pointer.
6103   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6104 
6105   // Store the old link SP.
6106   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
6107                       false, false, 0);
6108 }
6109 
6110 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6111   MachineFunction &MF = DAG.getMachineFunction();
6112   bool isPPC64 = Subtarget.isPPC64();
6113   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6114 
6115   // Get current frame pointer save index.  The users of this index will be
6116   // primarily DYNALLOC instructions.
6117   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6118   int RASI = FI->getReturnAddrSaveIndex();
6119 
6120   // If the frame pointer save index hasn't been defined yet.
6121   if (!RASI) {
6122     // Find out what the fix offset of the frame pointer save area.
6123     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6124     // Allocate the frame index for frame pointer save area.
6125     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6126     // Save the result.
6127     FI->setReturnAddrSaveIndex(RASI);
6128   }
6129   return DAG.getFrameIndex(RASI, PtrVT);
6130 }
6131 
6132 SDValue
6133 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6134   MachineFunction &MF = DAG.getMachineFunction();
6135   bool isPPC64 = Subtarget.isPPC64();
6136   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6137 
6138   // Get current frame pointer save index.  The users of this index will be
6139   // primarily DYNALLOC instructions.
6140   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6141   int FPSI = FI->getFramePointerSaveIndex();
6142 
6143   // If the frame pointer save index hasn't been defined yet.
6144   if (!FPSI) {
6145     // Find out what the fix offset of the frame pointer save area.
6146     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6147     // Allocate the frame index for frame pointer save area.
6148     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6149     // Save the result.
6150     FI->setFramePointerSaveIndex(FPSI);
6151   }
6152   return DAG.getFrameIndex(FPSI, PtrVT);
6153 }
6154 
6155 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6156                                          SelectionDAG &DAG,
6157                                          const PPCSubtarget &Subtarget) const {
6158   // Get the inputs.
6159   SDValue Chain = Op.getOperand(0);
6160   SDValue Size  = Op.getOperand(1);
6161   SDLoc dl(Op);
6162 
6163   // Get the corect type for pointers.
6164   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6165   // Negate the size.
6166   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6167                                 DAG.getConstant(0, dl, PtrVT), Size);
6168   // Construct a node for the frame pointer save index.
6169   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6170   // Build a DYNALLOC node.
6171   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6172   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6173   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6174 }
6175 
6176 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6177                                                SelectionDAG &DAG) const {
6178   SDLoc DL(Op);
6179   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6180                      DAG.getVTList(MVT::i32, MVT::Other),
6181                      Op.getOperand(0), Op.getOperand(1));
6182 }
6183 
6184 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6185                                                 SelectionDAG &DAG) const {
6186   SDLoc DL(Op);
6187   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6188                      Op.getOperand(0), Op.getOperand(1));
6189 }
6190 
6191 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6192   if (Op.getValueType().isVector())
6193     return LowerVectorLoad(Op, DAG);
6194 
6195   assert(Op.getValueType() == MVT::i1 &&
6196          "Custom lowering only for i1 loads");
6197 
6198   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6199 
6200   SDLoc dl(Op);
6201   LoadSDNode *LD = cast<LoadSDNode>(Op);
6202 
6203   SDValue Chain = LD->getChain();
6204   SDValue BasePtr = LD->getBasePtr();
6205   MachineMemOperand *MMO = LD->getMemOperand();
6206 
6207   SDValue NewLD =
6208       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6209                      BasePtr, MVT::i8, MMO);
6210   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6211 
6212   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6213   return DAG.getMergeValues(Ops, dl);
6214 }
6215 
6216 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6217   if (Op.getOperand(1).getValueType().isVector())
6218     return LowerVectorStore(Op, DAG);
6219 
6220   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6221          "Custom lowering only for i1 stores");
6222 
6223   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6224 
6225   SDLoc dl(Op);
6226   StoreSDNode *ST = cast<StoreSDNode>(Op);
6227 
6228   SDValue Chain = ST->getChain();
6229   SDValue BasePtr = ST->getBasePtr();
6230   SDValue Value = ST->getValue();
6231   MachineMemOperand *MMO = ST->getMemOperand();
6232 
6233   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6234                       Value);
6235   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6236 }
6237 
6238 // FIXME: Remove this once the ANDI glue bug is fixed:
6239 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6240   assert(Op.getValueType() == MVT::i1 &&
6241          "Custom lowering only for i1 results");
6242 
6243   SDLoc DL(Op);
6244   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6245                      Op.getOperand(0));
6246 }
6247 
6248 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6249 /// possible.
6250 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6251   // Not FP? Not a fsel.
6252   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6253       !Op.getOperand(2).getValueType().isFloatingPoint())
6254     return Op;
6255 
6256   // We might be able to do better than this under some circumstances, but in
6257   // general, fsel-based lowering of select is a finite-math-only optimization.
6258   // For more information, see section F.3 of the 2.06 ISA specification.
6259   if (!DAG.getTarget().Options.NoInfsFPMath ||
6260       !DAG.getTarget().Options.NoNaNsFPMath)
6261     return Op;
6262   // TODO: Propagate flags from the select rather than global settings.
6263   SDNodeFlags Flags;
6264   Flags.setNoInfs(true);
6265   Flags.setNoNaNs(true);
6266 
6267   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6268 
6269   EVT ResVT = Op.getValueType();
6270   EVT CmpVT = Op.getOperand(0).getValueType();
6271   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6272   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6273   SDLoc dl(Op);
6274 
6275   // If the RHS of the comparison is a 0.0, we don't need to do the
6276   // subtraction at all.
6277   SDValue Sel1;
6278   if (isFloatingPointZero(RHS))
6279     switch (CC) {
6280     default: break;       // SETUO etc aren't handled by fsel.
6281     case ISD::SETNE:
6282       std::swap(TV, FV);
6283     case ISD::SETEQ:
6284       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6285         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6286       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6287       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6288         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6289       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6290                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6291     case ISD::SETULT:
6292     case ISD::SETLT:
6293       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6294     case ISD::SETOGE:
6295     case ISD::SETGE:
6296       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6297         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6298       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6299     case ISD::SETUGT:
6300     case ISD::SETGT:
6301       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6302     case ISD::SETOLE:
6303     case ISD::SETLE:
6304       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6305         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6306       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6307                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6308     }
6309 
6310   SDValue Cmp;
6311   switch (CC) {
6312   default: break;       // SETUO etc aren't handled by fsel.
6313   case ISD::SETNE:
6314     std::swap(TV, FV);
6315   case ISD::SETEQ:
6316     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6317     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6318       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6319     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6320     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6321       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6322     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6323                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6324   case ISD::SETULT:
6325   case ISD::SETLT:
6326     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6327     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6328       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6329     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6330   case ISD::SETOGE:
6331   case ISD::SETGE:
6332     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6333     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6334       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6335     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6336   case ISD::SETUGT:
6337   case ISD::SETGT:
6338     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6339     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6340       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6341     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6342   case ISD::SETOLE:
6343   case ISD::SETLE:
6344     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6345     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6346       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6347     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6348   }
6349   return Op;
6350 }
6351 
6352 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6353                                                SelectionDAG &DAG,
6354                                                SDLoc dl) const {
6355   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6356   SDValue Src = Op.getOperand(0);
6357   if (Src.getValueType() == MVT::f32)
6358     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6359 
6360   SDValue Tmp;
6361   switch (Op.getSimpleValueType().SimpleTy) {
6362   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6363   case MVT::i32:
6364     Tmp = DAG.getNode(
6365         Op.getOpcode() == ISD::FP_TO_SINT
6366             ? PPCISD::FCTIWZ
6367             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6368         dl, MVT::f64, Src);
6369     break;
6370   case MVT::i64:
6371     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6372            "i64 FP_TO_UINT is supported only with FPCVT");
6373     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6374                                                         PPCISD::FCTIDUZ,
6375                       dl, MVT::f64, Src);
6376     break;
6377   }
6378 
6379   // Convert the FP value to an int value through memory.
6380   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6381     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6382   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6383   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6384   MachinePointerInfo MPI =
6385       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6386 
6387   // Emit a store to the stack slot.
6388   SDValue Chain;
6389   if (i32Stack) {
6390     MachineFunction &MF = DAG.getMachineFunction();
6391     MachineMemOperand *MMO =
6392       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6393     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6394     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6395               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6396   } else
6397     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6398                          MPI, false, false, 0);
6399 
6400   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6401   // add in a bias on big endian.
6402   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6403     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6404                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6405     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6406   }
6407 
6408   RLI.Chain = Chain;
6409   RLI.Ptr = FIPtr;
6410   RLI.MPI = MPI;
6411 }
6412 
6413 /// \brief Custom lowers floating point to integer conversions to use
6414 /// the direct move instructions available in ISA 2.07 to avoid the
6415 /// need for load/store combinations.
6416 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6417                                                     SelectionDAG &DAG,
6418                                                     SDLoc dl) const {
6419   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6420   SDValue Src = Op.getOperand(0);
6421 
6422   if (Src.getValueType() == MVT::f32)
6423     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6424 
6425   SDValue Tmp;
6426   switch (Op.getSimpleValueType().SimpleTy) {
6427   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6428   case MVT::i32:
6429     Tmp = DAG.getNode(
6430         Op.getOpcode() == ISD::FP_TO_SINT
6431             ? PPCISD::FCTIWZ
6432             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6433         dl, MVT::f64, Src);
6434     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6435     break;
6436   case MVT::i64:
6437     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6438            "i64 FP_TO_UINT is supported only with FPCVT");
6439     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6440                                                         PPCISD::FCTIDUZ,
6441                       dl, MVT::f64, Src);
6442     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6443     break;
6444   }
6445   return Tmp;
6446 }
6447 
6448 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6449                                           SDLoc dl) const {
6450   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6451     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6452 
6453   ReuseLoadInfo RLI;
6454   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6455 
6456   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6457                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6458                      RLI.Ranges);
6459 }
6460 
6461 // We're trying to insert a regular store, S, and then a load, L. If the
6462 // incoming value, O, is a load, we might just be able to have our load use the
6463 // address used by O. However, we don't know if anything else will store to
6464 // that address before we can load from it. To prevent this situation, we need
6465 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6466 // the same chain operand as O, we create a token factor from the chain results
6467 // of O and L, and we replace all uses of O's chain result with that token
6468 // factor (see spliceIntoChain below for this last part).
6469 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6470                                             ReuseLoadInfo &RLI,
6471                                             SelectionDAG &DAG,
6472                                             ISD::LoadExtType ET) const {
6473   SDLoc dl(Op);
6474   if (ET == ISD::NON_EXTLOAD &&
6475       (Op.getOpcode() == ISD::FP_TO_UINT ||
6476        Op.getOpcode() == ISD::FP_TO_SINT) &&
6477       isOperationLegalOrCustom(Op.getOpcode(),
6478                                Op.getOperand(0).getValueType())) {
6479 
6480     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6481     return true;
6482   }
6483 
6484   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6485   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6486       LD->isNonTemporal())
6487     return false;
6488   if (LD->getMemoryVT() != MemVT)
6489     return false;
6490 
6491   RLI.Ptr = LD->getBasePtr();
6492   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6493     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6494            "Non-pre-inc AM on PPC?");
6495     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6496                           LD->getOffset());
6497   }
6498 
6499   RLI.Chain = LD->getChain();
6500   RLI.MPI = LD->getPointerInfo();
6501   RLI.IsInvariant = LD->isInvariant();
6502   RLI.Alignment = LD->getAlignment();
6503   RLI.AAInfo = LD->getAAInfo();
6504   RLI.Ranges = LD->getRanges();
6505 
6506   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6507   return true;
6508 }
6509 
6510 // Given the head of the old chain, ResChain, insert a token factor containing
6511 // it and NewResChain, and make users of ResChain now be users of that token
6512 // factor.
6513 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6514                                         SDValue NewResChain,
6515                                         SelectionDAG &DAG) const {
6516   if (!ResChain)
6517     return;
6518 
6519   SDLoc dl(NewResChain);
6520 
6521   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6522                            NewResChain, DAG.getUNDEF(MVT::Other));
6523   assert(TF.getNode() != NewResChain.getNode() &&
6524          "A new TF really is required here");
6525 
6526   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6527   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6528 }
6529 
6530 /// \brief Analyze profitability of direct move
6531 /// prefer float load to int load plus direct move
6532 /// when there is no integer use of int load
6533 static bool directMoveIsProfitable(const SDValue &Op) {
6534   SDNode *Origin = Op.getOperand(0).getNode();
6535   if (Origin->getOpcode() != ISD::LOAD)
6536     return true;
6537 
6538   for (SDNode::use_iterator UI = Origin->use_begin(),
6539                             UE = Origin->use_end();
6540        UI != UE; ++UI) {
6541 
6542     // Only look at the users of the loaded value.
6543     if (UI.getUse().get().getResNo() != 0)
6544       continue;
6545 
6546     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6547         UI->getOpcode() != ISD::UINT_TO_FP)
6548       return true;
6549   }
6550 
6551   return false;
6552 }
6553 
6554 /// \brief Custom lowers integer to floating point conversions to use
6555 /// the direct move instructions available in ISA 2.07 to avoid the
6556 /// need for load/store combinations.
6557 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6558                                                     SelectionDAG &DAG,
6559                                                     SDLoc dl) const {
6560   assert((Op.getValueType() == MVT::f32 ||
6561           Op.getValueType() == MVT::f64) &&
6562          "Invalid floating point type as target of conversion");
6563   assert(Subtarget.hasFPCVT() &&
6564          "Int to FP conversions with direct moves require FPCVT");
6565   SDValue FP;
6566   SDValue Src = Op.getOperand(0);
6567   bool SinglePrec = Op.getValueType() == MVT::f32;
6568   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6569   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6570   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6571                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6572 
6573   if (WordInt) {
6574     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6575                      dl, MVT::f64, Src);
6576     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6577   }
6578   else {
6579     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6580     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6581   }
6582 
6583   return FP;
6584 }
6585 
6586 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6587                                           SelectionDAG &DAG) const {
6588   SDLoc dl(Op);
6589 
6590   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6591     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6592       return SDValue();
6593 
6594     SDValue Value = Op.getOperand(0);
6595     // The values are now known to be -1 (false) or 1 (true). To convert this
6596     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6597     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6598     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6599 
6600     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6601 
6602     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6603 
6604     if (Op.getValueType() != MVT::v4f64)
6605       Value = DAG.getNode(ISD::FP_ROUND, dl,
6606                           Op.getValueType(), Value,
6607                           DAG.getIntPtrConstant(1, dl));
6608     return Value;
6609   }
6610 
6611   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6612   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6613     return SDValue();
6614 
6615   if (Op.getOperand(0).getValueType() == MVT::i1)
6616     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6617                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6618                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6619 
6620   // If we have direct moves, we can do all the conversion, skip the store/load
6621   // however, without FPCVT we can't do most conversions.
6622   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6623       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6624     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6625 
6626   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6627          "UINT_TO_FP is supported only with FPCVT");
6628 
6629   // If we have FCFIDS, then use it when converting to single-precision.
6630   // Otherwise, convert to double-precision and then round.
6631   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6632                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6633                                                             : PPCISD::FCFIDS)
6634                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6635                                                             : PPCISD::FCFID);
6636   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6637                   ? MVT::f32
6638                   : MVT::f64;
6639 
6640   if (Op.getOperand(0).getValueType() == MVT::i64) {
6641     SDValue SINT = Op.getOperand(0);
6642     // When converting to single-precision, we actually need to convert
6643     // to double-precision first and then round to single-precision.
6644     // To avoid double-rounding effects during that operation, we have
6645     // to prepare the input operand.  Bits that might be truncated when
6646     // converting to double-precision are replaced by a bit that won't
6647     // be lost at this stage, but is below the single-precision rounding
6648     // position.
6649     //
6650     // However, if -enable-unsafe-fp-math is in effect, accept double
6651     // rounding to avoid the extra overhead.
6652     if (Op.getValueType() == MVT::f32 &&
6653         !Subtarget.hasFPCVT() &&
6654         !DAG.getTarget().Options.UnsafeFPMath) {
6655 
6656       // Twiddle input to make sure the low 11 bits are zero.  (If this
6657       // is the case, we are guaranteed the value will fit into the 53 bit
6658       // mantissa of an IEEE double-precision value without rounding.)
6659       // If any of those low 11 bits were not zero originally, make sure
6660       // bit 12 (value 2048) is set instead, so that the final rounding
6661       // to single-precision gets the correct result.
6662       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6663                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6664       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6665                           Round, DAG.getConstant(2047, dl, MVT::i64));
6666       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6667       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6668                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6669 
6670       // However, we cannot use that value unconditionally: if the magnitude
6671       // of the input value is small, the bit-twiddling we did above might
6672       // end up visibly changing the output.  Fortunately, in that case, we
6673       // don't need to twiddle bits since the original input will convert
6674       // exactly to double-precision floating-point already.  Therefore,
6675       // construct a conditional to use the original value if the top 11
6676       // bits are all sign-bit copies, and use the rounded value computed
6677       // above otherwise.
6678       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6679                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6680       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6681                          Cond, DAG.getConstant(1, dl, MVT::i64));
6682       Cond = DAG.getSetCC(dl, MVT::i32,
6683                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6684 
6685       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6686     }
6687 
6688     ReuseLoadInfo RLI;
6689     SDValue Bits;
6690 
6691     MachineFunction &MF = DAG.getMachineFunction();
6692     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6693       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6694                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6695                          RLI.Ranges);
6696       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6697     } else if (Subtarget.hasLFIWAX() &&
6698                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6699       MachineMemOperand *MMO =
6700         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6701                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6702       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6703       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6704                                      DAG.getVTList(MVT::f64, MVT::Other),
6705                                      Ops, MVT::i32, MMO);
6706       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6707     } else if (Subtarget.hasFPCVT() &&
6708                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6709       MachineMemOperand *MMO =
6710         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6711                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6712       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6713       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6714                                      DAG.getVTList(MVT::f64, MVT::Other),
6715                                      Ops, MVT::i32, MMO);
6716       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6717     } else if (((Subtarget.hasLFIWAX() &&
6718                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6719                 (Subtarget.hasFPCVT() &&
6720                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6721                SINT.getOperand(0).getValueType() == MVT::i32) {
6722       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6723       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6724 
6725       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6726       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6727 
6728       SDValue Store = DAG.getStore(
6729           DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6730           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6731           false, false, 0);
6732 
6733       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6734              "Expected an i32 store");
6735 
6736       RLI.Ptr = FIdx;
6737       RLI.Chain = Store;
6738       RLI.MPI =
6739           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6740       RLI.Alignment = 4;
6741 
6742       MachineMemOperand *MMO =
6743         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6744                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6745       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6746       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6747                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6748                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6749                                      Ops, MVT::i32, MMO);
6750     } else
6751       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6752 
6753     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6754 
6755     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6756       FP = DAG.getNode(ISD::FP_ROUND, dl,
6757                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6758     return FP;
6759   }
6760 
6761   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6762          "Unhandled INT_TO_FP type in custom expander!");
6763   // Since we only generate this in 64-bit mode, we can take advantage of
6764   // 64-bit registers.  In particular, sign extend the input value into the
6765   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6766   // then lfd it and fcfid it.
6767   MachineFunction &MF = DAG.getMachineFunction();
6768   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6769   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6770 
6771   SDValue Ld;
6772   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6773     ReuseLoadInfo RLI;
6774     bool ReusingLoad;
6775     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6776                                             DAG))) {
6777       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6778       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6779 
6780       SDValue Store = DAG.getStore(
6781           DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6782           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6783           false, false, 0);
6784 
6785       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6786              "Expected an i32 store");
6787 
6788       RLI.Ptr = FIdx;
6789       RLI.Chain = Store;
6790       RLI.MPI =
6791           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6792       RLI.Alignment = 4;
6793     }
6794 
6795     MachineMemOperand *MMO =
6796       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6797                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6798     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6799     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6800                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6801                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6802                                  Ops, MVT::i32, MMO);
6803     if (ReusingLoad)
6804       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6805   } else {
6806     assert(Subtarget.isPPC64() &&
6807            "i32->FP without LFIWAX supported only on PPC64");
6808 
6809     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6810     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6811 
6812     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6813                                 Op.getOperand(0));
6814 
6815     // STD the extended value into the stack slot.
6816     SDValue Store = DAG.getStore(
6817         DAG.getEntryNode(), dl, Ext64, FIdx,
6818         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6819         false, false, 0);
6820 
6821     // Load the value as a double.
6822     Ld = DAG.getLoad(
6823         MVT::f64, dl, Store, FIdx,
6824         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6825         false, false, false, 0);
6826   }
6827 
6828   // FCFID it and return it.
6829   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6830   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6831     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6832                      DAG.getIntPtrConstant(0, dl));
6833   return FP;
6834 }
6835 
6836 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6837                                             SelectionDAG &DAG) const {
6838   SDLoc dl(Op);
6839   /*
6840    The rounding mode is in bits 30:31 of FPSR, and has the following
6841    settings:
6842      00 Round to nearest
6843      01 Round to 0
6844      10 Round to +inf
6845      11 Round to -inf
6846 
6847   FLT_ROUNDS, on the other hand, expects the following:
6848     -1 Undefined
6849      0 Round to 0
6850      1 Round to nearest
6851      2 Round to +inf
6852      3 Round to -inf
6853 
6854   To perform the conversion, we do:
6855     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6856   */
6857 
6858   MachineFunction &MF = DAG.getMachineFunction();
6859   EVT VT = Op.getValueType();
6860   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6861 
6862   // Save FP Control Word to register
6863   EVT NodeTys[] = {
6864     MVT::f64,    // return register
6865     MVT::Glue    // unused in this context
6866   };
6867   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6868 
6869   // Save FP register to stack slot
6870   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6871   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6872   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6873                                StackSlot, MachinePointerInfo(), false, false,0);
6874 
6875   // Load FP Control Word from low 32 bits of stack slot.
6876   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6877   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6878   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6879                             false, false, false, 0);
6880 
6881   // Transform as necessary
6882   SDValue CWD1 =
6883     DAG.getNode(ISD::AND, dl, MVT::i32,
6884                 CWD, DAG.getConstant(3, dl, MVT::i32));
6885   SDValue CWD2 =
6886     DAG.getNode(ISD::SRL, dl, MVT::i32,
6887                 DAG.getNode(ISD::AND, dl, MVT::i32,
6888                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6889                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6890                             DAG.getConstant(3, dl, MVT::i32)),
6891                 DAG.getConstant(1, dl, MVT::i32));
6892 
6893   SDValue RetVal =
6894     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6895 
6896   return DAG.getNode((VT.getSizeInBits() < 16 ?
6897                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6898 }
6899 
6900 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6901   EVT VT = Op.getValueType();
6902   unsigned BitWidth = VT.getSizeInBits();
6903   SDLoc dl(Op);
6904   assert(Op.getNumOperands() == 3 &&
6905          VT == Op.getOperand(1).getValueType() &&
6906          "Unexpected SHL!");
6907 
6908   // Expand into a bunch of logical ops.  Note that these ops
6909   // depend on the PPC behavior for oversized shift amounts.
6910   SDValue Lo = Op.getOperand(0);
6911   SDValue Hi = Op.getOperand(1);
6912   SDValue Amt = Op.getOperand(2);
6913   EVT AmtVT = Amt.getValueType();
6914 
6915   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6916                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6917   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6918   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6919   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6920   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6921                              DAG.getConstant(-BitWidth, dl, AmtVT));
6922   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6923   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6924   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6925   SDValue OutOps[] = { OutLo, OutHi };
6926   return DAG.getMergeValues(OutOps, dl);
6927 }
6928 
6929 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6930   EVT VT = Op.getValueType();
6931   SDLoc dl(Op);
6932   unsigned BitWidth = VT.getSizeInBits();
6933   assert(Op.getNumOperands() == 3 &&
6934          VT == Op.getOperand(1).getValueType() &&
6935          "Unexpected SRL!");
6936 
6937   // Expand into a bunch of logical ops.  Note that these ops
6938   // depend on the PPC behavior for oversized shift amounts.
6939   SDValue Lo = Op.getOperand(0);
6940   SDValue Hi = Op.getOperand(1);
6941   SDValue Amt = Op.getOperand(2);
6942   EVT AmtVT = Amt.getValueType();
6943 
6944   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6945                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6946   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6947   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6948   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6949   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6950                              DAG.getConstant(-BitWidth, dl, AmtVT));
6951   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6952   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6953   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6954   SDValue OutOps[] = { OutLo, OutHi };
6955   return DAG.getMergeValues(OutOps, dl);
6956 }
6957 
6958 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6959   SDLoc dl(Op);
6960   EVT VT = Op.getValueType();
6961   unsigned BitWidth = VT.getSizeInBits();
6962   assert(Op.getNumOperands() == 3 &&
6963          VT == Op.getOperand(1).getValueType() &&
6964          "Unexpected SRA!");
6965 
6966   // Expand into a bunch of logical ops, followed by a select_cc.
6967   SDValue Lo = Op.getOperand(0);
6968   SDValue Hi = Op.getOperand(1);
6969   SDValue Amt = Op.getOperand(2);
6970   EVT AmtVT = Amt.getValueType();
6971 
6972   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6973                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6974   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6975   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6976   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6977   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6978                              DAG.getConstant(-BitWidth, dl, AmtVT));
6979   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6980   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6981   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6982                                   Tmp4, Tmp6, ISD::SETLE);
6983   SDValue OutOps[] = { OutLo, OutHi };
6984   return DAG.getMergeValues(OutOps, dl);
6985 }
6986 
6987 //===----------------------------------------------------------------------===//
6988 // Vector related lowering.
6989 //
6990 
6991 /// BuildSplatI - Build a canonical splati of Val with an element size of
6992 /// SplatSize.  Cast the result to VT.
6993 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6994                              SelectionDAG &DAG, SDLoc dl) {
6995   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6996 
6997   static const MVT VTys[] = { // canonical VT to use for each size.
6998     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6999   };
7000 
7001   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7002 
7003   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7004   if (Val == -1)
7005     SplatSize = 1;
7006 
7007   EVT CanonicalVT = VTys[SplatSize-1];
7008 
7009   // Build a canonical splat for this value.
7010   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7011 }
7012 
7013 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7014 /// specified intrinsic ID.
7015 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
7016                                 SelectionDAG &DAG, SDLoc dl,
7017                                 EVT DestVT = MVT::Other) {
7018   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7019   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7020                      DAG.getConstant(IID, dl, MVT::i32), Op);
7021 }
7022 
7023 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7024 /// specified intrinsic ID.
7025 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7026                                 SelectionDAG &DAG, SDLoc dl,
7027                                 EVT DestVT = MVT::Other) {
7028   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7029   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7030                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7031 }
7032 
7033 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7034 /// specified intrinsic ID.
7035 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7036                                 SDValue Op2, SelectionDAG &DAG,
7037                                 SDLoc dl, EVT DestVT = MVT::Other) {
7038   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7039   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7040                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7041 }
7042 
7043 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7044 /// amount.  The result has the specified value type.
7045 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
7046                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
7047   // Force LHS/RHS to be the right type.
7048   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7049   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7050 
7051   int Ops[16];
7052   for (unsigned i = 0; i != 16; ++i)
7053     Ops[i] = i + Amt;
7054   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7055   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7056 }
7057 
7058 // If this is a case we can't handle, return null and let the default
7059 // expansion code take care of it.  If we CAN select this case, and if it
7060 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7061 // this case more efficiently than a constant pool load, lower it to the
7062 // sequence of ops that should be used.
7063 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7064                                              SelectionDAG &DAG) const {
7065   SDLoc dl(Op);
7066   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7067   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7068 
7069   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7070     // We first build an i32 vector, load it into a QPX register,
7071     // then convert it to a floating-point vector and compare it
7072     // to a zero vector to get the boolean result.
7073     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7074     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7075     MachinePointerInfo PtrInfo =
7076         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7077     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7078     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7079 
7080     assert(BVN->getNumOperands() == 4 &&
7081       "BUILD_VECTOR for v4i1 does not have 4 operands");
7082 
7083     bool IsConst = true;
7084     for (unsigned i = 0; i < 4; ++i) {
7085       if (BVN->getOperand(i).isUndef()) continue;
7086       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7087         IsConst = false;
7088         break;
7089       }
7090     }
7091 
7092     if (IsConst) {
7093       Constant *One =
7094         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7095       Constant *NegOne =
7096         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7097 
7098       SmallVector<Constant*, 4> CV(4, NegOne);
7099       for (unsigned i = 0; i < 4; ++i) {
7100         if (BVN->getOperand(i).isUndef())
7101           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7102         else if (isNullConstant(BVN->getOperand(i)))
7103           continue;
7104         else
7105           CV[i] = One;
7106       }
7107 
7108       Constant *CP = ConstantVector::get(CV);
7109       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7110                                           16 /* alignment */);
7111 
7112       SmallVector<SDValue, 2> Ops;
7113       Ops.push_back(DAG.getEntryNode());
7114       Ops.push_back(CPIdx);
7115 
7116       SmallVector<EVT, 2> ValueVTs;
7117       ValueVTs.push_back(MVT::v4i1);
7118       ValueVTs.push_back(MVT::Other); // chain
7119       SDVTList VTs = DAG.getVTList(ValueVTs);
7120 
7121       return DAG.getMemIntrinsicNode(
7122           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7123           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7124     }
7125 
7126     SmallVector<SDValue, 4> Stores;
7127     for (unsigned i = 0; i < 4; ++i) {
7128       if (BVN->getOperand(i).isUndef()) continue;
7129 
7130       unsigned Offset = 4*i;
7131       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7132       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7133 
7134       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7135       if (StoreSize > 4) {
7136         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
7137                                            BVN->getOperand(i), Idx,
7138                                            PtrInfo.getWithOffset(Offset),
7139                                            MVT::i32, false, false, 0));
7140       } else {
7141         SDValue StoreValue = BVN->getOperand(i);
7142         if (StoreSize < 4)
7143           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7144 
7145         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
7146                                       StoreValue, Idx,
7147                                       PtrInfo.getWithOffset(Offset),
7148                                       false, false, 0));
7149       }
7150     }
7151 
7152     SDValue StoreChain;
7153     if (!Stores.empty())
7154       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7155     else
7156       StoreChain = DAG.getEntryNode();
7157 
7158     // Now load from v4i32 into the QPX register; this will extend it to
7159     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7160     // is typed as v4f64 because the QPX register integer states are not
7161     // explicitly represented.
7162 
7163     SmallVector<SDValue, 2> Ops;
7164     Ops.push_back(StoreChain);
7165     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
7166     Ops.push_back(FIdx);
7167 
7168     SmallVector<EVT, 2> ValueVTs;
7169     ValueVTs.push_back(MVT::v4f64);
7170     ValueVTs.push_back(MVT::Other); // chain
7171     SDVTList VTs = DAG.getVTList(ValueVTs);
7172 
7173     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7174       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7175     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7176       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7177       LoadedVect);
7178 
7179     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7180 
7181     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7182   }
7183 
7184   // All other QPX vectors are handled by generic code.
7185   if (Subtarget.hasQPX())
7186     return SDValue();
7187 
7188   // Check if this is a splat of a constant value.
7189   APInt APSplatBits, APSplatUndef;
7190   unsigned SplatBitSize;
7191   bool HasAnyUndefs;
7192   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7193                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7194       SplatBitSize > 32)
7195     return SDValue();
7196 
7197   unsigned SplatBits = APSplatBits.getZExtValue();
7198   unsigned SplatUndef = APSplatUndef.getZExtValue();
7199   unsigned SplatSize = SplatBitSize / 8;
7200 
7201   // First, handle single instruction cases.
7202 
7203   // All zeros?
7204   if (SplatBits == 0) {
7205     // Canonicalize all zero vectors to be v4i32.
7206     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7207       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7208       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7209     }
7210     return Op;
7211   }
7212 
7213   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7214   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7215                     (32-SplatBitSize));
7216   if (SextVal >= -16 && SextVal <= 15)
7217     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7218 
7219   // Two instruction sequences.
7220 
7221   // If this value is in the range [-32,30] and is even, use:
7222   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7223   // If this value is in the range [17,31] and is odd, use:
7224   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7225   // If this value is in the range [-31,-17] and is odd, use:
7226   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7227   // Note the last two are three-instruction sequences.
7228   if (SextVal >= -32 && SextVal <= 31) {
7229     // To avoid having these optimizations undone by constant folding,
7230     // we convert to a pseudo that will be expanded later into one of
7231     // the above forms.
7232     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7233     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7234               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7235     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7236     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7237     if (VT == Op.getValueType())
7238       return RetVal;
7239     else
7240       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7241   }
7242 
7243   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7244   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7245   // for fneg/fabs.
7246   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7247     // Make -1 and vspltisw -1:
7248     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7249 
7250     // Make the VSLW intrinsic, computing 0x8000_0000.
7251     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7252                                    OnesV, DAG, dl);
7253 
7254     // xor by OnesV to invert it.
7255     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7256     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7257   }
7258 
7259   // Check to see if this is a wide variety of vsplti*, binop self cases.
7260   static const signed char SplatCsts[] = {
7261     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7262     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7263   };
7264 
7265   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7266     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7267     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7268     int i = SplatCsts[idx];
7269 
7270     // Figure out what shift amount will be used by altivec if shifted by i in
7271     // this splat size.
7272     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7273 
7274     // vsplti + shl self.
7275     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7276       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7277       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7278         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7279         Intrinsic::ppc_altivec_vslw
7280       };
7281       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7282       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7283     }
7284 
7285     // vsplti + srl self.
7286     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7287       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7288       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7289         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7290         Intrinsic::ppc_altivec_vsrw
7291       };
7292       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7293       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7294     }
7295 
7296     // vsplti + sra self.
7297     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7298       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7299       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7300         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7301         Intrinsic::ppc_altivec_vsraw
7302       };
7303       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7304       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7305     }
7306 
7307     // vsplti + rol self.
7308     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7309                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7310       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7311       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7312         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7313         Intrinsic::ppc_altivec_vrlw
7314       };
7315       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7316       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7317     }
7318 
7319     // t = vsplti c, result = vsldoi t, t, 1
7320     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7321       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7322       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7323       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7324     }
7325     // t = vsplti c, result = vsldoi t, t, 2
7326     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7327       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7328       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7329       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7330     }
7331     // t = vsplti c, result = vsldoi t, t, 3
7332     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7333       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7334       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7335       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7336     }
7337   }
7338 
7339   return SDValue();
7340 }
7341 
7342 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7343 /// the specified operations to build the shuffle.
7344 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7345                                       SDValue RHS, SelectionDAG &DAG,
7346                                       SDLoc dl) {
7347   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7348   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7349   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7350 
7351   enum {
7352     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7353     OP_VMRGHW,
7354     OP_VMRGLW,
7355     OP_VSPLTISW0,
7356     OP_VSPLTISW1,
7357     OP_VSPLTISW2,
7358     OP_VSPLTISW3,
7359     OP_VSLDOI4,
7360     OP_VSLDOI8,
7361     OP_VSLDOI12
7362   };
7363 
7364   if (OpNum == OP_COPY) {
7365     if (LHSID == (1*9+2)*9+3) return LHS;
7366     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7367     return RHS;
7368   }
7369 
7370   SDValue OpLHS, OpRHS;
7371   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7372   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7373 
7374   int ShufIdxs[16];
7375   switch (OpNum) {
7376   default: llvm_unreachable("Unknown i32 permute!");
7377   case OP_VMRGHW:
7378     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7379     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7380     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7381     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7382     break;
7383   case OP_VMRGLW:
7384     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7385     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7386     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7387     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7388     break;
7389   case OP_VSPLTISW0:
7390     for (unsigned i = 0; i != 16; ++i)
7391       ShufIdxs[i] = (i&3)+0;
7392     break;
7393   case OP_VSPLTISW1:
7394     for (unsigned i = 0; i != 16; ++i)
7395       ShufIdxs[i] = (i&3)+4;
7396     break;
7397   case OP_VSPLTISW2:
7398     for (unsigned i = 0; i != 16; ++i)
7399       ShufIdxs[i] = (i&3)+8;
7400     break;
7401   case OP_VSPLTISW3:
7402     for (unsigned i = 0; i != 16; ++i)
7403       ShufIdxs[i] = (i&3)+12;
7404     break;
7405   case OP_VSLDOI4:
7406     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7407   case OP_VSLDOI8:
7408     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7409   case OP_VSLDOI12:
7410     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7411   }
7412   EVT VT = OpLHS.getValueType();
7413   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7414   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7415   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7416   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7417 }
7418 
7419 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7420 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7421 /// return the code it can be lowered into.  Worst case, it can always be
7422 /// lowered into a vperm.
7423 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7424                                                SelectionDAG &DAG) const {
7425   SDLoc dl(Op);
7426   SDValue V1 = Op.getOperand(0);
7427   SDValue V2 = Op.getOperand(1);
7428   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7429   EVT VT = Op.getValueType();
7430   bool isLittleEndian = Subtarget.isLittleEndian();
7431 
7432   if (Subtarget.hasVSX()) {
7433     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7434       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7435       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7436       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7437                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7438       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7439     }
7440   }
7441 
7442   if (Subtarget.hasQPX()) {
7443     if (VT.getVectorNumElements() != 4)
7444       return SDValue();
7445 
7446     if (V2.isUndef()) V2 = V1;
7447 
7448     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7449     if (AlignIdx != -1) {
7450       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7451                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7452     } else if (SVOp->isSplat()) {
7453       int SplatIdx = SVOp->getSplatIndex();
7454       if (SplatIdx >= 4) {
7455         std::swap(V1, V2);
7456         SplatIdx -= 4;
7457       }
7458 
7459       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7460                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7461     }
7462 
7463     // Lower this into a qvgpci/qvfperm pair.
7464 
7465     // Compute the qvgpci literal
7466     unsigned idx = 0;
7467     for (unsigned i = 0; i < 4; ++i) {
7468       int m = SVOp->getMaskElt(i);
7469       unsigned mm = m >= 0 ? (unsigned) m : i;
7470       idx |= mm << (3-i)*3;
7471     }
7472 
7473     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7474                              DAG.getConstant(idx, dl, MVT::i32));
7475     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7476   }
7477 
7478   // Cases that are handled by instructions that take permute immediates
7479   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7480   // selected by the instruction selector.
7481   if (V2.isUndef()) {
7482     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7483         PPC::isSplatShuffleMask(SVOp, 2) ||
7484         PPC::isSplatShuffleMask(SVOp, 4) ||
7485         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7486         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7487         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7488         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7489         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7490         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7491         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7492         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7493         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7494         (Subtarget.hasP8Altivec() && (
7495          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7496          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7497          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7498       return Op;
7499     }
7500   }
7501 
7502   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7503   // and produce a fixed permutation.  If any of these match, do not lower to
7504   // VPERM.
7505   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7506   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7507       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7508       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7509       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7510       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7511       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7512       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7513       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7514       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7515       (Subtarget.hasP8Altivec() && (
7516        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7517        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7518        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7519     return Op;
7520 
7521   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7522   // perfect shuffle table to emit an optimal matching sequence.
7523   ArrayRef<int> PermMask = SVOp->getMask();
7524 
7525   unsigned PFIndexes[4];
7526   bool isFourElementShuffle = true;
7527   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7528     unsigned EltNo = 8;   // Start out undef.
7529     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7530       if (PermMask[i*4+j] < 0)
7531         continue;   // Undef, ignore it.
7532 
7533       unsigned ByteSource = PermMask[i*4+j];
7534       if ((ByteSource & 3) != j) {
7535         isFourElementShuffle = false;
7536         break;
7537       }
7538 
7539       if (EltNo == 8) {
7540         EltNo = ByteSource/4;
7541       } else if (EltNo != ByteSource/4) {
7542         isFourElementShuffle = false;
7543         break;
7544       }
7545     }
7546     PFIndexes[i] = EltNo;
7547   }
7548 
7549   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7550   // perfect shuffle vector to determine if it is cost effective to do this as
7551   // discrete instructions, or whether we should use a vperm.
7552   // For now, we skip this for little endian until such time as we have a
7553   // little-endian perfect shuffle table.
7554   if (isFourElementShuffle && !isLittleEndian) {
7555     // Compute the index in the perfect shuffle table.
7556     unsigned PFTableIndex =
7557       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7558 
7559     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7560     unsigned Cost  = (PFEntry >> 30);
7561 
7562     // Determining when to avoid vperm is tricky.  Many things affect the cost
7563     // of vperm, particularly how many times the perm mask needs to be computed.
7564     // For example, if the perm mask can be hoisted out of a loop or is already
7565     // used (perhaps because there are multiple permutes with the same shuffle
7566     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7567     // the loop requires an extra register.
7568     //
7569     // As a compromise, we only emit discrete instructions if the shuffle can be
7570     // generated in 3 or fewer operations.  When we have loop information
7571     // available, if this block is within a loop, we should avoid using vperm
7572     // for 3-operation perms and use a constant pool load instead.
7573     if (Cost < 3)
7574       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7575   }
7576 
7577   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7578   // vector that will get spilled to the constant pool.
7579   if (V2.isUndef()) V2 = V1;
7580 
7581   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7582   // that it is in input element units, not in bytes.  Convert now.
7583 
7584   // For little endian, the order of the input vectors is reversed, and
7585   // the permutation mask is complemented with respect to 31.  This is
7586   // necessary to produce proper semantics with the big-endian-biased vperm
7587   // instruction.
7588   EVT EltVT = V1.getValueType().getVectorElementType();
7589   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7590 
7591   SmallVector<SDValue, 16> ResultMask;
7592   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7593     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7594 
7595     for (unsigned j = 0; j != BytesPerElement; ++j)
7596       if (isLittleEndian)
7597         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7598                                              dl, MVT::i32));
7599       else
7600         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7601                                              MVT::i32));
7602   }
7603 
7604   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7605   if (isLittleEndian)
7606     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7607                        V2, V1, VPermMask);
7608   else
7609     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7610                        V1, V2, VPermMask);
7611 }
7612 
7613 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7614 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7615 /// information about the intrinsic.
7616 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7617                                  bool &isDot, const PPCSubtarget &Subtarget) {
7618   unsigned IntrinsicID =
7619     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7620   CompareOpc = -1;
7621   isDot = false;
7622   switch (IntrinsicID) {
7623   default: return false;
7624     // Comparison predicates.
7625   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7626   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7627   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7628   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7629   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7630   case Intrinsic::ppc_altivec_vcmpequd_p:
7631     if (Subtarget.hasP8Altivec()) {
7632       CompareOpc = 199;
7633       isDot = 1;
7634     } else
7635       return false;
7636 
7637     break;
7638   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7639   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7640   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7641   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7642   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7643   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7644     if (Subtarget.hasP8Altivec()) {
7645       CompareOpc = 967;
7646       isDot = 1;
7647     } else
7648       return false;
7649 
7650     break;
7651   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7652   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7653   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7654   case Intrinsic::ppc_altivec_vcmpgtud_p:
7655     if (Subtarget.hasP8Altivec()) {
7656       CompareOpc = 711;
7657       isDot = 1;
7658     } else
7659       return false;
7660 
7661     break;
7662     // VSX predicate comparisons use the same infrastructure
7663   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7664   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7665   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7666   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7667   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7668   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7669     if (Subtarget.hasVSX()) {
7670       switch (IntrinsicID) {
7671       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7672       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7673       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7674       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7675       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7676       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7677       }
7678       isDot = 1;
7679     }
7680     else
7681       return false;
7682 
7683     break;
7684 
7685     // Normal Comparisons.
7686   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7687   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7688   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7689   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7690   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7691   case Intrinsic::ppc_altivec_vcmpequd:
7692     if (Subtarget.hasP8Altivec()) {
7693       CompareOpc = 199;
7694       isDot = 0;
7695     } else
7696       return false;
7697 
7698     break;
7699   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7700   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7701   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7702   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7703   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7704   case Intrinsic::ppc_altivec_vcmpgtsd:
7705     if (Subtarget.hasP8Altivec()) {
7706       CompareOpc = 967;
7707       isDot = 0;
7708     } else
7709       return false;
7710 
7711     break;
7712   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7713   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7714   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7715   case Intrinsic::ppc_altivec_vcmpgtud:
7716     if (Subtarget.hasP8Altivec()) {
7717       CompareOpc = 711;
7718       isDot = 0;
7719     } else
7720       return false;
7721 
7722     break;
7723   }
7724   return true;
7725 }
7726 
7727 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7728 /// lower, do it, otherwise return null.
7729 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7730                                                    SelectionDAG &DAG) const {
7731   unsigned IntrinsicID =
7732     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7733 
7734   if (IntrinsicID == Intrinsic::thread_pointer) {
7735     // Reads the thread pointer register, used for __builtin_thread_pointer.
7736     bool is64bit = Subtarget.isPPC64();
7737     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7738                            is64bit ? MVT::i64 : MVT::i32);
7739   }
7740 
7741   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7742   // opcode number of the comparison.
7743   SDLoc dl(Op);
7744   int CompareOpc;
7745   bool isDot;
7746   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7747     return SDValue();    // Don't custom lower most intrinsics.
7748 
7749   // If this is a non-dot comparison, make the VCMP node and we are done.
7750   if (!isDot) {
7751     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7752                               Op.getOperand(1), Op.getOperand(2),
7753                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7754     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7755   }
7756 
7757   // Create the PPCISD altivec 'dot' comparison node.
7758   SDValue Ops[] = {
7759     Op.getOperand(2),  // LHS
7760     Op.getOperand(3),  // RHS
7761     DAG.getConstant(CompareOpc, dl, MVT::i32)
7762   };
7763   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7764   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7765 
7766   // Now that we have the comparison, emit a copy from the CR to a GPR.
7767   // This is flagged to the above dot comparison.
7768   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7769                                 DAG.getRegister(PPC::CR6, MVT::i32),
7770                                 CompNode.getValue(1));
7771 
7772   // Unpack the result based on how the target uses it.
7773   unsigned BitNo;   // Bit # of CR6.
7774   bool InvertBit;   // Invert result?
7775   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7776   default:  // Can't happen, don't crash on invalid number though.
7777   case 0:   // Return the value of the EQ bit of CR6.
7778     BitNo = 0; InvertBit = false;
7779     break;
7780   case 1:   // Return the inverted value of the EQ bit of CR6.
7781     BitNo = 0; InvertBit = true;
7782     break;
7783   case 2:   // Return the value of the LT bit of CR6.
7784     BitNo = 2; InvertBit = false;
7785     break;
7786   case 3:   // Return the inverted value of the LT bit of CR6.
7787     BitNo = 2; InvertBit = true;
7788     break;
7789   }
7790 
7791   // Shift the bit into the low position.
7792   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7793                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7794   // Isolate the bit.
7795   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7796                       DAG.getConstant(1, dl, MVT::i32));
7797 
7798   // If we are supposed to, toggle the bit.
7799   if (InvertBit)
7800     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7801                         DAG.getConstant(1, dl, MVT::i32));
7802   return Flags;
7803 }
7804 
7805 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7806                                                   SelectionDAG &DAG) const {
7807   SDLoc dl(Op);
7808   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7809   // instructions), but for smaller types, we need to first extend up to v2i32
7810   // before doing going farther.
7811   if (Op.getValueType() == MVT::v2i64) {
7812     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7813     if (ExtVT != MVT::v2i32) {
7814       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7815       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7816                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7817                                         ExtVT.getVectorElementType(), 4)));
7818       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7819       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7820                        DAG.getValueType(MVT::v2i32));
7821     }
7822 
7823     return Op;
7824   }
7825 
7826   return SDValue();
7827 }
7828 
7829 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7830                                                    SelectionDAG &DAG) const {
7831   SDLoc dl(Op);
7832   // Create a stack slot that is 16-byte aligned.
7833   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7834   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7835   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7836   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7837 
7838   // Store the input value into Value#0 of the stack slot.
7839   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7840                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7841                                false, false, 0);
7842   // Load it out.
7843   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7844                      false, false, false, 0);
7845 }
7846 
7847 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7848                                                    SelectionDAG &DAG) const {
7849   SDLoc dl(Op);
7850   SDNode *N = Op.getNode();
7851 
7852   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7853          "Unknown extract_vector_elt type");
7854 
7855   SDValue Value = N->getOperand(0);
7856 
7857   // The first part of this is like the store lowering except that we don't
7858   // need to track the chain.
7859 
7860   // The values are now known to be -1 (false) or 1 (true). To convert this
7861   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7862   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7863   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7864 
7865   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7866   // understand how to form the extending load.
7867   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7868 
7869   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7870 
7871   // Now convert to an integer and store.
7872   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7873     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7874     Value);
7875 
7876   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7877   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7878   MachinePointerInfo PtrInfo =
7879       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7880   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7881   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7882 
7883   SDValue StoreChain = DAG.getEntryNode();
7884   SmallVector<SDValue, 2> Ops;
7885   Ops.push_back(StoreChain);
7886   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7887   Ops.push_back(Value);
7888   Ops.push_back(FIdx);
7889 
7890   SmallVector<EVT, 2> ValueVTs;
7891   ValueVTs.push_back(MVT::Other); // chain
7892   SDVTList VTs = DAG.getVTList(ValueVTs);
7893 
7894   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7895     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7896 
7897   // Extract the value requested.
7898   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7899   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7900   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7901 
7902   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7903                                PtrInfo.getWithOffset(Offset),
7904                                false, false, false, 0);
7905 
7906   if (!Subtarget.useCRBits())
7907     return IntVal;
7908 
7909   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7910 }
7911 
7912 /// Lowering for QPX v4i1 loads
7913 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7914                                            SelectionDAG &DAG) const {
7915   SDLoc dl(Op);
7916   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7917   SDValue LoadChain = LN->getChain();
7918   SDValue BasePtr = LN->getBasePtr();
7919 
7920   if (Op.getValueType() == MVT::v4f64 ||
7921       Op.getValueType() == MVT::v4f32) {
7922     EVT MemVT = LN->getMemoryVT();
7923     unsigned Alignment = LN->getAlignment();
7924 
7925     // If this load is properly aligned, then it is legal.
7926     if (Alignment >= MemVT.getStoreSize())
7927       return Op;
7928 
7929     EVT ScalarVT = Op.getValueType().getScalarType(),
7930         ScalarMemVT = MemVT.getScalarType();
7931     unsigned Stride = ScalarMemVT.getStoreSize();
7932 
7933     SmallVector<SDValue, 8> Vals, LoadChains;
7934     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7935       SDValue Load;
7936       if (ScalarVT != ScalarMemVT)
7937         Load =
7938           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7939                          BasePtr,
7940                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7941                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7942                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7943                          LN->getAAInfo());
7944       else
7945         Load =
7946           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7947                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7948                        LN->isVolatile(), LN->isNonTemporal(),
7949                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7950                        LN->getAAInfo());
7951 
7952       if (Idx == 0 && LN->isIndexed()) {
7953         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7954                "Unknown addressing mode on vector load");
7955         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7956                                   LN->getAddressingMode());
7957       }
7958 
7959       Vals.push_back(Load);
7960       LoadChains.push_back(Load.getValue(1));
7961 
7962       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7963                             DAG.getConstant(Stride, dl,
7964                                             BasePtr.getValueType()));
7965     }
7966 
7967     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7968     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7969 
7970     if (LN->isIndexed()) {
7971       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7972       return DAG.getMergeValues(RetOps, dl);
7973     }
7974 
7975     SDValue RetOps[] = { Value, TF };
7976     return DAG.getMergeValues(RetOps, dl);
7977   }
7978 
7979   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7980   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7981 
7982   // To lower v4i1 from a byte array, we load the byte elements of the
7983   // vector and then reuse the BUILD_VECTOR logic.
7984 
7985   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7986   for (unsigned i = 0; i < 4; ++i) {
7987     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7988     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7989 
7990     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7991                         dl, MVT::i32, LoadChain, Idx,
7992                         LN->getPointerInfo().getWithOffset(i),
7993                         MVT::i8 /* memory type */,
7994                         LN->isVolatile(), LN->isNonTemporal(),
7995                         LN->isInvariant(),
7996                         1 /* alignment */, LN->getAAInfo()));
7997     VectElmtChains.push_back(VectElmts[i].getValue(1));
7998   }
7999 
8000   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8001   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8002 
8003   SDValue RVals[] = { Value, LoadChain };
8004   return DAG.getMergeValues(RVals, dl);
8005 }
8006 
8007 /// Lowering for QPX v4i1 stores
8008 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8009                                             SelectionDAG &DAG) const {
8010   SDLoc dl(Op);
8011   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8012   SDValue StoreChain = SN->getChain();
8013   SDValue BasePtr = SN->getBasePtr();
8014   SDValue Value = SN->getValue();
8015 
8016   if (Value.getValueType() == MVT::v4f64 ||
8017       Value.getValueType() == MVT::v4f32) {
8018     EVT MemVT = SN->getMemoryVT();
8019     unsigned Alignment = SN->getAlignment();
8020 
8021     // If this store is properly aligned, then it is legal.
8022     if (Alignment >= MemVT.getStoreSize())
8023       return Op;
8024 
8025     EVT ScalarVT = Value.getValueType().getScalarType(),
8026         ScalarMemVT = MemVT.getScalarType();
8027     unsigned Stride = ScalarMemVT.getStoreSize();
8028 
8029     SmallVector<SDValue, 8> Stores;
8030     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8031       SDValue Ex = DAG.getNode(
8032           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8033           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8034       SDValue Store;
8035       if (ScalarVT != ScalarMemVT)
8036         Store =
8037           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8038                             SN->getPointerInfo().getWithOffset(Idx*Stride),
8039                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
8040                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
8041       else
8042         Store =
8043           DAG.getStore(StoreChain, dl, Ex, BasePtr,
8044                        SN->getPointerInfo().getWithOffset(Idx*Stride),
8045                        SN->isVolatile(), SN->isNonTemporal(),
8046                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
8047 
8048       if (Idx == 0 && SN->isIndexed()) {
8049         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8050                "Unknown addressing mode on vector store");
8051         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8052                                     SN->getAddressingMode());
8053       }
8054 
8055       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8056                             DAG.getConstant(Stride, dl,
8057                                             BasePtr.getValueType()));
8058       Stores.push_back(Store);
8059     }
8060 
8061     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8062 
8063     if (SN->isIndexed()) {
8064       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8065       return DAG.getMergeValues(RetOps, dl);
8066     }
8067 
8068     return TF;
8069   }
8070 
8071   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8072   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8073 
8074   // The values are now known to be -1 (false) or 1 (true). To convert this
8075   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8076   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8077   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8078 
8079   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8080   // understand how to form the extending load.
8081   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8082 
8083   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8084 
8085   // Now convert to an integer and store.
8086   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8087     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8088     Value);
8089 
8090   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
8091   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
8092   MachinePointerInfo PtrInfo =
8093       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8094   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8095   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8096 
8097   SmallVector<SDValue, 2> Ops;
8098   Ops.push_back(StoreChain);
8099   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
8100   Ops.push_back(Value);
8101   Ops.push_back(FIdx);
8102 
8103   SmallVector<EVT, 2> ValueVTs;
8104   ValueVTs.push_back(MVT::Other); // chain
8105   SDVTList VTs = DAG.getVTList(ValueVTs);
8106 
8107   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8108     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8109 
8110   // Move data into the byte array.
8111   SmallVector<SDValue, 4> Loads, LoadChains;
8112   for (unsigned i = 0; i < 4; ++i) {
8113     unsigned Offset = 4*i;
8114     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8115     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8116 
8117     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8118                                    PtrInfo.getWithOffset(Offset),
8119                                    false, false, false, 0));
8120     LoadChains.push_back(Loads[i].getValue(1));
8121   }
8122 
8123   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8124 
8125   SmallVector<SDValue, 4> Stores;
8126   for (unsigned i = 0; i < 4; ++i) {
8127     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8128     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8129 
8130     Stores.push_back(DAG.getTruncStore(
8131         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8132         MVT::i8 /* memory type */, SN->isNonTemporal(), SN->isVolatile(),
8133         1 /* alignment */, SN->getAAInfo()));
8134   }
8135 
8136   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8137 
8138   return StoreChain;
8139 }
8140 
8141 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8142   SDLoc dl(Op);
8143   if (Op.getValueType() == MVT::v4i32) {
8144     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8145 
8146     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8147     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8148 
8149     SDValue RHSSwap =   // = vrlw RHS, 16
8150       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8151 
8152     // Shrinkify inputs to v8i16.
8153     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8154     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8155     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8156 
8157     // Low parts multiplied together, generating 32-bit results (we ignore the
8158     // top parts).
8159     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8160                                         LHS, RHS, DAG, dl, MVT::v4i32);
8161 
8162     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8163                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8164     // Shift the high parts up 16 bits.
8165     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8166                               Neg16, DAG, dl);
8167     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8168   } else if (Op.getValueType() == MVT::v8i16) {
8169     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8170 
8171     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8172 
8173     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8174                             LHS, RHS, Zero, DAG, dl);
8175   } else if (Op.getValueType() == MVT::v16i8) {
8176     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8177     bool isLittleEndian = Subtarget.isLittleEndian();
8178 
8179     // Multiply the even 8-bit parts, producing 16-bit sums.
8180     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8181                                            LHS, RHS, DAG, dl, MVT::v8i16);
8182     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8183 
8184     // Multiply the odd 8-bit parts, producing 16-bit sums.
8185     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8186                                           LHS, RHS, DAG, dl, MVT::v8i16);
8187     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8188 
8189     // Merge the results together.  Because vmuleub and vmuloub are
8190     // instructions with a big-endian bias, we must reverse the
8191     // element numbering and reverse the meaning of "odd" and "even"
8192     // when generating little endian code.
8193     int Ops[16];
8194     for (unsigned i = 0; i != 8; ++i) {
8195       if (isLittleEndian) {
8196         Ops[i*2  ] = 2*i;
8197         Ops[i*2+1] = 2*i+16;
8198       } else {
8199         Ops[i*2  ] = 2*i+1;
8200         Ops[i*2+1] = 2*i+1+16;
8201       }
8202     }
8203     if (isLittleEndian)
8204       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8205     else
8206       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8207   } else {
8208     llvm_unreachable("Unknown mul to lower!");
8209   }
8210 }
8211 
8212 /// LowerOperation - Provide custom lowering hooks for some operations.
8213 ///
8214 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8215   switch (Op.getOpcode()) {
8216   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8217   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8218   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8219   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8220   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8221   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8222   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8223   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8224   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8225   case ISD::VASTART:
8226     return LowerVASTART(Op, DAG, Subtarget);
8227 
8228   case ISD::VAARG:
8229     return LowerVAARG(Op, DAG, Subtarget);
8230 
8231   case ISD::VACOPY:
8232     return LowerVACOPY(Op, DAG, Subtarget);
8233 
8234   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
8235   case ISD::DYNAMIC_STACKALLOC:
8236     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
8237   case ISD::GET_DYNAMIC_AREA_OFFSET: return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG, Subtarget);
8238 
8239   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8240   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8241 
8242   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8243   case ISD::STORE:              return LowerSTORE(Op, DAG);
8244   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8245   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8246   case ISD::FP_TO_UINT:
8247   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8248                                                       SDLoc(Op));
8249   case ISD::UINT_TO_FP:
8250   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8251   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8252 
8253   // Lower 64-bit shifts.
8254   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8255   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8256   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8257 
8258   // Vector-related lowering.
8259   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8260   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8261   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8262   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8263   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8264   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8265   case ISD::MUL:                return LowerMUL(Op, DAG);
8266 
8267   // For counter-based loop handling.
8268   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8269 
8270   // Frame & Return address.
8271   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8272   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8273   }
8274 }
8275 
8276 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8277                                            SmallVectorImpl<SDValue>&Results,
8278                                            SelectionDAG &DAG) const {
8279   SDLoc dl(N);
8280   switch (N->getOpcode()) {
8281   default:
8282     llvm_unreachable("Do not know how to custom type legalize this operation!");
8283   case ISD::READCYCLECOUNTER: {
8284     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8285     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8286 
8287     Results.push_back(RTB);
8288     Results.push_back(RTB.getValue(1));
8289     Results.push_back(RTB.getValue(2));
8290     break;
8291   }
8292   case ISD::INTRINSIC_W_CHAIN: {
8293     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8294         Intrinsic::ppc_is_decremented_ctr_nonzero)
8295       break;
8296 
8297     assert(N->getValueType(0) == MVT::i1 &&
8298            "Unexpected result type for CTR decrement intrinsic");
8299     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8300                                  N->getValueType(0));
8301     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8302     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8303                                  N->getOperand(1));
8304 
8305     Results.push_back(NewInt);
8306     Results.push_back(NewInt.getValue(1));
8307     break;
8308   }
8309   case ISD::VAARG: {
8310     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8311       return;
8312 
8313     EVT VT = N->getValueType(0);
8314 
8315     if (VT == MVT::i64) {
8316       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
8317 
8318       Results.push_back(NewNode);
8319       Results.push_back(NewNode.getValue(1));
8320     }
8321     return;
8322   }
8323   case ISD::FP_ROUND_INREG: {
8324     assert(N->getValueType(0) == MVT::ppcf128);
8325     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8326     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8327                              MVT::f64, N->getOperand(0),
8328                              DAG.getIntPtrConstant(0, dl));
8329     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8330                              MVT::f64, N->getOperand(0),
8331                              DAG.getIntPtrConstant(1, dl));
8332 
8333     // Add the two halves of the long double in round-to-zero mode.
8334     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8335 
8336     // We know the low half is about to be thrown away, so just use something
8337     // convenient.
8338     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8339                                 FPreg, FPreg));
8340     return;
8341   }
8342   case ISD::FP_TO_SINT:
8343   case ISD::FP_TO_UINT:
8344     // LowerFP_TO_INT() can only handle f32 and f64.
8345     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8346       return;
8347     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8348     return;
8349   }
8350 }
8351 
8352 //===----------------------------------------------------------------------===//
8353 //  Other Lowering Code
8354 //===----------------------------------------------------------------------===//
8355 
8356 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8357   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8358   Function *Func = Intrinsic::getDeclaration(M, Id);
8359   return Builder.CreateCall(Func, {});
8360 }
8361 
8362 // The mappings for emitLeading/TrailingFence is taken from
8363 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8364 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8365                                          AtomicOrdering Ord, bool IsStore,
8366                                          bool IsLoad) const {
8367   if (Ord == AtomicOrdering::SequentiallyConsistent)
8368     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8369   if (isReleaseOrStronger(Ord))
8370     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8371   return nullptr;
8372 }
8373 
8374 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8375                                           AtomicOrdering Ord, bool IsStore,
8376                                           bool IsLoad) const {
8377   if (IsLoad && isAcquireOrStronger(Ord))
8378     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8379   // FIXME: this is too conservative, a dependent branch + isync is enough.
8380   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8381   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8382   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8383   return nullptr;
8384 }
8385 
8386 MachineBasicBlock *
8387 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
8388                                     unsigned AtomicSize,
8389                                     unsigned BinOpcode) const {
8390   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8391   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8392 
8393   auto LoadMnemonic = PPC::LDARX;
8394   auto StoreMnemonic = PPC::STDCX;
8395   switch (AtomicSize) {
8396   default:
8397     llvm_unreachable("Unexpected size of atomic entity");
8398   case 1:
8399     LoadMnemonic = PPC::LBARX;
8400     StoreMnemonic = PPC::STBCX;
8401     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8402     break;
8403   case 2:
8404     LoadMnemonic = PPC::LHARX;
8405     StoreMnemonic = PPC::STHCX;
8406     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8407     break;
8408   case 4:
8409     LoadMnemonic = PPC::LWARX;
8410     StoreMnemonic = PPC::STWCX;
8411     break;
8412   case 8:
8413     LoadMnemonic = PPC::LDARX;
8414     StoreMnemonic = PPC::STDCX;
8415     break;
8416   }
8417 
8418   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8419   MachineFunction *F = BB->getParent();
8420   MachineFunction::iterator It = ++BB->getIterator();
8421 
8422   unsigned dest = MI->getOperand(0).getReg();
8423   unsigned ptrA = MI->getOperand(1).getReg();
8424   unsigned ptrB = MI->getOperand(2).getReg();
8425   unsigned incr = MI->getOperand(3).getReg();
8426   DebugLoc dl = MI->getDebugLoc();
8427 
8428   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8429   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8430   F->insert(It, loopMBB);
8431   F->insert(It, exitMBB);
8432   exitMBB->splice(exitMBB->begin(), BB,
8433                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8434   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8435 
8436   MachineRegisterInfo &RegInfo = F->getRegInfo();
8437   unsigned TmpReg = (!BinOpcode) ? incr :
8438     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8439                                            : &PPC::GPRCRegClass);
8440 
8441   //  thisMBB:
8442   //   ...
8443   //   fallthrough --> loopMBB
8444   BB->addSuccessor(loopMBB);
8445 
8446   //  loopMBB:
8447   //   l[wd]arx dest, ptr
8448   //   add r0, dest, incr
8449   //   st[wd]cx. r0, ptr
8450   //   bne- loopMBB
8451   //   fallthrough --> exitMBB
8452   BB = loopMBB;
8453   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8454     .addReg(ptrA).addReg(ptrB);
8455   if (BinOpcode)
8456     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8457   BuildMI(BB, dl, TII->get(StoreMnemonic))
8458     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8459   BuildMI(BB, dl, TII->get(PPC::BCC))
8460     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8461   BB->addSuccessor(loopMBB);
8462   BB->addSuccessor(exitMBB);
8463 
8464   //  exitMBB:
8465   //   ...
8466   BB = exitMBB;
8467   return BB;
8468 }
8469 
8470 MachineBasicBlock *
8471 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8472                                             MachineBasicBlock *BB,
8473                                             bool is8bit,    // operation
8474                                             unsigned BinOpcode) const {
8475   // If we support part-word atomic mnemonics, just use them
8476   if (Subtarget.hasPartwordAtomics())
8477     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8478 
8479   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8480   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8481   // In 64 bit mode we have to use 64 bits for addresses, even though the
8482   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8483   // registers without caring whether they're 32 or 64, but here we're
8484   // doing actual arithmetic on the addresses.
8485   bool is64bit = Subtarget.isPPC64();
8486   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8487 
8488   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8489   MachineFunction *F = BB->getParent();
8490   MachineFunction::iterator It = ++BB->getIterator();
8491 
8492   unsigned dest = MI->getOperand(0).getReg();
8493   unsigned ptrA = MI->getOperand(1).getReg();
8494   unsigned ptrB = MI->getOperand(2).getReg();
8495   unsigned incr = MI->getOperand(3).getReg();
8496   DebugLoc dl = MI->getDebugLoc();
8497 
8498   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8499   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8500   F->insert(It, loopMBB);
8501   F->insert(It, exitMBB);
8502   exitMBB->splice(exitMBB->begin(), BB,
8503                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8504   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8505 
8506   MachineRegisterInfo &RegInfo = F->getRegInfo();
8507   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8508                                           : &PPC::GPRCRegClass;
8509   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8510   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8511   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8512   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8513   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8514   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8515   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8516   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8517   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8518   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8519   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8520   unsigned Ptr1Reg;
8521   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8522 
8523   //  thisMBB:
8524   //   ...
8525   //   fallthrough --> loopMBB
8526   BB->addSuccessor(loopMBB);
8527 
8528   // The 4-byte load must be aligned, while a char or short may be
8529   // anywhere in the word.  Hence all this nasty bookkeeping code.
8530   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8531   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8532   //   xori shift, shift1, 24 [16]
8533   //   rlwinm ptr, ptr1, 0, 0, 29
8534   //   slw incr2, incr, shift
8535   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8536   //   slw mask, mask2, shift
8537   //  loopMBB:
8538   //   lwarx tmpDest, ptr
8539   //   add tmp, tmpDest, incr2
8540   //   andc tmp2, tmpDest, mask
8541   //   and tmp3, tmp, mask
8542   //   or tmp4, tmp3, tmp2
8543   //   stwcx. tmp4, ptr
8544   //   bne- loopMBB
8545   //   fallthrough --> exitMBB
8546   //   srw dest, tmpDest, shift
8547   if (ptrA != ZeroReg) {
8548     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8549     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8550       .addReg(ptrA).addReg(ptrB);
8551   } else {
8552     Ptr1Reg = ptrB;
8553   }
8554   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8555       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8556   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8557       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8558   if (is64bit)
8559     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8560       .addReg(Ptr1Reg).addImm(0).addImm(61);
8561   else
8562     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8563       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8564   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8565       .addReg(incr).addReg(ShiftReg);
8566   if (is8bit)
8567     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8568   else {
8569     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8570     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8571   }
8572   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8573       .addReg(Mask2Reg).addReg(ShiftReg);
8574 
8575   BB = loopMBB;
8576   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8577     .addReg(ZeroReg).addReg(PtrReg);
8578   if (BinOpcode)
8579     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8580       .addReg(Incr2Reg).addReg(TmpDestReg);
8581   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8582     .addReg(TmpDestReg).addReg(MaskReg);
8583   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8584     .addReg(TmpReg).addReg(MaskReg);
8585   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8586     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8587   BuildMI(BB, dl, TII->get(PPC::STWCX))
8588     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8589   BuildMI(BB, dl, TII->get(PPC::BCC))
8590     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8591   BB->addSuccessor(loopMBB);
8592   BB->addSuccessor(exitMBB);
8593 
8594   //  exitMBB:
8595   //   ...
8596   BB = exitMBB;
8597   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8598     .addReg(ShiftReg);
8599   return BB;
8600 }
8601 
8602 llvm::MachineBasicBlock*
8603 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8604                                     MachineBasicBlock *MBB) const {
8605   DebugLoc DL = MI->getDebugLoc();
8606   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8607 
8608   MachineFunction *MF = MBB->getParent();
8609   MachineRegisterInfo &MRI = MF->getRegInfo();
8610 
8611   const BasicBlock *BB = MBB->getBasicBlock();
8612   MachineFunction::iterator I = ++MBB->getIterator();
8613 
8614   // Memory Reference
8615   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8616   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8617 
8618   unsigned DstReg = MI->getOperand(0).getReg();
8619   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8620   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8621   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8622   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8623 
8624   MVT PVT = getPointerTy(MF->getDataLayout());
8625   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8626          "Invalid Pointer Size!");
8627   // For v = setjmp(buf), we generate
8628   //
8629   // thisMBB:
8630   //  SjLjSetup mainMBB
8631   //  bl mainMBB
8632   //  v_restore = 1
8633   //  b sinkMBB
8634   //
8635   // mainMBB:
8636   //  buf[LabelOffset] = LR
8637   //  v_main = 0
8638   //
8639   // sinkMBB:
8640   //  v = phi(main, restore)
8641   //
8642 
8643   MachineBasicBlock *thisMBB = MBB;
8644   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8645   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8646   MF->insert(I, mainMBB);
8647   MF->insert(I, sinkMBB);
8648 
8649   MachineInstrBuilder MIB;
8650 
8651   // Transfer the remainder of BB and its successor edges to sinkMBB.
8652   sinkMBB->splice(sinkMBB->begin(), MBB,
8653                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8654   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8655 
8656   // Note that the structure of the jmp_buf used here is not compatible
8657   // with that used by libc, and is not designed to be. Specifically, it
8658   // stores only those 'reserved' registers that LLVM does not otherwise
8659   // understand how to spill. Also, by convention, by the time this
8660   // intrinsic is called, Clang has already stored the frame address in the
8661   // first slot of the buffer and stack address in the third. Following the
8662   // X86 target code, we'll store the jump address in the second slot. We also
8663   // need to save the TOC pointer (R2) to handle jumps between shared
8664   // libraries, and that will be stored in the fourth slot. The thread
8665   // identifier (R13) is not affected.
8666 
8667   // thisMBB:
8668   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8669   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8670   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8671 
8672   // Prepare IP either in reg.
8673   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8674   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8675   unsigned BufReg = MI->getOperand(1).getReg();
8676 
8677   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8678     setUsesTOCBasePtr(*MBB->getParent());
8679     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8680             .addReg(PPC::X2)
8681             .addImm(TOCOffset)
8682             .addReg(BufReg);
8683     MIB.setMemRefs(MMOBegin, MMOEnd);
8684   }
8685 
8686   // Naked functions never have a base pointer, and so we use r1. For all
8687   // other functions, this decision must be delayed until during PEI.
8688   unsigned BaseReg;
8689   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8690     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8691   else
8692     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8693 
8694   MIB = BuildMI(*thisMBB, MI, DL,
8695                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8696             .addReg(BaseReg)
8697             .addImm(BPOffset)
8698             .addReg(BufReg);
8699   MIB.setMemRefs(MMOBegin, MMOEnd);
8700 
8701   // Setup
8702   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8703   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8704   MIB.addRegMask(TRI->getNoPreservedMask());
8705 
8706   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8707 
8708   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8709           .addMBB(mainMBB);
8710   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8711 
8712   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8713   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8714 
8715   // mainMBB:
8716   //  mainDstReg = 0
8717   MIB =
8718       BuildMI(mainMBB, DL,
8719               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8720 
8721   // Store IP
8722   if (Subtarget.isPPC64()) {
8723     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8724             .addReg(LabelReg)
8725             .addImm(LabelOffset)
8726             .addReg(BufReg);
8727   } else {
8728     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8729             .addReg(LabelReg)
8730             .addImm(LabelOffset)
8731             .addReg(BufReg);
8732   }
8733 
8734   MIB.setMemRefs(MMOBegin, MMOEnd);
8735 
8736   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8737   mainMBB->addSuccessor(sinkMBB);
8738 
8739   // sinkMBB:
8740   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8741           TII->get(PPC::PHI), DstReg)
8742     .addReg(mainDstReg).addMBB(mainMBB)
8743     .addReg(restoreDstReg).addMBB(thisMBB);
8744 
8745   MI->eraseFromParent();
8746   return sinkMBB;
8747 }
8748 
8749 MachineBasicBlock *
8750 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8751                                      MachineBasicBlock *MBB) const {
8752   DebugLoc DL = MI->getDebugLoc();
8753   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8754 
8755   MachineFunction *MF = MBB->getParent();
8756   MachineRegisterInfo &MRI = MF->getRegInfo();
8757 
8758   // Memory Reference
8759   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8760   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8761 
8762   MVT PVT = getPointerTy(MF->getDataLayout());
8763   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8764          "Invalid Pointer Size!");
8765 
8766   const TargetRegisterClass *RC =
8767     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8768   unsigned Tmp = MRI.createVirtualRegister(RC);
8769   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8770   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8771   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8772   unsigned BP =
8773       (PVT == MVT::i64)
8774           ? PPC::X30
8775           : (Subtarget.isSVR4ABI() &&
8776                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8777                  ? PPC::R29
8778                  : PPC::R30);
8779 
8780   MachineInstrBuilder MIB;
8781 
8782   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8783   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8784   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8785   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8786 
8787   unsigned BufReg = MI->getOperand(0).getReg();
8788 
8789   // Reload FP (the jumped-to function may not have had a
8790   // frame pointer, and if so, then its r31 will be restored
8791   // as necessary).
8792   if (PVT == MVT::i64) {
8793     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8794             .addImm(0)
8795             .addReg(BufReg);
8796   } else {
8797     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8798             .addImm(0)
8799             .addReg(BufReg);
8800   }
8801   MIB.setMemRefs(MMOBegin, MMOEnd);
8802 
8803   // Reload IP
8804   if (PVT == MVT::i64) {
8805     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8806             .addImm(LabelOffset)
8807             .addReg(BufReg);
8808   } else {
8809     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8810             .addImm(LabelOffset)
8811             .addReg(BufReg);
8812   }
8813   MIB.setMemRefs(MMOBegin, MMOEnd);
8814 
8815   // Reload SP
8816   if (PVT == MVT::i64) {
8817     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8818             .addImm(SPOffset)
8819             .addReg(BufReg);
8820   } else {
8821     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8822             .addImm(SPOffset)
8823             .addReg(BufReg);
8824   }
8825   MIB.setMemRefs(MMOBegin, MMOEnd);
8826 
8827   // Reload BP
8828   if (PVT == MVT::i64) {
8829     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8830             .addImm(BPOffset)
8831             .addReg(BufReg);
8832   } else {
8833     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8834             .addImm(BPOffset)
8835             .addReg(BufReg);
8836   }
8837   MIB.setMemRefs(MMOBegin, MMOEnd);
8838 
8839   // Reload TOC
8840   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8841     setUsesTOCBasePtr(*MBB->getParent());
8842     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8843             .addImm(TOCOffset)
8844             .addReg(BufReg);
8845 
8846     MIB.setMemRefs(MMOBegin, MMOEnd);
8847   }
8848 
8849   // Jump
8850   BuildMI(*MBB, MI, DL,
8851           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8852   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8853 
8854   MI->eraseFromParent();
8855   return MBB;
8856 }
8857 
8858 MachineBasicBlock *
8859 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8860                                                MachineBasicBlock *BB) const {
8861   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8862       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8863     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8864         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8865       // Call lowering should have added an r2 operand to indicate a dependence
8866       // on the TOC base pointer value. It can't however, because there is no
8867       // way to mark the dependence as implicit there, and so the stackmap code
8868       // will confuse it with a regular operand. Instead, add the dependence
8869       // here.
8870       setUsesTOCBasePtr(*BB->getParent());
8871       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8872     }
8873 
8874     return emitPatchPoint(MI, BB);
8875   }
8876 
8877   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8878       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8879     return emitEHSjLjSetJmp(MI, BB);
8880   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8881              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8882     return emitEHSjLjLongJmp(MI, BB);
8883   }
8884 
8885   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8886 
8887   // To "insert" these instructions we actually have to insert their
8888   // control-flow patterns.
8889   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8890   MachineFunction::iterator It = ++BB->getIterator();
8891 
8892   MachineFunction *F = BB->getParent();
8893 
8894   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8895                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8896                               MI->getOpcode() == PPC::SELECT_I4 ||
8897                               MI->getOpcode() == PPC::SELECT_I8)) {
8898     SmallVector<MachineOperand, 2> Cond;
8899     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8900         MI->getOpcode() == PPC::SELECT_CC_I8)
8901       Cond.push_back(MI->getOperand(4));
8902     else
8903       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8904     Cond.push_back(MI->getOperand(1));
8905 
8906     DebugLoc dl = MI->getDebugLoc();
8907     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8908                       Cond, MI->getOperand(2).getReg(),
8909                       MI->getOperand(3).getReg());
8910   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8911              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8912              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8913              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8914              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8915              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8916              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8917              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8918              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8919              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8920              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8921              MI->getOpcode() == PPC::SELECT_I4 ||
8922              MI->getOpcode() == PPC::SELECT_I8 ||
8923              MI->getOpcode() == PPC::SELECT_F4 ||
8924              MI->getOpcode() == PPC::SELECT_F8 ||
8925              MI->getOpcode() == PPC::SELECT_QFRC ||
8926              MI->getOpcode() == PPC::SELECT_QSRC ||
8927              MI->getOpcode() == PPC::SELECT_QBRC ||
8928              MI->getOpcode() == PPC::SELECT_VRRC ||
8929              MI->getOpcode() == PPC::SELECT_VSFRC ||
8930              MI->getOpcode() == PPC::SELECT_VSSRC ||
8931              MI->getOpcode() == PPC::SELECT_VSRC) {
8932     // The incoming instruction knows the destination vreg to set, the
8933     // condition code register to branch on, the true/false values to
8934     // select between, and a branch opcode to use.
8935 
8936     //  thisMBB:
8937     //  ...
8938     //   TrueVal = ...
8939     //   cmpTY ccX, r1, r2
8940     //   bCC copy1MBB
8941     //   fallthrough --> copy0MBB
8942     MachineBasicBlock *thisMBB = BB;
8943     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8944     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8945     DebugLoc dl = MI->getDebugLoc();
8946     F->insert(It, copy0MBB);
8947     F->insert(It, sinkMBB);
8948 
8949     // Transfer the remainder of BB and its successor edges to sinkMBB.
8950     sinkMBB->splice(sinkMBB->begin(), BB,
8951                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8952     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8953 
8954     // Next, add the true and fallthrough blocks as its successors.
8955     BB->addSuccessor(copy0MBB);
8956     BB->addSuccessor(sinkMBB);
8957 
8958     if (MI->getOpcode() == PPC::SELECT_I4 ||
8959         MI->getOpcode() == PPC::SELECT_I8 ||
8960         MI->getOpcode() == PPC::SELECT_F4 ||
8961         MI->getOpcode() == PPC::SELECT_F8 ||
8962         MI->getOpcode() == PPC::SELECT_QFRC ||
8963         MI->getOpcode() == PPC::SELECT_QSRC ||
8964         MI->getOpcode() == PPC::SELECT_QBRC ||
8965         MI->getOpcode() == PPC::SELECT_VRRC ||
8966         MI->getOpcode() == PPC::SELECT_VSFRC ||
8967         MI->getOpcode() == PPC::SELECT_VSSRC ||
8968         MI->getOpcode() == PPC::SELECT_VSRC) {
8969       BuildMI(BB, dl, TII->get(PPC::BC))
8970         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8971     } else {
8972       unsigned SelectPred = MI->getOperand(4).getImm();
8973       BuildMI(BB, dl, TII->get(PPC::BCC))
8974         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8975     }
8976 
8977     //  copy0MBB:
8978     //   %FalseValue = ...
8979     //   # fallthrough to sinkMBB
8980     BB = copy0MBB;
8981 
8982     // Update machine-CFG edges
8983     BB->addSuccessor(sinkMBB);
8984 
8985     //  sinkMBB:
8986     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8987     //  ...
8988     BB = sinkMBB;
8989     BuildMI(*BB, BB->begin(), dl,
8990             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8991       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8992       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8993   } else if (MI->getOpcode() == PPC::ReadTB) {
8994     // To read the 64-bit time-base register on a 32-bit target, we read the
8995     // two halves. Should the counter have wrapped while it was being read, we
8996     // need to try again.
8997     // ...
8998     // readLoop:
8999     // mfspr Rx,TBU # load from TBU
9000     // mfspr Ry,TB  # load from TB
9001     // mfspr Rz,TBU # load from TBU
9002     // cmpw crX,Rx,Rz # check if 'old'='new'
9003     // bne readLoop   # branch if they're not equal
9004     // ...
9005 
9006     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9007     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9008     DebugLoc dl = MI->getDebugLoc();
9009     F->insert(It, readMBB);
9010     F->insert(It, sinkMBB);
9011 
9012     // Transfer the remainder of BB and its successor edges to sinkMBB.
9013     sinkMBB->splice(sinkMBB->begin(), BB,
9014                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9015     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9016 
9017     BB->addSuccessor(readMBB);
9018     BB = readMBB;
9019 
9020     MachineRegisterInfo &RegInfo = F->getRegInfo();
9021     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9022     unsigned LoReg = MI->getOperand(0).getReg();
9023     unsigned HiReg = MI->getOperand(1).getReg();
9024 
9025     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9026     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9027     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9028 
9029     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9030 
9031     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9032       .addReg(HiReg).addReg(ReadAgainReg);
9033     BuildMI(BB, dl, TII->get(PPC::BCC))
9034       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9035 
9036     BB->addSuccessor(readMBB);
9037     BB->addSuccessor(sinkMBB);
9038   }
9039   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9040     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9041   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9042     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9043   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9044     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9045   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9046     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9047 
9048   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9049     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9050   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9051     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9052   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9053     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9054   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9055     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9056 
9057   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9058     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9059   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9060     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9061   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9062     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9063   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9064     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9065 
9066   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9067     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9068   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9069     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9070   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9071     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9072   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9073     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9074 
9075   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9076     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9077   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9078     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9079   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9080     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9081   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9082     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9083 
9084   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9085     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9086   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9087     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9088   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9089     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9090   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9091     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9092 
9093   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
9094     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9095   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
9096     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9097   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
9098     BB = EmitAtomicBinary(MI, BB, 4, 0);
9099   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
9100     BB = EmitAtomicBinary(MI, BB, 8, 0);
9101 
9102   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9103            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9104            (Subtarget.hasPartwordAtomics() &&
9105             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9106            (Subtarget.hasPartwordAtomics() &&
9107             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9108     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9109 
9110     auto LoadMnemonic = PPC::LDARX;
9111     auto StoreMnemonic = PPC::STDCX;
9112     switch(MI->getOpcode()) {
9113     default:
9114       llvm_unreachable("Compare and swap of unknown size");
9115     case PPC::ATOMIC_CMP_SWAP_I8:
9116       LoadMnemonic = PPC::LBARX;
9117       StoreMnemonic = PPC::STBCX;
9118       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9119       break;
9120     case PPC::ATOMIC_CMP_SWAP_I16:
9121       LoadMnemonic = PPC::LHARX;
9122       StoreMnemonic = PPC::STHCX;
9123       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9124       break;
9125     case PPC::ATOMIC_CMP_SWAP_I32:
9126       LoadMnemonic = PPC::LWARX;
9127       StoreMnemonic = PPC::STWCX;
9128       break;
9129     case PPC::ATOMIC_CMP_SWAP_I64:
9130       LoadMnemonic = PPC::LDARX;
9131       StoreMnemonic = PPC::STDCX;
9132       break;
9133     }
9134     unsigned dest   = MI->getOperand(0).getReg();
9135     unsigned ptrA   = MI->getOperand(1).getReg();
9136     unsigned ptrB   = MI->getOperand(2).getReg();
9137     unsigned oldval = MI->getOperand(3).getReg();
9138     unsigned newval = MI->getOperand(4).getReg();
9139     DebugLoc dl     = MI->getDebugLoc();
9140 
9141     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9142     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9143     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9144     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9145     F->insert(It, loop1MBB);
9146     F->insert(It, loop2MBB);
9147     F->insert(It, midMBB);
9148     F->insert(It, exitMBB);
9149     exitMBB->splice(exitMBB->begin(), BB,
9150                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9151     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9152 
9153     //  thisMBB:
9154     //   ...
9155     //   fallthrough --> loopMBB
9156     BB->addSuccessor(loop1MBB);
9157 
9158     // loop1MBB:
9159     //   l[bhwd]arx dest, ptr
9160     //   cmp[wd] dest, oldval
9161     //   bne- midMBB
9162     // loop2MBB:
9163     //   st[bhwd]cx. newval, ptr
9164     //   bne- loopMBB
9165     //   b exitBB
9166     // midMBB:
9167     //   st[bhwd]cx. dest, ptr
9168     // exitBB:
9169     BB = loop1MBB;
9170     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9171       .addReg(ptrA).addReg(ptrB);
9172     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9173       .addReg(oldval).addReg(dest);
9174     BuildMI(BB, dl, TII->get(PPC::BCC))
9175       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9176     BB->addSuccessor(loop2MBB);
9177     BB->addSuccessor(midMBB);
9178 
9179     BB = loop2MBB;
9180     BuildMI(BB, dl, TII->get(StoreMnemonic))
9181       .addReg(newval).addReg(ptrA).addReg(ptrB);
9182     BuildMI(BB, dl, TII->get(PPC::BCC))
9183       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9184     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9185     BB->addSuccessor(loop1MBB);
9186     BB->addSuccessor(exitMBB);
9187 
9188     BB = midMBB;
9189     BuildMI(BB, dl, TII->get(StoreMnemonic))
9190       .addReg(dest).addReg(ptrA).addReg(ptrB);
9191     BB->addSuccessor(exitMBB);
9192 
9193     //  exitMBB:
9194     //   ...
9195     BB = exitMBB;
9196   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9197              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9198     // We must use 64-bit registers for addresses when targeting 64-bit,
9199     // since we're actually doing arithmetic on them.  Other registers
9200     // can be 32-bit.
9201     bool is64bit = Subtarget.isPPC64();
9202     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9203 
9204     unsigned dest   = MI->getOperand(0).getReg();
9205     unsigned ptrA   = MI->getOperand(1).getReg();
9206     unsigned ptrB   = MI->getOperand(2).getReg();
9207     unsigned oldval = MI->getOperand(3).getReg();
9208     unsigned newval = MI->getOperand(4).getReg();
9209     DebugLoc dl     = MI->getDebugLoc();
9210 
9211     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9212     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9213     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9214     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9215     F->insert(It, loop1MBB);
9216     F->insert(It, loop2MBB);
9217     F->insert(It, midMBB);
9218     F->insert(It, exitMBB);
9219     exitMBB->splice(exitMBB->begin(), BB,
9220                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9221     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9222 
9223     MachineRegisterInfo &RegInfo = F->getRegInfo();
9224     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9225                                             : &PPC::GPRCRegClass;
9226     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9227     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9228     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
9229     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9230     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9231     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9232     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9233     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9234     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9235     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9236     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9237     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9238     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9239     unsigned Ptr1Reg;
9240     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9241     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9242     //  thisMBB:
9243     //   ...
9244     //   fallthrough --> loopMBB
9245     BB->addSuccessor(loop1MBB);
9246 
9247     // The 4-byte load must be aligned, while a char or short may be
9248     // anywhere in the word.  Hence all this nasty bookkeeping code.
9249     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9250     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9251     //   xori shift, shift1, 24 [16]
9252     //   rlwinm ptr, ptr1, 0, 0, 29
9253     //   slw newval2, newval, shift
9254     //   slw oldval2, oldval,shift
9255     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9256     //   slw mask, mask2, shift
9257     //   and newval3, newval2, mask
9258     //   and oldval3, oldval2, mask
9259     // loop1MBB:
9260     //   lwarx tmpDest, ptr
9261     //   and tmp, tmpDest, mask
9262     //   cmpw tmp, oldval3
9263     //   bne- midMBB
9264     // loop2MBB:
9265     //   andc tmp2, tmpDest, mask
9266     //   or tmp4, tmp2, newval3
9267     //   stwcx. tmp4, ptr
9268     //   bne- loop1MBB
9269     //   b exitBB
9270     // midMBB:
9271     //   stwcx. tmpDest, ptr
9272     // exitBB:
9273     //   srw dest, tmpDest, shift
9274     if (ptrA != ZeroReg) {
9275       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9276       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9277         .addReg(ptrA).addReg(ptrB);
9278     } else {
9279       Ptr1Reg = ptrB;
9280     }
9281     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9282         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9283     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9284         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9285     if (is64bit)
9286       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9287         .addReg(Ptr1Reg).addImm(0).addImm(61);
9288     else
9289       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9290         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9291     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9292         .addReg(newval).addReg(ShiftReg);
9293     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9294         .addReg(oldval).addReg(ShiftReg);
9295     if (is8bit)
9296       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9297     else {
9298       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9299       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9300         .addReg(Mask3Reg).addImm(65535);
9301     }
9302     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9303         .addReg(Mask2Reg).addReg(ShiftReg);
9304     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9305         .addReg(NewVal2Reg).addReg(MaskReg);
9306     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9307         .addReg(OldVal2Reg).addReg(MaskReg);
9308 
9309     BB = loop1MBB;
9310     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9311         .addReg(ZeroReg).addReg(PtrReg);
9312     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9313         .addReg(TmpDestReg).addReg(MaskReg);
9314     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9315         .addReg(TmpReg).addReg(OldVal3Reg);
9316     BuildMI(BB, dl, TII->get(PPC::BCC))
9317         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9318     BB->addSuccessor(loop2MBB);
9319     BB->addSuccessor(midMBB);
9320 
9321     BB = loop2MBB;
9322     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9323         .addReg(TmpDestReg).addReg(MaskReg);
9324     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9325         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9326     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9327         .addReg(ZeroReg).addReg(PtrReg);
9328     BuildMI(BB, dl, TII->get(PPC::BCC))
9329       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9330     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9331     BB->addSuccessor(loop1MBB);
9332     BB->addSuccessor(exitMBB);
9333 
9334     BB = midMBB;
9335     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9336       .addReg(ZeroReg).addReg(PtrReg);
9337     BB->addSuccessor(exitMBB);
9338 
9339     //  exitMBB:
9340     //   ...
9341     BB = exitMBB;
9342     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9343       .addReg(ShiftReg);
9344   } else if (MI->getOpcode() == PPC::FADDrtz) {
9345     // This pseudo performs an FADD with rounding mode temporarily forced
9346     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9347     // is not modeled at the SelectionDAG level.
9348     unsigned Dest = MI->getOperand(0).getReg();
9349     unsigned Src1 = MI->getOperand(1).getReg();
9350     unsigned Src2 = MI->getOperand(2).getReg();
9351     DebugLoc dl   = MI->getDebugLoc();
9352 
9353     MachineRegisterInfo &RegInfo = F->getRegInfo();
9354     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9355 
9356     // Save FPSCR value.
9357     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9358 
9359     // Set rounding mode to round-to-zero.
9360     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9361     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9362 
9363     // Perform addition.
9364     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9365 
9366     // Restore FPSCR value.
9367     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9368   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9369              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
9370              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9371              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9372     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9373                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
9374                       PPC::ANDIo8 : PPC::ANDIo;
9375     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9376                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9377 
9378     MachineRegisterInfo &RegInfo = F->getRegInfo();
9379     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9380                                                   &PPC::GPRCRegClass :
9381                                                   &PPC::G8RCRegClass);
9382 
9383     DebugLoc dl   = MI->getDebugLoc();
9384     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9385       .addReg(MI->getOperand(1).getReg()).addImm(1);
9386     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9387             MI->getOperand(0).getReg())
9388       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9389   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
9390     DebugLoc Dl = MI->getDebugLoc();
9391     MachineRegisterInfo &RegInfo = F->getRegInfo();
9392     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9393     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9394     return BB;
9395   } else {
9396     llvm_unreachable("Unexpected instr type to insert");
9397   }
9398 
9399   MI->eraseFromParent();   // The pseudo instruction is gone now.
9400   return BB;
9401 }
9402 
9403 //===----------------------------------------------------------------------===//
9404 // Target Optimization Hooks
9405 //===----------------------------------------------------------------------===//
9406 
9407 static std::string getRecipOp(const char *Base, EVT VT) {
9408   std::string RecipOp(Base);
9409   if (VT.getScalarType() == MVT::f64)
9410     RecipOp += "d";
9411   else
9412     RecipOp += "f";
9413 
9414   if (VT.isVector())
9415     RecipOp = "vec-" + RecipOp;
9416 
9417   return RecipOp;
9418 }
9419 
9420 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9421                                             DAGCombinerInfo &DCI,
9422                                             unsigned &RefinementSteps,
9423                                             bool &UseOneConstNR) const {
9424   EVT VT = Operand.getValueType();
9425   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9426       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9427       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9428       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9429       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9430       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9431     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9432     std::string RecipOp = getRecipOp("sqrt", VT);
9433     if (!Recips.isEnabled(RecipOp))
9434       return SDValue();
9435 
9436     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9437     UseOneConstNR = true;
9438     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9439   }
9440   return SDValue();
9441 }
9442 
9443 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9444                                             DAGCombinerInfo &DCI,
9445                                             unsigned &RefinementSteps) const {
9446   EVT VT = Operand.getValueType();
9447   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9448       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9449       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9450       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9451       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9452       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9453     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9454     std::string RecipOp = getRecipOp("div", VT);
9455     if (!Recips.isEnabled(RecipOp))
9456       return SDValue();
9457 
9458     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9459     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9460   }
9461   return SDValue();
9462 }
9463 
9464 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9465   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9466   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9467   // enabled for division), this functionality is redundant with the default
9468   // combiner logic (once the division -> reciprocal/multiply transformation
9469   // has taken place). As a result, this matters more for older cores than for
9470   // newer ones.
9471 
9472   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9473   // reciprocal if there are two or more FDIVs (for embedded cores with only
9474   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9475   switch (Subtarget.getDarwinDirective()) {
9476   default:
9477     return 3;
9478   case PPC::DIR_440:
9479   case PPC::DIR_A2:
9480   case PPC::DIR_E500mc:
9481   case PPC::DIR_E5500:
9482     return 2;
9483   }
9484 }
9485 
9486 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9487 // collapsed, and so we need to look through chains of them.
9488 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9489                                      int64_t& Offset, SelectionDAG &DAG) {
9490   if (DAG.isBaseWithConstantOffset(Loc)) {
9491     Base = Loc.getOperand(0);
9492     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9493 
9494     // The base might itself be a base plus an offset, and if so, accumulate
9495     // that as well.
9496     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9497   }
9498 }
9499 
9500 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9501                             unsigned Bytes, int Dist,
9502                             SelectionDAG &DAG) {
9503   if (VT.getSizeInBits() / 8 != Bytes)
9504     return false;
9505 
9506   SDValue BaseLoc = Base->getBasePtr();
9507   if (Loc.getOpcode() == ISD::FrameIndex) {
9508     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9509       return false;
9510     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9511     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9512     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9513     int FS  = MFI->getObjectSize(FI);
9514     int BFS = MFI->getObjectSize(BFI);
9515     if (FS != BFS || FS != (int)Bytes) return false;
9516     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9517   }
9518 
9519   SDValue Base1 = Loc, Base2 = BaseLoc;
9520   int64_t Offset1 = 0, Offset2 = 0;
9521   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9522   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9523   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9524     return true;
9525 
9526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9527   const GlobalValue *GV1 = nullptr;
9528   const GlobalValue *GV2 = nullptr;
9529   Offset1 = 0;
9530   Offset2 = 0;
9531   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9532   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9533   if (isGA1 && isGA2 && GV1 == GV2)
9534     return Offset1 == (Offset2 + Dist*Bytes);
9535   return false;
9536 }
9537 
9538 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9539 // not enforce equality of the chain operands.
9540 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9541                             unsigned Bytes, int Dist,
9542                             SelectionDAG &DAG) {
9543   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9544     EVT VT = LS->getMemoryVT();
9545     SDValue Loc = LS->getBasePtr();
9546     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9547   }
9548 
9549   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9550     EVT VT;
9551     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9552     default: return false;
9553     case Intrinsic::ppc_qpx_qvlfd:
9554     case Intrinsic::ppc_qpx_qvlfda:
9555       VT = MVT::v4f64;
9556       break;
9557     case Intrinsic::ppc_qpx_qvlfs:
9558     case Intrinsic::ppc_qpx_qvlfsa:
9559       VT = MVT::v4f32;
9560       break;
9561     case Intrinsic::ppc_qpx_qvlfcd:
9562     case Intrinsic::ppc_qpx_qvlfcda:
9563       VT = MVT::v2f64;
9564       break;
9565     case Intrinsic::ppc_qpx_qvlfcs:
9566     case Intrinsic::ppc_qpx_qvlfcsa:
9567       VT = MVT::v2f32;
9568       break;
9569     case Intrinsic::ppc_qpx_qvlfiwa:
9570     case Intrinsic::ppc_qpx_qvlfiwz:
9571     case Intrinsic::ppc_altivec_lvx:
9572     case Intrinsic::ppc_altivec_lvxl:
9573     case Intrinsic::ppc_vsx_lxvw4x:
9574       VT = MVT::v4i32;
9575       break;
9576     case Intrinsic::ppc_vsx_lxvd2x:
9577       VT = MVT::v2f64;
9578       break;
9579     case Intrinsic::ppc_altivec_lvebx:
9580       VT = MVT::i8;
9581       break;
9582     case Intrinsic::ppc_altivec_lvehx:
9583       VT = MVT::i16;
9584       break;
9585     case Intrinsic::ppc_altivec_lvewx:
9586       VT = MVT::i32;
9587       break;
9588     }
9589 
9590     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9591   }
9592 
9593   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9594     EVT VT;
9595     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9596     default: return false;
9597     case Intrinsic::ppc_qpx_qvstfd:
9598     case Intrinsic::ppc_qpx_qvstfda:
9599       VT = MVT::v4f64;
9600       break;
9601     case Intrinsic::ppc_qpx_qvstfs:
9602     case Intrinsic::ppc_qpx_qvstfsa:
9603       VT = MVT::v4f32;
9604       break;
9605     case Intrinsic::ppc_qpx_qvstfcd:
9606     case Intrinsic::ppc_qpx_qvstfcda:
9607       VT = MVT::v2f64;
9608       break;
9609     case Intrinsic::ppc_qpx_qvstfcs:
9610     case Intrinsic::ppc_qpx_qvstfcsa:
9611       VT = MVT::v2f32;
9612       break;
9613     case Intrinsic::ppc_qpx_qvstfiw:
9614     case Intrinsic::ppc_qpx_qvstfiwa:
9615     case Intrinsic::ppc_altivec_stvx:
9616     case Intrinsic::ppc_altivec_stvxl:
9617     case Intrinsic::ppc_vsx_stxvw4x:
9618       VT = MVT::v4i32;
9619       break;
9620     case Intrinsic::ppc_vsx_stxvd2x:
9621       VT = MVT::v2f64;
9622       break;
9623     case Intrinsic::ppc_altivec_stvebx:
9624       VT = MVT::i8;
9625       break;
9626     case Intrinsic::ppc_altivec_stvehx:
9627       VT = MVT::i16;
9628       break;
9629     case Intrinsic::ppc_altivec_stvewx:
9630       VT = MVT::i32;
9631       break;
9632     }
9633 
9634     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9635   }
9636 
9637   return false;
9638 }
9639 
9640 // Return true is there is a nearyby consecutive load to the one provided
9641 // (regardless of alignment). We search up and down the chain, looking though
9642 // token factors and other loads (but nothing else). As a result, a true result
9643 // indicates that it is safe to create a new consecutive load adjacent to the
9644 // load provided.
9645 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9646   SDValue Chain = LD->getChain();
9647   EVT VT = LD->getMemoryVT();
9648 
9649   SmallSet<SDNode *, 16> LoadRoots;
9650   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9651   SmallSet<SDNode *, 16> Visited;
9652 
9653   // First, search up the chain, branching to follow all token-factor operands.
9654   // If we find a consecutive load, then we're done, otherwise, record all
9655   // nodes just above the top-level loads and token factors.
9656   while (!Queue.empty()) {
9657     SDNode *ChainNext = Queue.pop_back_val();
9658     if (!Visited.insert(ChainNext).second)
9659       continue;
9660 
9661     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9662       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9663         return true;
9664 
9665       if (!Visited.count(ChainLD->getChain().getNode()))
9666         Queue.push_back(ChainLD->getChain().getNode());
9667     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9668       for (const SDUse &O : ChainNext->ops())
9669         if (!Visited.count(O.getNode()))
9670           Queue.push_back(O.getNode());
9671     } else
9672       LoadRoots.insert(ChainNext);
9673   }
9674 
9675   // Second, search down the chain, starting from the top-level nodes recorded
9676   // in the first phase. These top-level nodes are the nodes just above all
9677   // loads and token factors. Starting with their uses, recursively look though
9678   // all loads (just the chain uses) and token factors to find a consecutive
9679   // load.
9680   Visited.clear();
9681   Queue.clear();
9682 
9683   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9684        IE = LoadRoots.end(); I != IE; ++I) {
9685     Queue.push_back(*I);
9686 
9687     while (!Queue.empty()) {
9688       SDNode *LoadRoot = Queue.pop_back_val();
9689       if (!Visited.insert(LoadRoot).second)
9690         continue;
9691 
9692       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9693         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9694           return true;
9695 
9696       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9697            UE = LoadRoot->use_end(); UI != UE; ++UI)
9698         if (((isa<MemSDNode>(*UI) &&
9699             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9700             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9701           Queue.push_back(*UI);
9702     }
9703   }
9704 
9705   return false;
9706 }
9707 
9708 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9709                                                   DAGCombinerInfo &DCI) const {
9710   SelectionDAG &DAG = DCI.DAG;
9711   SDLoc dl(N);
9712 
9713   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9714   // If we're tracking CR bits, we need to be careful that we don't have:
9715   //   trunc(binary-ops(zext(x), zext(y)))
9716   // or
9717   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9718   // such that we're unnecessarily moving things into GPRs when it would be
9719   // better to keep them in CR bits.
9720 
9721   // Note that trunc here can be an actual i1 trunc, or can be the effective
9722   // truncation that comes from a setcc or select_cc.
9723   if (N->getOpcode() == ISD::TRUNCATE &&
9724       N->getValueType(0) != MVT::i1)
9725     return SDValue();
9726 
9727   if (N->getOperand(0).getValueType() != MVT::i32 &&
9728       N->getOperand(0).getValueType() != MVT::i64)
9729     return SDValue();
9730 
9731   if (N->getOpcode() == ISD::SETCC ||
9732       N->getOpcode() == ISD::SELECT_CC) {
9733     // If we're looking at a comparison, then we need to make sure that the
9734     // high bits (all except for the first) don't matter the result.
9735     ISD::CondCode CC =
9736       cast<CondCodeSDNode>(N->getOperand(
9737         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9738     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9739 
9740     if (ISD::isSignedIntSetCC(CC)) {
9741       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9742           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9743         return SDValue();
9744     } else if (ISD::isUnsignedIntSetCC(CC)) {
9745       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9746                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9747           !DAG.MaskedValueIsZero(N->getOperand(1),
9748                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9749         return SDValue();
9750     } else {
9751       // This is neither a signed nor an unsigned comparison, just make sure
9752       // that the high bits are equal.
9753       APInt Op1Zero, Op1One;
9754       APInt Op2Zero, Op2One;
9755       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9756       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9757 
9758       // We don't really care about what is known about the first bit (if
9759       // anything), so clear it in all masks prior to comparing them.
9760       Op1Zero.clearBit(0); Op1One.clearBit(0);
9761       Op2Zero.clearBit(0); Op2One.clearBit(0);
9762 
9763       if (Op1Zero != Op2Zero || Op1One != Op2One)
9764         return SDValue();
9765     }
9766   }
9767 
9768   // We now know that the higher-order bits are irrelevant, we just need to
9769   // make sure that all of the intermediate operations are bit operations, and
9770   // all inputs are extensions.
9771   if (N->getOperand(0).getOpcode() != ISD::AND &&
9772       N->getOperand(0).getOpcode() != ISD::OR  &&
9773       N->getOperand(0).getOpcode() != ISD::XOR &&
9774       N->getOperand(0).getOpcode() != ISD::SELECT &&
9775       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9776       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9777       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9778       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9779       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9780     return SDValue();
9781 
9782   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9783       N->getOperand(1).getOpcode() != ISD::AND &&
9784       N->getOperand(1).getOpcode() != ISD::OR  &&
9785       N->getOperand(1).getOpcode() != ISD::XOR &&
9786       N->getOperand(1).getOpcode() != ISD::SELECT &&
9787       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9788       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9789       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9790       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9791       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9792     return SDValue();
9793 
9794   SmallVector<SDValue, 4> Inputs;
9795   SmallVector<SDValue, 8> BinOps, PromOps;
9796   SmallPtrSet<SDNode *, 16> Visited;
9797 
9798   for (unsigned i = 0; i < 2; ++i) {
9799     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9800           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9801           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9802           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9803         isa<ConstantSDNode>(N->getOperand(i)))
9804       Inputs.push_back(N->getOperand(i));
9805     else
9806       BinOps.push_back(N->getOperand(i));
9807 
9808     if (N->getOpcode() == ISD::TRUNCATE)
9809       break;
9810   }
9811 
9812   // Visit all inputs, collect all binary operations (and, or, xor and
9813   // select) that are all fed by extensions.
9814   while (!BinOps.empty()) {
9815     SDValue BinOp = BinOps.back();
9816     BinOps.pop_back();
9817 
9818     if (!Visited.insert(BinOp.getNode()).second)
9819       continue;
9820 
9821     PromOps.push_back(BinOp);
9822 
9823     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9824       // The condition of the select is not promoted.
9825       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9826         continue;
9827       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9828         continue;
9829 
9830       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9831             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9832             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9833            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9834           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9835         Inputs.push_back(BinOp.getOperand(i));
9836       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9837                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9838                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9839                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9840                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9841                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9842                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9843                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9844                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9845         BinOps.push_back(BinOp.getOperand(i));
9846       } else {
9847         // We have an input that is not an extension or another binary
9848         // operation; we'll abort this transformation.
9849         return SDValue();
9850       }
9851     }
9852   }
9853 
9854   // Make sure that this is a self-contained cluster of operations (which
9855   // is not quite the same thing as saying that everything has only one
9856   // use).
9857   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9858     if (isa<ConstantSDNode>(Inputs[i]))
9859       continue;
9860 
9861     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9862                               UE = Inputs[i].getNode()->use_end();
9863          UI != UE; ++UI) {
9864       SDNode *User = *UI;
9865       if (User != N && !Visited.count(User))
9866         return SDValue();
9867 
9868       // Make sure that we're not going to promote the non-output-value
9869       // operand(s) or SELECT or SELECT_CC.
9870       // FIXME: Although we could sometimes handle this, and it does occur in
9871       // practice that one of the condition inputs to the select is also one of
9872       // the outputs, we currently can't deal with this.
9873       if (User->getOpcode() == ISD::SELECT) {
9874         if (User->getOperand(0) == Inputs[i])
9875           return SDValue();
9876       } else if (User->getOpcode() == ISD::SELECT_CC) {
9877         if (User->getOperand(0) == Inputs[i] ||
9878             User->getOperand(1) == Inputs[i])
9879           return SDValue();
9880       }
9881     }
9882   }
9883 
9884   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9885     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9886                               UE = PromOps[i].getNode()->use_end();
9887          UI != UE; ++UI) {
9888       SDNode *User = *UI;
9889       if (User != N && !Visited.count(User))
9890         return SDValue();
9891 
9892       // Make sure that we're not going to promote the non-output-value
9893       // operand(s) or SELECT or SELECT_CC.
9894       // FIXME: Although we could sometimes handle this, and it does occur in
9895       // practice that one of the condition inputs to the select is also one of
9896       // the outputs, we currently can't deal with this.
9897       if (User->getOpcode() == ISD::SELECT) {
9898         if (User->getOperand(0) == PromOps[i])
9899           return SDValue();
9900       } else if (User->getOpcode() == ISD::SELECT_CC) {
9901         if (User->getOperand(0) == PromOps[i] ||
9902             User->getOperand(1) == PromOps[i])
9903           return SDValue();
9904       }
9905     }
9906   }
9907 
9908   // Replace all inputs with the extension operand.
9909   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9910     // Constants may have users outside the cluster of to-be-promoted nodes,
9911     // and so we need to replace those as we do the promotions.
9912     if (isa<ConstantSDNode>(Inputs[i]))
9913       continue;
9914     else
9915       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9916   }
9917 
9918   std::list<HandleSDNode> PromOpHandles;
9919   for (auto &PromOp : PromOps)
9920     PromOpHandles.emplace_back(PromOp);
9921 
9922   // Replace all operations (these are all the same, but have a different
9923   // (i1) return type). DAG.getNode will validate that the types of
9924   // a binary operator match, so go through the list in reverse so that
9925   // we've likely promoted both operands first. Any intermediate truncations or
9926   // extensions disappear.
9927   while (!PromOpHandles.empty()) {
9928     SDValue PromOp = PromOpHandles.back().getValue();
9929     PromOpHandles.pop_back();
9930 
9931     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9932         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9933         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9934         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9935       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9936           PromOp.getOperand(0).getValueType() != MVT::i1) {
9937         // The operand is not yet ready (see comment below).
9938         PromOpHandles.emplace_front(PromOp);
9939         continue;
9940       }
9941 
9942       SDValue RepValue = PromOp.getOperand(0);
9943       if (isa<ConstantSDNode>(RepValue))
9944         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9945 
9946       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9947       continue;
9948     }
9949 
9950     unsigned C;
9951     switch (PromOp.getOpcode()) {
9952     default:             C = 0; break;
9953     case ISD::SELECT:    C = 1; break;
9954     case ISD::SELECT_CC: C = 2; break;
9955     }
9956 
9957     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9958          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9959         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9960          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9961       // The to-be-promoted operands of this node have not yet been
9962       // promoted (this should be rare because we're going through the
9963       // list backward, but if one of the operands has several users in
9964       // this cluster of to-be-promoted nodes, it is possible).
9965       PromOpHandles.emplace_front(PromOp);
9966       continue;
9967     }
9968 
9969     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9970                                 PromOp.getNode()->op_end());
9971 
9972     // If there are any constant inputs, make sure they're replaced now.
9973     for (unsigned i = 0; i < 2; ++i)
9974       if (isa<ConstantSDNode>(Ops[C+i]))
9975         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9976 
9977     DAG.ReplaceAllUsesOfValueWith(PromOp,
9978       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9979   }
9980 
9981   // Now we're left with the initial truncation itself.
9982   if (N->getOpcode() == ISD::TRUNCATE)
9983     return N->getOperand(0);
9984 
9985   // Otherwise, this is a comparison. The operands to be compared have just
9986   // changed type (to i1), but everything else is the same.
9987   return SDValue(N, 0);
9988 }
9989 
9990 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9991                                                   DAGCombinerInfo &DCI) const {
9992   SelectionDAG &DAG = DCI.DAG;
9993   SDLoc dl(N);
9994 
9995   // If we're tracking CR bits, we need to be careful that we don't have:
9996   //   zext(binary-ops(trunc(x), trunc(y)))
9997   // or
9998   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9999   // such that we're unnecessarily moving things into CR bits that can more
10000   // efficiently stay in GPRs. Note that if we're not certain that the high
10001   // bits are set as required by the final extension, we still may need to do
10002   // some masking to get the proper behavior.
10003 
10004   // This same functionality is important on PPC64 when dealing with
10005   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10006   // the return values of functions. Because it is so similar, it is handled
10007   // here as well.
10008 
10009   if (N->getValueType(0) != MVT::i32 &&
10010       N->getValueType(0) != MVT::i64)
10011     return SDValue();
10012 
10013   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10014         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10015     return SDValue();
10016 
10017   if (N->getOperand(0).getOpcode() != ISD::AND &&
10018       N->getOperand(0).getOpcode() != ISD::OR  &&
10019       N->getOperand(0).getOpcode() != ISD::XOR &&
10020       N->getOperand(0).getOpcode() != ISD::SELECT &&
10021       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10022     return SDValue();
10023 
10024   SmallVector<SDValue, 4> Inputs;
10025   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10026   SmallPtrSet<SDNode *, 16> Visited;
10027 
10028   // Visit all inputs, collect all binary operations (and, or, xor and
10029   // select) that are all fed by truncations.
10030   while (!BinOps.empty()) {
10031     SDValue BinOp = BinOps.back();
10032     BinOps.pop_back();
10033 
10034     if (!Visited.insert(BinOp.getNode()).second)
10035       continue;
10036 
10037     PromOps.push_back(BinOp);
10038 
10039     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10040       // The condition of the select is not promoted.
10041       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10042         continue;
10043       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10044         continue;
10045 
10046       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10047           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10048         Inputs.push_back(BinOp.getOperand(i));
10049       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10050                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10051                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10052                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10053                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10054         BinOps.push_back(BinOp.getOperand(i));
10055       } else {
10056         // We have an input that is not a truncation or another binary
10057         // operation; we'll abort this transformation.
10058         return SDValue();
10059       }
10060     }
10061   }
10062 
10063   // The operands of a select that must be truncated when the select is
10064   // promoted because the operand is actually part of the to-be-promoted set.
10065   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10066 
10067   // Make sure that this is a self-contained cluster of operations (which
10068   // is not quite the same thing as saying that everything has only one
10069   // use).
10070   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10071     if (isa<ConstantSDNode>(Inputs[i]))
10072       continue;
10073 
10074     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10075                               UE = Inputs[i].getNode()->use_end();
10076          UI != UE; ++UI) {
10077       SDNode *User = *UI;
10078       if (User != N && !Visited.count(User))
10079         return SDValue();
10080 
10081       // If we're going to promote the non-output-value operand(s) or SELECT or
10082       // SELECT_CC, record them for truncation.
10083       if (User->getOpcode() == ISD::SELECT) {
10084         if (User->getOperand(0) == Inputs[i])
10085           SelectTruncOp[0].insert(std::make_pair(User,
10086                                     User->getOperand(0).getValueType()));
10087       } else if (User->getOpcode() == ISD::SELECT_CC) {
10088         if (User->getOperand(0) == Inputs[i])
10089           SelectTruncOp[0].insert(std::make_pair(User,
10090                                     User->getOperand(0).getValueType()));
10091         if (User->getOperand(1) == Inputs[i])
10092           SelectTruncOp[1].insert(std::make_pair(User,
10093                                     User->getOperand(1).getValueType()));
10094       }
10095     }
10096   }
10097 
10098   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10099     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10100                               UE = PromOps[i].getNode()->use_end();
10101          UI != UE; ++UI) {
10102       SDNode *User = *UI;
10103       if (User != N && !Visited.count(User))
10104         return SDValue();
10105 
10106       // If we're going to promote the non-output-value operand(s) or SELECT or
10107       // SELECT_CC, record them for truncation.
10108       if (User->getOpcode() == ISD::SELECT) {
10109         if (User->getOperand(0) == PromOps[i])
10110           SelectTruncOp[0].insert(std::make_pair(User,
10111                                     User->getOperand(0).getValueType()));
10112       } else if (User->getOpcode() == ISD::SELECT_CC) {
10113         if (User->getOperand(0) == PromOps[i])
10114           SelectTruncOp[0].insert(std::make_pair(User,
10115                                     User->getOperand(0).getValueType()));
10116         if (User->getOperand(1) == PromOps[i])
10117           SelectTruncOp[1].insert(std::make_pair(User,
10118                                     User->getOperand(1).getValueType()));
10119       }
10120     }
10121   }
10122 
10123   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10124   bool ReallyNeedsExt = false;
10125   if (N->getOpcode() != ISD::ANY_EXTEND) {
10126     // If all of the inputs are not already sign/zero extended, then
10127     // we'll still need to do that at the end.
10128     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10129       if (isa<ConstantSDNode>(Inputs[i]))
10130         continue;
10131 
10132       unsigned OpBits =
10133         Inputs[i].getOperand(0).getValueSizeInBits();
10134       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10135 
10136       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10137            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10138                                   APInt::getHighBitsSet(OpBits,
10139                                                         OpBits-PromBits))) ||
10140           (N->getOpcode() == ISD::SIGN_EXTEND &&
10141            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10142              (OpBits-(PromBits-1)))) {
10143         ReallyNeedsExt = true;
10144         break;
10145       }
10146     }
10147   }
10148 
10149   // Replace all inputs, either with the truncation operand, or a
10150   // truncation or extension to the final output type.
10151   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10152     // Constant inputs need to be replaced with the to-be-promoted nodes that
10153     // use them because they might have users outside of the cluster of
10154     // promoted nodes.
10155     if (isa<ConstantSDNode>(Inputs[i]))
10156       continue;
10157 
10158     SDValue InSrc = Inputs[i].getOperand(0);
10159     if (Inputs[i].getValueType() == N->getValueType(0))
10160       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10161     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10162       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10163         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10164     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10165       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10166         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10167     else
10168       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10169         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10170   }
10171 
10172   std::list<HandleSDNode> PromOpHandles;
10173   for (auto &PromOp : PromOps)
10174     PromOpHandles.emplace_back(PromOp);
10175 
10176   // Replace all operations (these are all the same, but have a different
10177   // (promoted) return type). DAG.getNode will validate that the types of
10178   // a binary operator match, so go through the list in reverse so that
10179   // we've likely promoted both operands first.
10180   while (!PromOpHandles.empty()) {
10181     SDValue PromOp = PromOpHandles.back().getValue();
10182     PromOpHandles.pop_back();
10183 
10184     unsigned C;
10185     switch (PromOp.getOpcode()) {
10186     default:             C = 0; break;
10187     case ISD::SELECT:    C = 1; break;
10188     case ISD::SELECT_CC: C = 2; break;
10189     }
10190 
10191     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10192          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10193         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10194          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10195       // The to-be-promoted operands of this node have not yet been
10196       // promoted (this should be rare because we're going through the
10197       // list backward, but if one of the operands has several users in
10198       // this cluster of to-be-promoted nodes, it is possible).
10199       PromOpHandles.emplace_front(PromOp);
10200       continue;
10201     }
10202 
10203     // For SELECT and SELECT_CC nodes, we do a similar check for any
10204     // to-be-promoted comparison inputs.
10205     if (PromOp.getOpcode() == ISD::SELECT ||
10206         PromOp.getOpcode() == ISD::SELECT_CC) {
10207       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10208            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10209           (SelectTruncOp[1].count(PromOp.getNode()) &&
10210            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10211         PromOpHandles.emplace_front(PromOp);
10212         continue;
10213       }
10214     }
10215 
10216     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10217                                 PromOp.getNode()->op_end());
10218 
10219     // If this node has constant inputs, then they'll need to be promoted here.
10220     for (unsigned i = 0; i < 2; ++i) {
10221       if (!isa<ConstantSDNode>(Ops[C+i]))
10222         continue;
10223       if (Ops[C+i].getValueType() == N->getValueType(0))
10224         continue;
10225 
10226       if (N->getOpcode() == ISD::SIGN_EXTEND)
10227         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10228       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10229         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10230       else
10231         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10232     }
10233 
10234     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10235     // truncate them again to the original value type.
10236     if (PromOp.getOpcode() == ISD::SELECT ||
10237         PromOp.getOpcode() == ISD::SELECT_CC) {
10238       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10239       if (SI0 != SelectTruncOp[0].end())
10240         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10241       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10242       if (SI1 != SelectTruncOp[1].end())
10243         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10244     }
10245 
10246     DAG.ReplaceAllUsesOfValueWith(PromOp,
10247       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10248   }
10249 
10250   // Now we're left with the initial extension itself.
10251   if (!ReallyNeedsExt)
10252     return N->getOperand(0);
10253 
10254   // To zero extend, just mask off everything except for the first bit (in the
10255   // i1 case).
10256   if (N->getOpcode() == ISD::ZERO_EXTEND)
10257     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10258                        DAG.getConstant(APInt::getLowBitsSet(
10259                                          N->getValueSizeInBits(0), PromBits),
10260                                        dl, N->getValueType(0)));
10261 
10262   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10263          "Invalid extension type");
10264   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10265   SDValue ShiftCst =
10266       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10267   return DAG.getNode(
10268       ISD::SRA, dl, N->getValueType(0),
10269       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10270       ShiftCst);
10271 }
10272 
10273 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10274                                               DAGCombinerInfo &DCI) const {
10275   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10276           N->getOpcode() == ISD::UINT_TO_FP) &&
10277          "Need an int -> FP conversion node here");
10278 
10279   if (!Subtarget.has64BitSupport())
10280     return SDValue();
10281 
10282   SelectionDAG &DAG = DCI.DAG;
10283   SDLoc dl(N);
10284   SDValue Op(N, 0);
10285 
10286   // Don't handle ppc_fp128 here or i1 conversions.
10287   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10288     return SDValue();
10289   if (Op.getOperand(0).getValueType() == MVT::i1)
10290     return SDValue();
10291 
10292   // For i32 intermediate values, unfortunately, the conversion functions
10293   // leave the upper 32 bits of the value are undefined. Within the set of
10294   // scalar instructions, we have no method for zero- or sign-extending the
10295   // value. Thus, we cannot handle i32 intermediate values here.
10296   if (Op.getOperand(0).getValueType() == MVT::i32)
10297     return SDValue();
10298 
10299   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10300          "UINT_TO_FP is supported only with FPCVT");
10301 
10302   // If we have FCFIDS, then use it when converting to single-precision.
10303   // Otherwise, convert to double-precision and then round.
10304   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10305                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10306                                                             : PPCISD::FCFIDS)
10307                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10308                                                             : PPCISD::FCFID);
10309   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10310                   ? MVT::f32
10311                   : MVT::f64;
10312 
10313   // If we're converting from a float, to an int, and back to a float again,
10314   // then we don't need the store/load pair at all.
10315   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10316        Subtarget.hasFPCVT()) ||
10317       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10318     SDValue Src = Op.getOperand(0).getOperand(0);
10319     if (Src.getValueType() == MVT::f32) {
10320       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10321       DCI.AddToWorklist(Src.getNode());
10322     } else if (Src.getValueType() != MVT::f64) {
10323       // Make sure that we don't pick up a ppc_fp128 source value.
10324       return SDValue();
10325     }
10326 
10327     unsigned FCTOp =
10328       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10329                                                         PPCISD::FCTIDUZ;
10330 
10331     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10332     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10333 
10334     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10335       FP = DAG.getNode(ISD::FP_ROUND, dl,
10336                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10337       DCI.AddToWorklist(FP.getNode());
10338     }
10339 
10340     return FP;
10341   }
10342 
10343   return SDValue();
10344 }
10345 
10346 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10347 // builtins) into loads with swaps.
10348 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10349                                               DAGCombinerInfo &DCI) const {
10350   SelectionDAG &DAG = DCI.DAG;
10351   SDLoc dl(N);
10352   SDValue Chain;
10353   SDValue Base;
10354   MachineMemOperand *MMO;
10355 
10356   switch (N->getOpcode()) {
10357   default:
10358     llvm_unreachable("Unexpected opcode for little endian VSX load");
10359   case ISD::LOAD: {
10360     LoadSDNode *LD = cast<LoadSDNode>(N);
10361     Chain = LD->getChain();
10362     Base = LD->getBasePtr();
10363     MMO = LD->getMemOperand();
10364     // If the MMO suggests this isn't a load of a full vector, leave
10365     // things alone.  For a built-in, we have to make the change for
10366     // correctness, so if there is a size problem that will be a bug.
10367     if (MMO->getSize() < 16)
10368       return SDValue();
10369     break;
10370   }
10371   case ISD::INTRINSIC_W_CHAIN: {
10372     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10373     Chain = Intrin->getChain();
10374     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10375     // us what we want. Get operand 2 instead.
10376     Base = Intrin->getOperand(2);
10377     MMO = Intrin->getMemOperand();
10378     break;
10379   }
10380   }
10381 
10382   MVT VecTy = N->getValueType(0).getSimpleVT();
10383   SDValue LoadOps[] = { Chain, Base };
10384   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10385                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10386                                          LoadOps, MVT::v2f64, MMO);
10387 
10388   DCI.AddToWorklist(Load.getNode());
10389   Chain = Load.getValue(1);
10390   SDValue Swap = DAG.getNode(
10391       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10392   DCI.AddToWorklist(Swap.getNode());
10393 
10394   // Add a bitcast if the resulting load type doesn't match v2f64.
10395   if (VecTy != MVT::v2f64) {
10396     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10397     DCI.AddToWorklist(N.getNode());
10398     // Package {bitcast value, swap's chain} to match Load's shape.
10399     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10400                        N, Swap.getValue(1));
10401   }
10402 
10403   return Swap;
10404 }
10405 
10406 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10407 // builtins) into stores with swaps.
10408 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10409                                                DAGCombinerInfo &DCI) const {
10410   SelectionDAG &DAG = DCI.DAG;
10411   SDLoc dl(N);
10412   SDValue Chain;
10413   SDValue Base;
10414   unsigned SrcOpnd;
10415   MachineMemOperand *MMO;
10416 
10417   switch (N->getOpcode()) {
10418   default:
10419     llvm_unreachable("Unexpected opcode for little endian VSX store");
10420   case ISD::STORE: {
10421     StoreSDNode *ST = cast<StoreSDNode>(N);
10422     Chain = ST->getChain();
10423     Base = ST->getBasePtr();
10424     MMO = ST->getMemOperand();
10425     SrcOpnd = 1;
10426     // If the MMO suggests this isn't a store of a full vector, leave
10427     // things alone.  For a built-in, we have to make the change for
10428     // correctness, so if there is a size problem that will be a bug.
10429     if (MMO->getSize() < 16)
10430       return SDValue();
10431     break;
10432   }
10433   case ISD::INTRINSIC_VOID: {
10434     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10435     Chain = Intrin->getChain();
10436     // Intrin->getBasePtr() oddly does not get what we want.
10437     Base = Intrin->getOperand(3);
10438     MMO = Intrin->getMemOperand();
10439     SrcOpnd = 2;
10440     break;
10441   }
10442   }
10443 
10444   SDValue Src = N->getOperand(SrcOpnd);
10445   MVT VecTy = Src.getValueType().getSimpleVT();
10446 
10447   // All stores are done as v2f64 and possible bit cast.
10448   if (VecTy != MVT::v2f64) {
10449     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10450     DCI.AddToWorklist(Src.getNode());
10451   }
10452 
10453   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10454                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10455   DCI.AddToWorklist(Swap.getNode());
10456   Chain = Swap.getValue(1);
10457   SDValue StoreOps[] = { Chain, Swap, Base };
10458   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10459                                           DAG.getVTList(MVT::Other),
10460                                           StoreOps, VecTy, MMO);
10461   DCI.AddToWorklist(Store.getNode());
10462   return Store;
10463 }
10464 
10465 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10466                                              DAGCombinerInfo &DCI) const {
10467   SelectionDAG &DAG = DCI.DAG;
10468   SDLoc dl(N);
10469   switch (N->getOpcode()) {
10470   default: break;
10471   case PPCISD::SHL:
10472     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10473         return N->getOperand(0);
10474     break;
10475   case PPCISD::SRL:
10476     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10477         return N->getOperand(0);
10478     break;
10479   case PPCISD::SRA:
10480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10481       if (C->isNullValue() ||   //  0 >>s V -> 0.
10482           C->isAllOnesValue())    // -1 >>s V -> -1.
10483         return N->getOperand(0);
10484     }
10485     break;
10486   case ISD::SIGN_EXTEND:
10487   case ISD::ZERO_EXTEND:
10488   case ISD::ANY_EXTEND:
10489     return DAGCombineExtBoolTrunc(N, DCI);
10490   case ISD::TRUNCATE:
10491   case ISD::SETCC:
10492   case ISD::SELECT_CC:
10493     return DAGCombineTruncBoolExt(N, DCI);
10494   case ISD::SINT_TO_FP:
10495   case ISD::UINT_TO_FP:
10496     return combineFPToIntToFP(N, DCI);
10497   case ISD::STORE: {
10498     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10499     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10500         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10501         N->getOperand(1).getValueType() == MVT::i32 &&
10502         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10503       SDValue Val = N->getOperand(1).getOperand(0);
10504       if (Val.getValueType() == MVT::f32) {
10505         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10506         DCI.AddToWorklist(Val.getNode());
10507       }
10508       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10509       DCI.AddToWorklist(Val.getNode());
10510 
10511       SDValue Ops[] = {
10512         N->getOperand(0), Val, N->getOperand(2),
10513         DAG.getValueType(N->getOperand(1).getValueType())
10514       };
10515 
10516       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10517               DAG.getVTList(MVT::Other), Ops,
10518               cast<StoreSDNode>(N)->getMemoryVT(),
10519               cast<StoreSDNode>(N)->getMemOperand());
10520       DCI.AddToWorklist(Val.getNode());
10521       return Val;
10522     }
10523 
10524     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10525     if (cast<StoreSDNode>(N)->isUnindexed() &&
10526         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10527         N->getOperand(1).getNode()->hasOneUse() &&
10528         (N->getOperand(1).getValueType() == MVT::i32 ||
10529          N->getOperand(1).getValueType() == MVT::i16 ||
10530          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10531           N->getOperand(1).getValueType() == MVT::i64))) {
10532       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10533       // Do an any-extend to 32-bits if this is a half-word input.
10534       if (BSwapOp.getValueType() == MVT::i16)
10535         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10536 
10537       SDValue Ops[] = {
10538         N->getOperand(0), BSwapOp, N->getOperand(2),
10539         DAG.getValueType(N->getOperand(1).getValueType())
10540       };
10541       return
10542         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10543                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10544                                 cast<StoreSDNode>(N)->getMemOperand());
10545     }
10546 
10547     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10548     EVT VT = N->getOperand(1).getValueType();
10549     if (VT.isSimple()) {
10550       MVT StoreVT = VT.getSimpleVT();
10551       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10552           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10553            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10554         return expandVSXStoreForLE(N, DCI);
10555     }
10556     break;
10557   }
10558   case ISD::LOAD: {
10559     LoadSDNode *LD = cast<LoadSDNode>(N);
10560     EVT VT = LD->getValueType(0);
10561 
10562     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10563     if (VT.isSimple()) {
10564       MVT LoadVT = VT.getSimpleVT();
10565       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10566           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10567            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10568         return expandVSXLoadForLE(N, DCI);
10569     }
10570 
10571     // We sometimes end up with a 64-bit integer load, from which we extract
10572     // two single-precision floating-point numbers. This happens with
10573     // std::complex<float>, and other similar structures, because of the way we
10574     // canonicalize structure copies. However, if we lack direct moves,
10575     // then the final bitcasts from the extracted integer values to the
10576     // floating-point numbers turn into store/load pairs. Even with direct moves,
10577     // just loading the two floating-point numbers is likely better.
10578     auto ReplaceTwoFloatLoad = [&]() {
10579       if (VT != MVT::i64)
10580         return false;
10581 
10582       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10583           LD->isVolatile())
10584         return false;
10585 
10586       //  We're looking for a sequence like this:
10587       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10588       //      t16: i64 = srl t13, Constant:i32<32>
10589       //    t17: i32 = truncate t16
10590       //  t18: f32 = bitcast t17
10591       //    t19: i32 = truncate t13
10592       //  t20: f32 = bitcast t19
10593 
10594       if (!LD->hasNUsesOfValue(2, 0))
10595         return false;
10596 
10597       auto UI = LD->use_begin();
10598       while (UI.getUse().getResNo() != 0) ++UI;
10599       SDNode *Trunc = *UI++;
10600       while (UI.getUse().getResNo() != 0) ++UI;
10601       SDNode *RightShift = *UI;
10602       if (Trunc->getOpcode() != ISD::TRUNCATE)
10603         std::swap(Trunc, RightShift);
10604 
10605       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10606           Trunc->getValueType(0) != MVT::i32 ||
10607           !Trunc->hasOneUse())
10608         return false;
10609       if (RightShift->getOpcode() != ISD::SRL ||
10610           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10611           RightShift->getConstantOperandVal(1) != 32 ||
10612           !RightShift->hasOneUse())
10613         return false;
10614 
10615       SDNode *Trunc2 = *RightShift->use_begin();
10616       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10617           Trunc2->getValueType(0) != MVT::i32 ||
10618           !Trunc2->hasOneUse())
10619         return false;
10620 
10621       SDNode *Bitcast = *Trunc->use_begin();
10622       SDNode *Bitcast2 = *Trunc2->use_begin();
10623 
10624       if (Bitcast->getOpcode() != ISD::BITCAST ||
10625           Bitcast->getValueType(0) != MVT::f32)
10626         return false;
10627       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10628           Bitcast2->getValueType(0) != MVT::f32)
10629         return false;
10630 
10631       if (Subtarget.isLittleEndian())
10632         std::swap(Bitcast, Bitcast2);
10633 
10634       // Bitcast has the second float (in memory-layout order) and Bitcast2
10635       // has the first one.
10636 
10637       SDValue BasePtr = LD->getBasePtr();
10638       if (LD->isIndexed()) {
10639         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10640                "Non-pre-inc AM on PPC?");
10641         BasePtr =
10642           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10643                       LD->getOffset());
10644       }
10645 
10646       SDValue FloatLoad =
10647         DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10648                     LD->getPointerInfo(), false, LD->isNonTemporal(),
10649                     LD->isInvariant(), LD->getAlignment(), LD->getAAInfo());
10650       SDValue AddPtr =
10651         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10652                     BasePtr, DAG.getIntPtrConstant(4, dl));
10653       SDValue FloatLoad2 =
10654         DAG.getLoad(MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10655                     LD->getPointerInfo().getWithOffset(4), false,
10656                     LD->isNonTemporal(), LD->isInvariant(),
10657                     MinAlign(LD->getAlignment(), 4), LD->getAAInfo());
10658 
10659       if (LD->isIndexed()) {
10660 	// Note that DAGCombine should re-form any pre-increment load(s) from
10661 	// what is produced here if that makes sense.
10662         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10663       }
10664 
10665       DCI.CombineTo(Bitcast2, FloatLoad);
10666       DCI.CombineTo(Bitcast, FloatLoad2);
10667 
10668       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10669                                     SDValue(FloatLoad2.getNode(), 1));
10670       return true;
10671     };
10672 
10673     if (ReplaceTwoFloatLoad())
10674       return SDValue(N, 0);
10675 
10676     EVT MemVT = LD->getMemoryVT();
10677     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10678     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10679     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10680     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10681     if (LD->isUnindexed() && VT.isVector() &&
10682         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10683           // P8 and later hardware should just use LOAD.
10684           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10685                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10686          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10687           LD->getAlignment() >= ScalarABIAlignment)) &&
10688         LD->getAlignment() < ABIAlignment) {
10689       // This is a type-legal unaligned Altivec or QPX load.
10690       SDValue Chain = LD->getChain();
10691       SDValue Ptr = LD->getBasePtr();
10692       bool isLittleEndian = Subtarget.isLittleEndian();
10693 
10694       // This implements the loading of unaligned vectors as described in
10695       // the venerable Apple Velocity Engine overview. Specifically:
10696       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10697       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10698       //
10699       // The general idea is to expand a sequence of one or more unaligned
10700       // loads into an alignment-based permutation-control instruction (lvsl
10701       // or lvsr), a series of regular vector loads (which always truncate
10702       // their input address to an aligned address), and a series of
10703       // permutations.  The results of these permutations are the requested
10704       // loaded values.  The trick is that the last "extra" load is not taken
10705       // from the address you might suspect (sizeof(vector) bytes after the
10706       // last requested load), but rather sizeof(vector) - 1 bytes after the
10707       // last requested vector. The point of this is to avoid a page fault if
10708       // the base address happened to be aligned. This works because if the
10709       // base address is aligned, then adding less than a full vector length
10710       // will cause the last vector in the sequence to be (re)loaded.
10711       // Otherwise, the next vector will be fetched as you might suspect was
10712       // necessary.
10713 
10714       // We might be able to reuse the permutation generation from
10715       // a different base address offset from this one by an aligned amount.
10716       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10717       // optimization later.
10718       Intrinsic::ID Intr, IntrLD, IntrPerm;
10719       MVT PermCntlTy, PermTy, LDTy;
10720       if (Subtarget.hasAltivec()) {
10721         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10722                                  Intrinsic::ppc_altivec_lvsl;
10723         IntrLD = Intrinsic::ppc_altivec_lvx;
10724         IntrPerm = Intrinsic::ppc_altivec_vperm;
10725         PermCntlTy = MVT::v16i8;
10726         PermTy = MVT::v4i32;
10727         LDTy = MVT::v4i32;
10728       } else {
10729         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10730                                        Intrinsic::ppc_qpx_qvlpcls;
10731         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10732                                        Intrinsic::ppc_qpx_qvlfs;
10733         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10734         PermCntlTy = MVT::v4f64;
10735         PermTy = MVT::v4f64;
10736         LDTy = MemVT.getSimpleVT();
10737       }
10738 
10739       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10740 
10741       // Create the new MMO for the new base load. It is like the original MMO,
10742       // but represents an area in memory almost twice the vector size centered
10743       // on the original address. If the address is unaligned, we might start
10744       // reading up to (sizeof(vector)-1) bytes below the address of the
10745       // original unaligned load.
10746       MachineFunction &MF = DAG.getMachineFunction();
10747       MachineMemOperand *BaseMMO =
10748         MF.getMachineMemOperand(LD->getMemOperand(),
10749                                 -(long)MemVT.getStoreSize()+1,
10750                                 2*MemVT.getStoreSize()-1);
10751 
10752       // Create the new base load.
10753       SDValue LDXIntID =
10754           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10755       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10756       SDValue BaseLoad =
10757         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10758                                 DAG.getVTList(PermTy, MVT::Other),
10759                                 BaseLoadOps, LDTy, BaseMMO);
10760 
10761       // Note that the value of IncOffset (which is provided to the next
10762       // load's pointer info offset value, and thus used to calculate the
10763       // alignment), and the value of IncValue (which is actually used to
10764       // increment the pointer value) are different! This is because we
10765       // require the next load to appear to be aligned, even though it
10766       // is actually offset from the base pointer by a lesser amount.
10767       int IncOffset = VT.getSizeInBits() / 8;
10768       int IncValue = IncOffset;
10769 
10770       // Walk (both up and down) the chain looking for another load at the real
10771       // (aligned) offset (the alignment of the other load does not matter in
10772       // this case). If found, then do not use the offset reduction trick, as
10773       // that will prevent the loads from being later combined (as they would
10774       // otherwise be duplicates).
10775       if (!findConsecutiveLoad(LD, DAG))
10776         --IncValue;
10777 
10778       SDValue Increment =
10779           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10780       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10781 
10782       MachineMemOperand *ExtraMMO =
10783         MF.getMachineMemOperand(LD->getMemOperand(),
10784                                 1, 2*MemVT.getStoreSize()-1);
10785       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10786       SDValue ExtraLoad =
10787         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10788                                 DAG.getVTList(PermTy, MVT::Other),
10789                                 ExtraLoadOps, LDTy, ExtraMMO);
10790 
10791       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10792         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10793 
10794       // Because vperm has a big-endian bias, we must reverse the order
10795       // of the input vectors and complement the permute control vector
10796       // when generating little endian code.  We have already handled the
10797       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10798       // and ExtraLoad here.
10799       SDValue Perm;
10800       if (isLittleEndian)
10801         Perm = BuildIntrinsicOp(IntrPerm,
10802                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10803       else
10804         Perm = BuildIntrinsicOp(IntrPerm,
10805                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10806 
10807       if (VT != PermTy)
10808         Perm = Subtarget.hasAltivec() ?
10809                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10810                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10811                                DAG.getTargetConstant(1, dl, MVT::i64));
10812                                // second argument is 1 because this rounding
10813                                // is always exact.
10814 
10815       // The output of the permutation is our loaded result, the TokenFactor is
10816       // our new chain.
10817       DCI.CombineTo(N, Perm, TF);
10818       return SDValue(N, 0);
10819     }
10820     }
10821     break;
10822     case ISD::INTRINSIC_WO_CHAIN: {
10823       bool isLittleEndian = Subtarget.isLittleEndian();
10824       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10825       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10826                                            : Intrinsic::ppc_altivec_lvsl);
10827       if ((IID == Intr ||
10828            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10829            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10830         N->getOperand(1)->getOpcode() == ISD::ADD) {
10831         SDValue Add = N->getOperand(1);
10832 
10833         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10834                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10835 
10836         if (DAG.MaskedValueIsZero(
10837                 Add->getOperand(1),
10838                 APInt::getAllOnesValue(Bits /* alignment */)
10839                     .zext(
10840                         Add.getValueType().getScalarType().getSizeInBits()))) {
10841           SDNode *BasePtr = Add->getOperand(0).getNode();
10842           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10843                                     UE = BasePtr->use_end();
10844                UI != UE; ++UI) {
10845             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10846                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10847               // We've found another LVSL/LVSR, and this address is an aligned
10848               // multiple of that one. The results will be the same, so use the
10849               // one we've just found instead.
10850 
10851               return SDValue(*UI, 0);
10852             }
10853           }
10854         }
10855 
10856         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10857           SDNode *BasePtr = Add->getOperand(0).getNode();
10858           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10859                UE = BasePtr->use_end(); UI != UE; ++UI) {
10860             if (UI->getOpcode() == ISD::ADD &&
10861                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10862                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10863                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10864                 (1ULL << Bits) == 0) {
10865               SDNode *OtherAdd = *UI;
10866               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10867                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10868                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10869                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10870                   return SDValue(*VI, 0);
10871                 }
10872               }
10873             }
10874           }
10875         }
10876       }
10877     }
10878 
10879     break;
10880   case ISD::INTRINSIC_W_CHAIN: {
10881     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10882     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10883       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10884       default:
10885         break;
10886       case Intrinsic::ppc_vsx_lxvw4x:
10887       case Intrinsic::ppc_vsx_lxvd2x:
10888         return expandVSXLoadForLE(N, DCI);
10889       }
10890     }
10891     break;
10892   }
10893   case ISD::INTRINSIC_VOID: {
10894     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10895     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10896       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10897       default:
10898         break;
10899       case Intrinsic::ppc_vsx_stxvw4x:
10900       case Intrinsic::ppc_vsx_stxvd2x:
10901         return expandVSXStoreForLE(N, DCI);
10902       }
10903     }
10904     break;
10905   }
10906   case ISD::BSWAP:
10907     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10908     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10909         N->getOperand(0).hasOneUse() &&
10910         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10911          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10912           N->getValueType(0) == MVT::i64))) {
10913       SDValue Load = N->getOperand(0);
10914       LoadSDNode *LD = cast<LoadSDNode>(Load);
10915       // Create the byte-swapping load.
10916       SDValue Ops[] = {
10917         LD->getChain(),    // Chain
10918         LD->getBasePtr(),  // Ptr
10919         DAG.getValueType(N->getValueType(0)) // VT
10920       };
10921       SDValue BSLoad =
10922         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10923                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10924                                               MVT::i64 : MVT::i32, MVT::Other),
10925                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10926 
10927       // If this is an i16 load, insert the truncate.
10928       SDValue ResVal = BSLoad;
10929       if (N->getValueType(0) == MVT::i16)
10930         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10931 
10932       // First, combine the bswap away.  This makes the value produced by the
10933       // load dead.
10934       DCI.CombineTo(N, ResVal);
10935 
10936       // Next, combine the load away, we give it a bogus result value but a real
10937       // chain result.  The result value is dead because the bswap is dead.
10938       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10939 
10940       // Return N so it doesn't get rechecked!
10941       return SDValue(N, 0);
10942     }
10943 
10944     break;
10945   case PPCISD::VCMP: {
10946     // If a VCMPo node already exists with exactly the same operands as this
10947     // node, use its result instead of this node (VCMPo computes both a CR6 and
10948     // a normal output).
10949     //
10950     if (!N->getOperand(0).hasOneUse() &&
10951         !N->getOperand(1).hasOneUse() &&
10952         !N->getOperand(2).hasOneUse()) {
10953 
10954       // Scan all of the users of the LHS, looking for VCMPo's that match.
10955       SDNode *VCMPoNode = nullptr;
10956 
10957       SDNode *LHSN = N->getOperand(0).getNode();
10958       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10959            UI != E; ++UI)
10960         if (UI->getOpcode() == PPCISD::VCMPo &&
10961             UI->getOperand(1) == N->getOperand(1) &&
10962             UI->getOperand(2) == N->getOperand(2) &&
10963             UI->getOperand(0) == N->getOperand(0)) {
10964           VCMPoNode = *UI;
10965           break;
10966         }
10967 
10968       // If there is no VCMPo node, or if the flag value has a single use, don't
10969       // transform this.
10970       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10971         break;
10972 
10973       // Look at the (necessarily single) use of the flag value.  If it has a
10974       // chain, this transformation is more complex.  Note that multiple things
10975       // could use the value result, which we should ignore.
10976       SDNode *FlagUser = nullptr;
10977       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10978            FlagUser == nullptr; ++UI) {
10979         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10980         SDNode *User = *UI;
10981         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10982           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10983             FlagUser = User;
10984             break;
10985           }
10986         }
10987       }
10988 
10989       // If the user is a MFOCRF instruction, we know this is safe.
10990       // Otherwise we give up for right now.
10991       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10992         return SDValue(VCMPoNode, 0);
10993     }
10994     break;
10995   }
10996   case ISD::BRCOND: {
10997     SDValue Cond = N->getOperand(1);
10998     SDValue Target = N->getOperand(2);
10999 
11000     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11001         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11002           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11003 
11004       // We now need to make the intrinsic dead (it cannot be instruction
11005       // selected).
11006       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11007       assert(Cond.getNode()->hasOneUse() &&
11008              "Counter decrement has more than one use");
11009 
11010       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11011                          N->getOperand(0), Target);
11012     }
11013   }
11014   break;
11015   case ISD::BR_CC: {
11016     // If this is a branch on an altivec predicate comparison, lower this so
11017     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11018     // lowering is done pre-legalize, because the legalizer lowers the predicate
11019     // compare down to code that is difficult to reassemble.
11020     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11021     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11022 
11023     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11024     // value. If so, pass-through the AND to get to the intrinsic.
11025     if (LHS.getOpcode() == ISD::AND &&
11026         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11027         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11028           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11029         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11030         !isNullConstant(LHS.getOperand(1)))
11031       LHS = LHS.getOperand(0);
11032 
11033     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11034         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11035           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11036         isa<ConstantSDNode>(RHS)) {
11037       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11038              "Counter decrement comparison is not EQ or NE");
11039 
11040       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11041       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11042                     (CC == ISD::SETNE && !Val);
11043 
11044       // We now need to make the intrinsic dead (it cannot be instruction
11045       // selected).
11046       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11047       assert(LHS.getNode()->hasOneUse() &&
11048              "Counter decrement has more than one use");
11049 
11050       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11051                          N->getOperand(0), N->getOperand(4));
11052     }
11053 
11054     int CompareOpc;
11055     bool isDot;
11056 
11057     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11058         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11059         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11060       assert(isDot && "Can't compare against a vector result!");
11061 
11062       // If this is a comparison against something other than 0/1, then we know
11063       // that the condition is never/always true.
11064       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11065       if (Val != 0 && Val != 1) {
11066         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11067           return N->getOperand(0);
11068         // Always !=, turn it into an unconditional branch.
11069         return DAG.getNode(ISD::BR, dl, MVT::Other,
11070                            N->getOperand(0), N->getOperand(4));
11071       }
11072 
11073       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11074 
11075       // Create the PPCISD altivec 'dot' comparison node.
11076       SDValue Ops[] = {
11077         LHS.getOperand(2),  // LHS of compare
11078         LHS.getOperand(3),  // RHS of compare
11079         DAG.getConstant(CompareOpc, dl, MVT::i32)
11080       };
11081       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11082       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11083 
11084       // Unpack the result based on how the target uses it.
11085       PPC::Predicate CompOpc;
11086       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11087       default:  // Can't happen, don't crash on invalid number though.
11088       case 0:   // Branch on the value of the EQ bit of CR6.
11089         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11090         break;
11091       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11092         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11093         break;
11094       case 2:   // Branch on the value of the LT bit of CR6.
11095         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11096         break;
11097       case 3:   // Branch on the inverted value of the LT bit of CR6.
11098         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11099         break;
11100       }
11101 
11102       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11103                          DAG.getConstant(CompOpc, dl, MVT::i32),
11104                          DAG.getRegister(PPC::CR6, MVT::i32),
11105                          N->getOperand(4), CompNode.getValue(1));
11106     }
11107     break;
11108   }
11109   }
11110 
11111   return SDValue();
11112 }
11113 
11114 SDValue
11115 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11116                                   SelectionDAG &DAG,
11117                                   std::vector<SDNode *> *Created) const {
11118   // fold (sdiv X, pow2)
11119   EVT VT = N->getValueType(0);
11120   if (VT == MVT::i64 && !Subtarget.isPPC64())
11121     return SDValue();
11122   if ((VT != MVT::i32 && VT != MVT::i64) ||
11123       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11124     return SDValue();
11125 
11126   SDLoc DL(N);
11127   SDValue N0 = N->getOperand(0);
11128 
11129   bool IsNegPow2 = (-Divisor).isPowerOf2();
11130   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11131   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11132 
11133   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11134   if (Created)
11135     Created->push_back(Op.getNode());
11136 
11137   if (IsNegPow2) {
11138     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11139     if (Created)
11140       Created->push_back(Op.getNode());
11141   }
11142 
11143   return Op;
11144 }
11145 
11146 //===----------------------------------------------------------------------===//
11147 // Inline Assembly Support
11148 //===----------------------------------------------------------------------===//
11149 
11150 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11151                                                       APInt &KnownZero,
11152                                                       APInt &KnownOne,
11153                                                       const SelectionDAG &DAG,
11154                                                       unsigned Depth) const {
11155   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11156   switch (Op.getOpcode()) {
11157   default: break;
11158   case PPCISD::LBRX: {
11159     // lhbrx is known to have the top bits cleared out.
11160     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11161       KnownZero = 0xFFFF0000;
11162     break;
11163   }
11164   case ISD::INTRINSIC_WO_CHAIN: {
11165     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11166     default: break;
11167     case Intrinsic::ppc_altivec_vcmpbfp_p:
11168     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11169     case Intrinsic::ppc_altivec_vcmpequb_p:
11170     case Intrinsic::ppc_altivec_vcmpequh_p:
11171     case Intrinsic::ppc_altivec_vcmpequw_p:
11172     case Intrinsic::ppc_altivec_vcmpequd_p:
11173     case Intrinsic::ppc_altivec_vcmpgefp_p:
11174     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11175     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11176     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11177     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11178     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11179     case Intrinsic::ppc_altivec_vcmpgtub_p:
11180     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11181     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11182     case Intrinsic::ppc_altivec_vcmpgtud_p:
11183       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11184       break;
11185     }
11186   }
11187   }
11188 }
11189 
11190 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11191   switch (Subtarget.getDarwinDirective()) {
11192   default: break;
11193   case PPC::DIR_970:
11194   case PPC::DIR_PWR4:
11195   case PPC::DIR_PWR5:
11196   case PPC::DIR_PWR5X:
11197   case PPC::DIR_PWR6:
11198   case PPC::DIR_PWR6X:
11199   case PPC::DIR_PWR7:
11200   case PPC::DIR_PWR8:
11201   case PPC::DIR_PWR9: {
11202     if (!ML)
11203       break;
11204 
11205     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11206 
11207     // For small loops (between 5 and 8 instructions), align to a 32-byte
11208     // boundary so that the entire loop fits in one instruction-cache line.
11209     uint64_t LoopSize = 0;
11210     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11211       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11212         LoopSize += TII->GetInstSizeInBytes(J);
11213         if (LoopSize > 32)
11214           break;
11215       }
11216 
11217     if (LoopSize > 16 && LoopSize <= 32)
11218       return 5;
11219 
11220     break;
11221   }
11222   }
11223 
11224   return TargetLowering::getPrefLoopAlignment(ML);
11225 }
11226 
11227 /// getConstraintType - Given a constraint, return the type of
11228 /// constraint it is for this target.
11229 PPCTargetLowering::ConstraintType
11230 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11231   if (Constraint.size() == 1) {
11232     switch (Constraint[0]) {
11233     default: break;
11234     case 'b':
11235     case 'r':
11236     case 'f':
11237     case 'd':
11238     case 'v':
11239     case 'y':
11240       return C_RegisterClass;
11241     case 'Z':
11242       // FIXME: While Z does indicate a memory constraint, it specifically
11243       // indicates an r+r address (used in conjunction with the 'y' modifier
11244       // in the replacement string). Currently, we're forcing the base
11245       // register to be r0 in the asm printer (which is interpreted as zero)
11246       // and forming the complete address in the second register. This is
11247       // suboptimal.
11248       return C_Memory;
11249     }
11250   } else if (Constraint == "wc") { // individual CR bits.
11251     return C_RegisterClass;
11252   } else if (Constraint == "wa" || Constraint == "wd" ||
11253              Constraint == "wf" || Constraint == "ws") {
11254     return C_RegisterClass; // VSX registers.
11255   }
11256   return TargetLowering::getConstraintType(Constraint);
11257 }
11258 
11259 /// Examine constraint type and operand type and determine a weight value.
11260 /// This object must already have been set up with the operand type
11261 /// and the current alternative constraint selected.
11262 TargetLowering::ConstraintWeight
11263 PPCTargetLowering::getSingleConstraintMatchWeight(
11264     AsmOperandInfo &info, const char *constraint) const {
11265   ConstraintWeight weight = CW_Invalid;
11266   Value *CallOperandVal = info.CallOperandVal;
11267     // If we don't have a value, we can't do a match,
11268     // but allow it at the lowest weight.
11269   if (!CallOperandVal)
11270     return CW_Default;
11271   Type *type = CallOperandVal->getType();
11272 
11273   // Look at the constraint type.
11274   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11275     return CW_Register; // an individual CR bit.
11276   else if ((StringRef(constraint) == "wa" ||
11277             StringRef(constraint) == "wd" ||
11278             StringRef(constraint) == "wf") &&
11279            type->isVectorTy())
11280     return CW_Register;
11281   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11282     return CW_Register;
11283 
11284   switch (*constraint) {
11285   default:
11286     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11287     break;
11288   case 'b':
11289     if (type->isIntegerTy())
11290       weight = CW_Register;
11291     break;
11292   case 'f':
11293     if (type->isFloatTy())
11294       weight = CW_Register;
11295     break;
11296   case 'd':
11297     if (type->isDoubleTy())
11298       weight = CW_Register;
11299     break;
11300   case 'v':
11301     if (type->isVectorTy())
11302       weight = CW_Register;
11303     break;
11304   case 'y':
11305     weight = CW_Register;
11306     break;
11307   case 'Z':
11308     weight = CW_Memory;
11309     break;
11310   }
11311   return weight;
11312 }
11313 
11314 std::pair<unsigned, const TargetRegisterClass *>
11315 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11316                                                 StringRef Constraint,
11317                                                 MVT VT) const {
11318   if (Constraint.size() == 1) {
11319     // GCC RS6000 Constraint Letters
11320     switch (Constraint[0]) {
11321     case 'b':   // R1-R31
11322       if (VT == MVT::i64 && Subtarget.isPPC64())
11323         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11324       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11325     case 'r':   // R0-R31
11326       if (VT == MVT::i64 && Subtarget.isPPC64())
11327         return std::make_pair(0U, &PPC::G8RCRegClass);
11328       return std::make_pair(0U, &PPC::GPRCRegClass);
11329     // 'd' and 'f' constraints are both defined to be "the floating point
11330     // registers", where one is for 32-bit and the other for 64-bit. We don't
11331     // really care overly much here so just give them all the same reg classes.
11332     case 'd':
11333     case 'f':
11334       if (VT == MVT::f32 || VT == MVT::i32)
11335         return std::make_pair(0U, &PPC::F4RCRegClass);
11336       if (VT == MVT::f64 || VT == MVT::i64)
11337         return std::make_pair(0U, &PPC::F8RCRegClass);
11338       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11339         return std::make_pair(0U, &PPC::QFRCRegClass);
11340       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11341         return std::make_pair(0U, &PPC::QSRCRegClass);
11342       break;
11343     case 'v':
11344       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11345         return std::make_pair(0U, &PPC::QFRCRegClass);
11346       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11347         return std::make_pair(0U, &PPC::QSRCRegClass);
11348       if (Subtarget.hasAltivec())
11349         return std::make_pair(0U, &PPC::VRRCRegClass);
11350     case 'y':   // crrc
11351       return std::make_pair(0U, &PPC::CRRCRegClass);
11352     }
11353   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11354     // An individual CR bit.
11355     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11356   } else if ((Constraint == "wa" || Constraint == "wd" ||
11357              Constraint == "wf") && Subtarget.hasVSX()) {
11358     return std::make_pair(0U, &PPC::VSRCRegClass);
11359   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11360     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11361       return std::make_pair(0U, &PPC::VSSRCRegClass);
11362     else
11363       return std::make_pair(0U, &PPC::VSFRCRegClass);
11364   }
11365 
11366   std::pair<unsigned, const TargetRegisterClass *> R =
11367       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11368 
11369   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11370   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11371   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11372   // register.
11373   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11374   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11375   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11376       PPC::GPRCRegClass.contains(R.first))
11377     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11378                             PPC::sub_32, &PPC::G8RCRegClass),
11379                           &PPC::G8RCRegClass);
11380 
11381   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11382   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11383     R.first = PPC::CR0;
11384     R.second = &PPC::CRRCRegClass;
11385   }
11386 
11387   return R;
11388 }
11389 
11390 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11391 /// vector.  If it is invalid, don't add anything to Ops.
11392 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11393                                                      std::string &Constraint,
11394                                                      std::vector<SDValue>&Ops,
11395                                                      SelectionDAG &DAG) const {
11396   SDValue Result;
11397 
11398   // Only support length 1 constraints.
11399   if (Constraint.length() > 1) return;
11400 
11401   char Letter = Constraint[0];
11402   switch (Letter) {
11403   default: break;
11404   case 'I':
11405   case 'J':
11406   case 'K':
11407   case 'L':
11408   case 'M':
11409   case 'N':
11410   case 'O':
11411   case 'P': {
11412     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11413     if (!CST) return; // Must be an immediate to match.
11414     SDLoc dl(Op);
11415     int64_t Value = CST->getSExtValue();
11416     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11417                          // numbers are printed as such.
11418     switch (Letter) {
11419     default: llvm_unreachable("Unknown constraint letter!");
11420     case 'I':  // "I" is a signed 16-bit constant.
11421       if (isInt<16>(Value))
11422         Result = DAG.getTargetConstant(Value, dl, TCVT);
11423       break;
11424     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11425       if (isShiftedUInt<16, 16>(Value))
11426         Result = DAG.getTargetConstant(Value, dl, TCVT);
11427       break;
11428     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11429       if (isShiftedInt<16, 16>(Value))
11430         Result = DAG.getTargetConstant(Value, dl, TCVT);
11431       break;
11432     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11433       if (isUInt<16>(Value))
11434         Result = DAG.getTargetConstant(Value, dl, TCVT);
11435       break;
11436     case 'M':  // "M" is a constant that is greater than 31.
11437       if (Value > 31)
11438         Result = DAG.getTargetConstant(Value, dl, TCVT);
11439       break;
11440     case 'N':  // "N" is a positive constant that is an exact power of two.
11441       if (Value > 0 && isPowerOf2_64(Value))
11442         Result = DAG.getTargetConstant(Value, dl, TCVT);
11443       break;
11444     case 'O':  // "O" is the constant zero.
11445       if (Value == 0)
11446         Result = DAG.getTargetConstant(Value, dl, TCVT);
11447       break;
11448     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11449       if (isInt<16>(-Value))
11450         Result = DAG.getTargetConstant(Value, dl, TCVT);
11451       break;
11452     }
11453     break;
11454   }
11455   }
11456 
11457   if (Result.getNode()) {
11458     Ops.push_back(Result);
11459     return;
11460   }
11461 
11462   // Handle standard constraint letters.
11463   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11464 }
11465 
11466 // isLegalAddressingMode - Return true if the addressing mode represented
11467 // by AM is legal for this target, for a load/store of the specified type.
11468 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11469                                               const AddrMode &AM, Type *Ty,
11470                                               unsigned AS) const {
11471   // PPC does not allow r+i addressing modes for vectors!
11472   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11473     return false;
11474 
11475   // PPC allows a sign-extended 16-bit immediate field.
11476   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11477     return false;
11478 
11479   // No global is ever allowed as a base.
11480   if (AM.BaseGV)
11481     return false;
11482 
11483   // PPC only support r+r,
11484   switch (AM.Scale) {
11485   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11486     break;
11487   case 1:
11488     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11489       return false;
11490     // Otherwise we have r+r or r+i.
11491     break;
11492   case 2:
11493     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11494       return false;
11495     // Allow 2*r as r+r.
11496     break;
11497   default:
11498     // No other scales are supported.
11499     return false;
11500   }
11501 
11502   return true;
11503 }
11504 
11505 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11506                                            SelectionDAG &DAG) const {
11507   MachineFunction &MF = DAG.getMachineFunction();
11508   MachineFrameInfo *MFI = MF.getFrameInfo();
11509   MFI->setReturnAddressIsTaken(true);
11510 
11511   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11512     return SDValue();
11513 
11514   SDLoc dl(Op);
11515   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11516 
11517   // Make sure the function does not optimize away the store of the RA to
11518   // the stack.
11519   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11520   FuncInfo->setLRStoreRequired();
11521   bool isPPC64 = Subtarget.isPPC64();
11522   auto PtrVT = getPointerTy(MF.getDataLayout());
11523 
11524   if (Depth > 0) {
11525     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11526     SDValue Offset =
11527         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11528                         isPPC64 ? MVT::i64 : MVT::i32);
11529     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11530                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11531                        MachinePointerInfo(), false, false, false, 0);
11532   }
11533 
11534   // Just load the return address off the stack.
11535   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11536   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11537                      MachinePointerInfo(), false, false, false, 0);
11538 }
11539 
11540 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11541                                           SelectionDAG &DAG) const {
11542   SDLoc dl(Op);
11543   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11544 
11545   MachineFunction &MF = DAG.getMachineFunction();
11546   MachineFrameInfo *MFI = MF.getFrameInfo();
11547   MFI->setFrameAddressIsTaken(true);
11548 
11549   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11550   bool isPPC64 = PtrVT == MVT::i64;
11551 
11552   // Naked functions never have a frame pointer, and so we use r1. For all
11553   // other functions, this decision must be delayed until during PEI.
11554   unsigned FrameReg;
11555   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11556     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11557   else
11558     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11559 
11560   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11561                                          PtrVT);
11562   while (Depth--)
11563     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11564                             FrameAddr, MachinePointerInfo(), false, false,
11565                             false, 0);
11566   return FrameAddr;
11567 }
11568 
11569 // FIXME? Maybe this could be a TableGen attribute on some registers and
11570 // this table could be generated automatically from RegInfo.
11571 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11572                                               SelectionDAG &DAG) const {
11573   bool isPPC64 = Subtarget.isPPC64();
11574   bool isDarwinABI = Subtarget.isDarwinABI();
11575 
11576   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11577       (!isPPC64 && VT != MVT::i32))
11578     report_fatal_error("Invalid register global variable type");
11579 
11580   bool is64Bit = isPPC64 && VT == MVT::i64;
11581   unsigned Reg = StringSwitch<unsigned>(RegName)
11582                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11583                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11584                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11585                                   (is64Bit ? PPC::X13 : PPC::R13))
11586                    .Default(0);
11587 
11588   if (Reg)
11589     return Reg;
11590   report_fatal_error("Invalid register name global variable");
11591 }
11592 
11593 bool
11594 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11595   // The PowerPC target isn't yet aware of offsets.
11596   return false;
11597 }
11598 
11599 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11600                                            const CallInst &I,
11601                                            unsigned Intrinsic) const {
11602 
11603   switch (Intrinsic) {
11604   case Intrinsic::ppc_qpx_qvlfd:
11605   case Intrinsic::ppc_qpx_qvlfs:
11606   case Intrinsic::ppc_qpx_qvlfcd:
11607   case Intrinsic::ppc_qpx_qvlfcs:
11608   case Intrinsic::ppc_qpx_qvlfiwa:
11609   case Intrinsic::ppc_qpx_qvlfiwz:
11610   case Intrinsic::ppc_altivec_lvx:
11611   case Intrinsic::ppc_altivec_lvxl:
11612   case Intrinsic::ppc_altivec_lvebx:
11613   case Intrinsic::ppc_altivec_lvehx:
11614   case Intrinsic::ppc_altivec_lvewx:
11615   case Intrinsic::ppc_vsx_lxvd2x:
11616   case Intrinsic::ppc_vsx_lxvw4x: {
11617     EVT VT;
11618     switch (Intrinsic) {
11619     case Intrinsic::ppc_altivec_lvebx:
11620       VT = MVT::i8;
11621       break;
11622     case Intrinsic::ppc_altivec_lvehx:
11623       VT = MVT::i16;
11624       break;
11625     case Intrinsic::ppc_altivec_lvewx:
11626       VT = MVT::i32;
11627       break;
11628     case Intrinsic::ppc_vsx_lxvd2x:
11629       VT = MVT::v2f64;
11630       break;
11631     case Intrinsic::ppc_qpx_qvlfd:
11632       VT = MVT::v4f64;
11633       break;
11634     case Intrinsic::ppc_qpx_qvlfs:
11635       VT = MVT::v4f32;
11636       break;
11637     case Intrinsic::ppc_qpx_qvlfcd:
11638       VT = MVT::v2f64;
11639       break;
11640     case Intrinsic::ppc_qpx_qvlfcs:
11641       VT = MVT::v2f32;
11642       break;
11643     default:
11644       VT = MVT::v4i32;
11645       break;
11646     }
11647 
11648     Info.opc = ISD::INTRINSIC_W_CHAIN;
11649     Info.memVT = VT;
11650     Info.ptrVal = I.getArgOperand(0);
11651     Info.offset = -VT.getStoreSize()+1;
11652     Info.size = 2*VT.getStoreSize()-1;
11653     Info.align = 1;
11654     Info.vol = false;
11655     Info.readMem = true;
11656     Info.writeMem = false;
11657     return true;
11658   }
11659   case Intrinsic::ppc_qpx_qvlfda:
11660   case Intrinsic::ppc_qpx_qvlfsa:
11661   case Intrinsic::ppc_qpx_qvlfcda:
11662   case Intrinsic::ppc_qpx_qvlfcsa:
11663   case Intrinsic::ppc_qpx_qvlfiwaa:
11664   case Intrinsic::ppc_qpx_qvlfiwza: {
11665     EVT VT;
11666     switch (Intrinsic) {
11667     case Intrinsic::ppc_qpx_qvlfda:
11668       VT = MVT::v4f64;
11669       break;
11670     case Intrinsic::ppc_qpx_qvlfsa:
11671       VT = MVT::v4f32;
11672       break;
11673     case Intrinsic::ppc_qpx_qvlfcda:
11674       VT = MVT::v2f64;
11675       break;
11676     case Intrinsic::ppc_qpx_qvlfcsa:
11677       VT = MVT::v2f32;
11678       break;
11679     default:
11680       VT = MVT::v4i32;
11681       break;
11682     }
11683 
11684     Info.opc = ISD::INTRINSIC_W_CHAIN;
11685     Info.memVT = VT;
11686     Info.ptrVal = I.getArgOperand(0);
11687     Info.offset = 0;
11688     Info.size = VT.getStoreSize();
11689     Info.align = 1;
11690     Info.vol = false;
11691     Info.readMem = true;
11692     Info.writeMem = false;
11693     return true;
11694   }
11695   case Intrinsic::ppc_qpx_qvstfd:
11696   case Intrinsic::ppc_qpx_qvstfs:
11697   case Intrinsic::ppc_qpx_qvstfcd:
11698   case Intrinsic::ppc_qpx_qvstfcs:
11699   case Intrinsic::ppc_qpx_qvstfiw:
11700   case Intrinsic::ppc_altivec_stvx:
11701   case Intrinsic::ppc_altivec_stvxl:
11702   case Intrinsic::ppc_altivec_stvebx:
11703   case Intrinsic::ppc_altivec_stvehx:
11704   case Intrinsic::ppc_altivec_stvewx:
11705   case Intrinsic::ppc_vsx_stxvd2x:
11706   case Intrinsic::ppc_vsx_stxvw4x: {
11707     EVT VT;
11708     switch (Intrinsic) {
11709     case Intrinsic::ppc_altivec_stvebx:
11710       VT = MVT::i8;
11711       break;
11712     case Intrinsic::ppc_altivec_stvehx:
11713       VT = MVT::i16;
11714       break;
11715     case Intrinsic::ppc_altivec_stvewx:
11716       VT = MVT::i32;
11717       break;
11718     case Intrinsic::ppc_vsx_stxvd2x:
11719       VT = MVT::v2f64;
11720       break;
11721     case Intrinsic::ppc_qpx_qvstfd:
11722       VT = MVT::v4f64;
11723       break;
11724     case Intrinsic::ppc_qpx_qvstfs:
11725       VT = MVT::v4f32;
11726       break;
11727     case Intrinsic::ppc_qpx_qvstfcd:
11728       VT = MVT::v2f64;
11729       break;
11730     case Intrinsic::ppc_qpx_qvstfcs:
11731       VT = MVT::v2f32;
11732       break;
11733     default:
11734       VT = MVT::v4i32;
11735       break;
11736     }
11737 
11738     Info.opc = ISD::INTRINSIC_VOID;
11739     Info.memVT = VT;
11740     Info.ptrVal = I.getArgOperand(1);
11741     Info.offset = -VT.getStoreSize()+1;
11742     Info.size = 2*VT.getStoreSize()-1;
11743     Info.align = 1;
11744     Info.vol = false;
11745     Info.readMem = false;
11746     Info.writeMem = true;
11747     return true;
11748   }
11749   case Intrinsic::ppc_qpx_qvstfda:
11750   case Intrinsic::ppc_qpx_qvstfsa:
11751   case Intrinsic::ppc_qpx_qvstfcda:
11752   case Intrinsic::ppc_qpx_qvstfcsa:
11753   case Intrinsic::ppc_qpx_qvstfiwa: {
11754     EVT VT;
11755     switch (Intrinsic) {
11756     case Intrinsic::ppc_qpx_qvstfda:
11757       VT = MVT::v4f64;
11758       break;
11759     case Intrinsic::ppc_qpx_qvstfsa:
11760       VT = MVT::v4f32;
11761       break;
11762     case Intrinsic::ppc_qpx_qvstfcda:
11763       VT = MVT::v2f64;
11764       break;
11765     case Intrinsic::ppc_qpx_qvstfcsa:
11766       VT = MVT::v2f32;
11767       break;
11768     default:
11769       VT = MVT::v4i32;
11770       break;
11771     }
11772 
11773     Info.opc = ISD::INTRINSIC_VOID;
11774     Info.memVT = VT;
11775     Info.ptrVal = I.getArgOperand(1);
11776     Info.offset = 0;
11777     Info.size = VT.getStoreSize();
11778     Info.align = 1;
11779     Info.vol = false;
11780     Info.readMem = false;
11781     Info.writeMem = true;
11782     return true;
11783   }
11784   default:
11785     break;
11786   }
11787 
11788   return false;
11789 }
11790 
11791 /// getOptimalMemOpType - Returns the target specific optimal type for load
11792 /// and store operations as a result of memset, memcpy, and memmove
11793 /// lowering. If DstAlign is zero that means it's safe to destination
11794 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11795 /// means there isn't a need to check it against alignment requirement,
11796 /// probably because the source does not need to be loaded. If 'IsMemset' is
11797 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11798 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11799 /// source is constant so it does not need to be loaded.
11800 /// It returns EVT::Other if the type should be determined using generic
11801 /// target-independent logic.
11802 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11803                                            unsigned DstAlign, unsigned SrcAlign,
11804                                            bool IsMemset, bool ZeroMemset,
11805                                            bool MemcpyStrSrc,
11806                                            MachineFunction &MF) const {
11807   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11808     const Function *F = MF.getFunction();
11809     // When expanding a memset, require at least two QPX instructions to cover
11810     // the cost of loading the value to be stored from the constant pool.
11811     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11812        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11813         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11814       return MVT::v4f64;
11815     }
11816 
11817     // We should use Altivec/VSX loads and stores when available. For unaligned
11818     // addresses, unaligned VSX loads are only fast starting with the P8.
11819     if (Subtarget.hasAltivec() && Size >= 16 &&
11820         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11821          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11822       return MVT::v4i32;
11823   }
11824 
11825   if (Subtarget.isPPC64()) {
11826     return MVT::i64;
11827   }
11828 
11829   return MVT::i32;
11830 }
11831 
11832 /// \brief Returns true if it is beneficial to convert a load of a constant
11833 /// to just the constant itself.
11834 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11835                                                           Type *Ty) const {
11836   assert(Ty->isIntegerTy());
11837 
11838   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11839   return !(BitSize == 0 || BitSize > 64);
11840 }
11841 
11842 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11843   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11844     return false;
11845   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11846   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11847   return NumBits1 == 64 && NumBits2 == 32;
11848 }
11849 
11850 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11851   if (!VT1.isInteger() || !VT2.isInteger())
11852     return false;
11853   unsigned NumBits1 = VT1.getSizeInBits();
11854   unsigned NumBits2 = VT2.getSizeInBits();
11855   return NumBits1 == 64 && NumBits2 == 32;
11856 }
11857 
11858 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11859   // Generally speaking, zexts are not free, but they are free when they can be
11860   // folded with other operations.
11861   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11862     EVT MemVT = LD->getMemoryVT();
11863     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11864          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11865         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11866          LD->getExtensionType() == ISD::ZEXTLOAD))
11867       return true;
11868   }
11869 
11870   // FIXME: Add other cases...
11871   //  - 32-bit shifts with a zext to i64
11872   //  - zext after ctlz, bswap, etc.
11873   //  - zext after and by a constant mask
11874 
11875   return TargetLowering::isZExtFree(Val, VT2);
11876 }
11877 
11878 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11879   assert(VT.isFloatingPoint());
11880   return true;
11881 }
11882 
11883 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11884   return isInt<16>(Imm) || isUInt<16>(Imm);
11885 }
11886 
11887 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11888   return isInt<16>(Imm) || isUInt<16>(Imm);
11889 }
11890 
11891 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11892                                                        unsigned,
11893                                                        unsigned,
11894                                                        bool *Fast) const {
11895   if (DisablePPCUnaligned)
11896     return false;
11897 
11898   // PowerPC supports unaligned memory access for simple non-vector types.
11899   // Although accessing unaligned addresses is not as efficient as accessing
11900   // aligned addresses, it is generally more efficient than manual expansion,
11901   // and generally only traps for software emulation when crossing page
11902   // boundaries.
11903 
11904   if (!VT.isSimple())
11905     return false;
11906 
11907   if (VT.getSimpleVT().isVector()) {
11908     if (Subtarget.hasVSX()) {
11909       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11910           VT != MVT::v4f32 && VT != MVT::v4i32)
11911         return false;
11912     } else {
11913       return false;
11914     }
11915   }
11916 
11917   if (VT == MVT::ppcf128)
11918     return false;
11919 
11920   if (Fast)
11921     *Fast = true;
11922 
11923   return true;
11924 }
11925 
11926 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11927   VT = VT.getScalarType();
11928 
11929   if (!VT.isSimple())
11930     return false;
11931 
11932   switch (VT.getSimpleVT().SimpleTy) {
11933   case MVT::f32:
11934   case MVT::f64:
11935     return true;
11936   default:
11937     break;
11938   }
11939 
11940   return false;
11941 }
11942 
11943 const MCPhysReg *
11944 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11945   // LR is a callee-save register, but we must treat it as clobbered by any call
11946   // site. Hence we include LR in the scratch registers, which are in turn added
11947   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11948   // to CTR, which is used by any indirect call.
11949   static const MCPhysReg ScratchRegs[] = {
11950     PPC::X12, PPC::LR8, PPC::CTR8, 0
11951   };
11952 
11953   return ScratchRegs;
11954 }
11955 
11956 unsigned PPCTargetLowering::getExceptionPointerRegister(
11957     const Constant *PersonalityFn) const {
11958   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
11959 }
11960 
11961 unsigned PPCTargetLowering::getExceptionSelectorRegister(
11962     const Constant *PersonalityFn) const {
11963   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
11964 }
11965 
11966 bool
11967 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11968                      EVT VT , unsigned DefinedValues) const {
11969   if (VT == MVT::v2i64)
11970     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
11971 
11972   if (Subtarget.hasVSX() || Subtarget.hasQPX())
11973     return true;
11974 
11975   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11976 }
11977 
11978 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11979   if (DisableILPPref || Subtarget.enableMachineScheduler())
11980     return TargetLowering::getSchedulingPreference(N);
11981 
11982   return Sched::ILP;
11983 }
11984 
11985 // Create a fast isel object.
11986 FastISel *
11987 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11988                                   const TargetLibraryInfo *LibInfo) const {
11989   return PPC::createFastISel(FuncInfo, LibInfo);
11990 }
11991 
11992 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11993   if (Subtarget.isDarwinABI()) return;
11994   if (!Subtarget.isPPC64()) return;
11995 
11996   // Update IsSplitCSR in PPCFunctionInfo
11997   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
11998   PFI->setIsSplitCSR(true);
11999 }
12000 
12001 void PPCTargetLowering::insertCopiesSplitCSR(
12002   MachineBasicBlock *Entry,
12003   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12004   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12005   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12006   if (!IStart)
12007     return;
12008 
12009   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12010   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12011   MachineBasicBlock::iterator MBBI = Entry->begin();
12012   for (const MCPhysReg *I = IStart; *I; ++I) {
12013     const TargetRegisterClass *RC = nullptr;
12014     if (PPC::G8RCRegClass.contains(*I))
12015       RC = &PPC::G8RCRegClass;
12016     else if (PPC::F8RCRegClass.contains(*I))
12017       RC = &PPC::F8RCRegClass;
12018     else if (PPC::CRRCRegClass.contains(*I))
12019       RC = &PPC::CRRCRegClass;
12020     else if (PPC::VRRCRegClass.contains(*I))
12021       RC = &PPC::VRRCRegClass;
12022     else
12023       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12024 
12025     unsigned NewVR = MRI->createVirtualRegister(RC);
12026     // Create copy from CSR to a virtual register.
12027     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12028     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12029     // nounwind. If we want to generalize this later, we may need to emit
12030     // CFI pseudo-instructions.
12031     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12032              Attribute::NoUnwind) &&
12033            "Function should be nounwind in insertCopiesSplitCSR!");
12034     Entry->addLiveIn(*I);
12035     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12036       .addReg(*I);
12037 
12038     // Insert the copy-back instructions right before the terminator
12039     for (auto *Exit : Exits)
12040       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12041               TII->get(TargetOpcode::COPY), *I)
12042         .addReg(NewVR);
12043   }
12044 }
12045 
12046 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12047 bool PPCTargetLowering::useLoadStackGuardNode() const {
12048   if (!Subtarget.isTargetLinux())
12049     return TargetLowering::useLoadStackGuardNode();
12050   return true;
12051 }
12052 
12053 // Override to disable global variable loading on Linux.
12054 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12055   if (!Subtarget.isTargetLinux())
12056     return TargetLowering::insertSSPDeclarations(M);
12057 }
12058