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   if (Subtarget.enableMachineScheduler())
927     setSchedulingPreference(Sched::Source);
928   else
929     setSchedulingPreference(Sched::Hybrid);
930 
931   computeRegisterProperties(STI.getRegisterInfo());
932 
933   // The Freescale cores do better with aggressive inlining of memcpy and
934   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
935   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
936       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
937     MaxStoresPerMemset = 32;
938     MaxStoresPerMemsetOptSize = 16;
939     MaxStoresPerMemcpy = 32;
940     MaxStoresPerMemcpyOptSize = 8;
941     MaxStoresPerMemmove = 32;
942     MaxStoresPerMemmoveOptSize = 8;
943   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
944     // The A2 also benefits from (very) aggressive inlining of memcpy and
945     // friends. The overhead of a the function call, even when warm, can be
946     // over one hundred cycles.
947     MaxStoresPerMemset = 128;
948     MaxStoresPerMemcpy = 128;
949     MaxStoresPerMemmove = 128;
950   }
951 }
952 
953 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
954 /// the desired ByVal argument alignment.
955 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
956                              unsigned MaxMaxAlign) {
957   if (MaxAlign == MaxMaxAlign)
958     return;
959   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
960     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
961       MaxAlign = 32;
962     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
963       MaxAlign = 16;
964   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
965     unsigned EltAlign = 0;
966     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
967     if (EltAlign > MaxAlign)
968       MaxAlign = EltAlign;
969   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
970     for (auto *EltTy : STy->elements()) {
971       unsigned EltAlign = 0;
972       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
973       if (EltAlign > MaxAlign)
974         MaxAlign = EltAlign;
975       if (MaxAlign == MaxMaxAlign)
976         break;
977     }
978   }
979 }
980 
981 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
982 /// function arguments in the caller parameter area.
983 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
984                                                   const DataLayout &DL) const {
985   // Darwin passes everything on 4 byte boundary.
986   if (Subtarget.isDarwin())
987     return 4;
988 
989   // 16byte and wider vectors are passed on 16byte boundary.
990   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
991   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
992   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
993     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
994   return Align;
995 }
996 
997 bool PPCTargetLowering::useSoftFloat() const {
998   return Subtarget.useSoftFloat();
999 }
1000 
1001 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1002   switch ((PPCISD::NodeType)Opcode) {
1003   case PPCISD::FIRST_NUMBER:    break;
1004   case PPCISD::FSEL:            return "PPCISD::FSEL";
1005   case PPCISD::FCFID:           return "PPCISD::FCFID";
1006   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1007   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1008   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1009   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1010   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1011   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1012   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1013   case PPCISD::FRE:             return "PPCISD::FRE";
1014   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1015   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1016   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1017   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1018   case PPCISD::VPERM:           return "PPCISD::VPERM";
1019   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1020   case PPCISD::CMPB:            return "PPCISD::CMPB";
1021   case PPCISD::Hi:              return "PPCISD::Hi";
1022   case PPCISD::Lo:              return "PPCISD::Lo";
1023   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1024   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1025   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1026   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1027   case PPCISD::SRL:             return "PPCISD::SRL";
1028   case PPCISD::SRA:             return "PPCISD::SRA";
1029   case PPCISD::SHL:             return "PPCISD::SHL";
1030   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1031   case PPCISD::CALL:            return "PPCISD::CALL";
1032   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1033   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1034   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1035   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1036   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1037   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1038   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1039   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1040   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1041   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1042   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1043   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1044   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1045   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1046   case PPCISD::VCMP:            return "PPCISD::VCMP";
1047   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1048   case PPCISD::LBRX:            return "PPCISD::LBRX";
1049   case PPCISD::STBRX:           return "PPCISD::STBRX";
1050   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1051   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1052   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1053   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1054   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1055   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1056   case PPCISD::BDZ:             return "PPCISD::BDZ";
1057   case PPCISD::MFFS:            return "PPCISD::MFFS";
1058   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1059   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1060   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1061   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1062   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1063   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1064   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1065   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1066   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1067   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1068   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1069   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1070   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1071   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1072   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1073   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1074   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1075   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1076   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1077   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1078   case PPCISD::SC:              return "PPCISD::SC";
1079   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1080   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1081   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1082   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1083   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1084   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1085   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1086   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1087   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1088   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1089   }
1090   return nullptr;
1091 }
1092 
1093 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1094                                           EVT VT) const {
1095   if (!VT.isVector())
1096     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1097 
1098   if (Subtarget.hasQPX())
1099     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1100 
1101   return VT.changeVectorElementTypeToInteger();
1102 }
1103 
1104 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1105   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1106   return true;
1107 }
1108 
1109 //===----------------------------------------------------------------------===//
1110 // Node matching predicates, for use by the tblgen matching code.
1111 //===----------------------------------------------------------------------===//
1112 
1113 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1114 static bool isFloatingPointZero(SDValue Op) {
1115   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1116     return CFP->getValueAPF().isZero();
1117   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1118     // Maybe this has already been legalized into the constant pool?
1119     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1120       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1121         return CFP->getValueAPF().isZero();
1122   }
1123   return false;
1124 }
1125 
1126 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1127 /// true if Op is undef or if it matches the specified value.
1128 static bool isConstantOrUndef(int Op, int Val) {
1129   return Op < 0 || Op == Val;
1130 }
1131 
1132 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1133 /// VPKUHUM instruction.
1134 /// The ShuffleKind distinguishes between big-endian operations with
1135 /// two different inputs (0), either-endian operations with two identical
1136 /// inputs (1), and little-endian operations with two different inputs (2).
1137 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1138 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1139                                SelectionDAG &DAG) {
1140   bool IsLE = DAG.getDataLayout().isLittleEndian();
1141   if (ShuffleKind == 0) {
1142     if (IsLE)
1143       return false;
1144     for (unsigned i = 0; i != 16; ++i)
1145       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1146         return false;
1147   } else if (ShuffleKind == 2) {
1148     if (!IsLE)
1149       return false;
1150     for (unsigned i = 0; i != 16; ++i)
1151       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1152         return false;
1153   } else if (ShuffleKind == 1) {
1154     unsigned j = IsLE ? 0 : 1;
1155     for (unsigned i = 0; i != 8; ++i)
1156       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1157           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1158         return false;
1159   }
1160   return true;
1161 }
1162 
1163 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1164 /// VPKUWUM instruction.
1165 /// The ShuffleKind distinguishes between big-endian operations with
1166 /// two different inputs (0), either-endian operations with two identical
1167 /// inputs (1), and little-endian operations with two different inputs (2).
1168 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1169 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1170                                SelectionDAG &DAG) {
1171   bool IsLE = DAG.getDataLayout().isLittleEndian();
1172   if (ShuffleKind == 0) {
1173     if (IsLE)
1174       return false;
1175     for (unsigned i = 0; i != 16; i += 2)
1176       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1177           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1178         return false;
1179   } else if (ShuffleKind == 2) {
1180     if (!IsLE)
1181       return false;
1182     for (unsigned i = 0; i != 16; i += 2)
1183       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1184           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1185         return false;
1186   } else if (ShuffleKind == 1) {
1187     unsigned j = IsLE ? 0 : 2;
1188     for (unsigned i = 0; i != 8; i += 2)
1189       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1190           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1191           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1192           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1193         return false;
1194   }
1195   return true;
1196 }
1197 
1198 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1199 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1200 /// current subtarget.
1201 ///
1202 /// The ShuffleKind distinguishes between big-endian operations with
1203 /// two different inputs (0), either-endian operations with two identical
1204 /// inputs (1), and little-endian operations with two different inputs (2).
1205 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1206 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1207                                SelectionDAG &DAG) {
1208   const PPCSubtarget& Subtarget =
1209     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1210   if (!Subtarget.hasP8Vector())
1211     return false;
1212 
1213   bool IsLE = DAG.getDataLayout().isLittleEndian();
1214   if (ShuffleKind == 0) {
1215     if (IsLE)
1216       return false;
1217     for (unsigned i = 0; i != 16; i += 4)
1218       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1219           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1220           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1221           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1222         return false;
1223   } else if (ShuffleKind == 2) {
1224     if (!IsLE)
1225       return false;
1226     for (unsigned i = 0; i != 16; i += 4)
1227       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1228           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1229           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1230           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1231         return false;
1232   } else if (ShuffleKind == 1) {
1233     unsigned j = IsLE ? 0 : 4;
1234     for (unsigned i = 0; i != 8; i += 4)
1235       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1236           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1237           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1238           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1239           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1240           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1241           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1242           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1243         return false;
1244   }
1245   return true;
1246 }
1247 
1248 /// isVMerge - Common function, used to match vmrg* shuffles.
1249 ///
1250 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1251                      unsigned LHSStart, unsigned RHSStart) {
1252   if (N->getValueType(0) != MVT::v16i8)
1253     return false;
1254   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1255          "Unsupported merge size!");
1256 
1257   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1258     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1259       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1260                              LHSStart+j+i*UnitSize) ||
1261           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1262                              RHSStart+j+i*UnitSize))
1263         return false;
1264     }
1265   return true;
1266 }
1267 
1268 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1269 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1270 /// The ShuffleKind distinguishes between big-endian merges with two
1271 /// different inputs (0), either-endian merges with two identical inputs (1),
1272 /// and little-endian merges with two different inputs (2).  For the latter,
1273 /// the input operands are swapped (see PPCInstrAltivec.td).
1274 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1275                              unsigned ShuffleKind, SelectionDAG &DAG) {
1276   if (DAG.getDataLayout().isLittleEndian()) {
1277     if (ShuffleKind == 1) // unary
1278       return isVMerge(N, UnitSize, 0, 0);
1279     else if (ShuffleKind == 2) // swapped
1280       return isVMerge(N, UnitSize, 0, 16);
1281     else
1282       return false;
1283   } else {
1284     if (ShuffleKind == 1) // unary
1285       return isVMerge(N, UnitSize, 8, 8);
1286     else if (ShuffleKind == 0) // normal
1287       return isVMerge(N, UnitSize, 8, 24);
1288     else
1289       return false;
1290   }
1291 }
1292 
1293 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1294 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1295 /// The ShuffleKind distinguishes between big-endian merges with two
1296 /// different inputs (0), either-endian merges with two identical inputs (1),
1297 /// and little-endian merges with two different inputs (2).  For the latter,
1298 /// the input operands are swapped (see PPCInstrAltivec.td).
1299 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1300                              unsigned ShuffleKind, SelectionDAG &DAG) {
1301   if (DAG.getDataLayout().isLittleEndian()) {
1302     if (ShuffleKind == 1) // unary
1303       return isVMerge(N, UnitSize, 8, 8);
1304     else if (ShuffleKind == 2) // swapped
1305       return isVMerge(N, UnitSize, 8, 24);
1306     else
1307       return false;
1308   } else {
1309     if (ShuffleKind == 1) // unary
1310       return isVMerge(N, UnitSize, 0, 0);
1311     else if (ShuffleKind == 0) // normal
1312       return isVMerge(N, UnitSize, 0, 16);
1313     else
1314       return false;
1315   }
1316 }
1317 
1318 /**
1319  * \brief Common function used to match vmrgew and vmrgow shuffles
1320  *
1321  * The indexOffset determines whether to look for even or odd words in
1322  * the shuffle mask. This is based on the of the endianness of the target
1323  * machine.
1324  *   - Little Endian:
1325  *     - Use offset of 0 to check for odd elements
1326  *     - Use offset of 4 to check for even elements
1327  *   - Big Endian:
1328  *     - Use offset of 0 to check for even elements
1329  *     - Use offset of 4 to check for odd elements
1330  * A detailed description of the vector element ordering for little endian and
1331  * big endian can be found at
1332  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1333  * Targeting your applications - what little endian and big endian IBM XL C/C++
1334  * compiler differences mean to you
1335  *
1336  * The mask to the shuffle vector instruction specifies the indices of the
1337  * elements from the two input vectors to place in the result. The elements are
1338  * numbered in array-access order, starting with the first vector. These vectors
1339  * are always of type v16i8, thus each vector will contain 16 elements of size
1340  * 8. More info on the shuffle vector can be found in the
1341  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1342  * Language Reference.
1343  *
1344  * The RHSStartValue indicates whether the same input vectors are used (unary)
1345  * or two different input vectors are used, based on the following:
1346  *   - If the instruction uses the same vector for both inputs, the range of the
1347  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1348  *     be 0.
1349  *   - If the instruction has two different vectors then the range of the
1350  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1351  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1352  *     to 31 specify elements in the second vector).
1353  *
1354  * \param[in] N The shuffle vector SD Node to analyze
1355  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1356  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1357  * vector to the shuffle_vector instruction
1358  * \return true iff this shuffle vector represents an even or odd word merge
1359  */
1360 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1361                      unsigned RHSStartValue) {
1362   if (N->getValueType(0) != MVT::v16i8)
1363     return false;
1364 
1365   for (unsigned i = 0; i < 2; ++i)
1366     for (unsigned j = 0; j < 4; ++j)
1367       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1368                              i*RHSStartValue+j+IndexOffset) ||
1369           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1370                              i*RHSStartValue+j+IndexOffset+8))
1371         return false;
1372   return true;
1373 }
1374 
1375 /**
1376  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1377  * vmrgow instructions.
1378  *
1379  * \param[in] N The shuffle vector SD Node to analyze
1380  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1381  * \param[in] ShuffleKind Identify the type of merge:
1382  *   - 0 = big-endian merge with two different inputs;
1383  *   - 1 = either-endian merge with two identical inputs;
1384  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1385  *     little-endian merges).
1386  * \param[in] DAG The current SelectionDAG
1387  * \return true iff this shuffle mask
1388  */
1389 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1390                               unsigned ShuffleKind, SelectionDAG &DAG) {
1391   if (DAG.getDataLayout().isLittleEndian()) {
1392     unsigned indexOffset = CheckEven ? 4 : 0;
1393     if (ShuffleKind == 1) // Unary
1394       return isVMerge(N, indexOffset, 0);
1395     else if (ShuffleKind == 2) // swapped
1396       return isVMerge(N, indexOffset, 16);
1397     else
1398       return false;
1399   }
1400   else {
1401     unsigned indexOffset = CheckEven ? 0 : 4;
1402     if (ShuffleKind == 1) // Unary
1403       return isVMerge(N, indexOffset, 0);
1404     else if (ShuffleKind == 0) // Normal
1405       return isVMerge(N, indexOffset, 16);
1406     else
1407       return false;
1408   }
1409   return false;
1410 }
1411 
1412 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1413 /// amount, otherwise return -1.
1414 /// The ShuffleKind distinguishes between big-endian operations with two
1415 /// different inputs (0), either-endian operations with two identical inputs
1416 /// (1), and little-endian operations with two different inputs (2).  For the
1417 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1418 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1419                              SelectionDAG &DAG) {
1420   if (N->getValueType(0) != MVT::v16i8)
1421     return -1;
1422 
1423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1424 
1425   // Find the first non-undef value in the shuffle mask.
1426   unsigned i;
1427   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1428     /*search*/;
1429 
1430   if (i == 16) return -1;  // all undef.
1431 
1432   // Otherwise, check to see if the rest of the elements are consecutively
1433   // numbered from this value.
1434   unsigned ShiftAmt = SVOp->getMaskElt(i);
1435   if (ShiftAmt < i) return -1;
1436 
1437   ShiftAmt -= i;
1438   bool isLE = DAG.getDataLayout().isLittleEndian();
1439 
1440   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1441     // Check the rest of the elements to see if they are consecutive.
1442     for (++i; i != 16; ++i)
1443       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1444         return -1;
1445   } else if (ShuffleKind == 1) {
1446     // Check the rest of the elements to see if they are consecutive.
1447     for (++i; i != 16; ++i)
1448       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1449         return -1;
1450   } else
1451     return -1;
1452 
1453   if (isLE)
1454     ShiftAmt = 16 - ShiftAmt;
1455 
1456   return ShiftAmt;
1457 }
1458 
1459 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1460 /// specifies a splat of a single element that is suitable for input to
1461 /// VSPLTB/VSPLTH/VSPLTW.
1462 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1463   assert(N->getValueType(0) == MVT::v16i8 &&
1464          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1465 
1466   // The consecutive indices need to specify an element, not part of two
1467   // different elements.  So abandon ship early if this isn't the case.
1468   if (N->getMaskElt(0) % EltSize != 0)
1469     return false;
1470 
1471   // This is a splat operation if each element of the permute is the same, and
1472   // if the value doesn't reference the second vector.
1473   unsigned ElementBase = N->getMaskElt(0);
1474 
1475   // FIXME: Handle UNDEF elements too!
1476   if (ElementBase >= 16)
1477     return false;
1478 
1479   // Check that the indices are consecutive, in the case of a multi-byte element
1480   // splatted with a v16i8 mask.
1481   for (unsigned i = 1; i != EltSize; ++i)
1482     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1483       return false;
1484 
1485   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1486     if (N->getMaskElt(i) < 0) continue;
1487     for (unsigned j = 0; j != EltSize; ++j)
1488       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1489         return false;
1490   }
1491   return true;
1492 }
1493 
1494 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1495 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1496 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1497                                 SelectionDAG &DAG) {
1498   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1499   assert(isSplatShuffleMask(SVOp, EltSize));
1500   if (DAG.getDataLayout().isLittleEndian())
1501     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1502   else
1503     return SVOp->getMaskElt(0) / EltSize;
1504 }
1505 
1506 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1507 /// by using a vspltis[bhw] instruction of the specified element size, return
1508 /// the constant being splatted.  The ByteSize field indicates the number of
1509 /// bytes of each element [124] -> [bhw].
1510 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1511   SDValue OpVal(nullptr, 0);
1512 
1513   // If ByteSize of the splat is bigger than the element size of the
1514   // build_vector, then we have a case where we are checking for a splat where
1515   // multiple elements of the buildvector are folded together into a single
1516   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1517   unsigned EltSize = 16/N->getNumOperands();
1518   if (EltSize < ByteSize) {
1519     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1520     SDValue UniquedVals[4];
1521     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1522 
1523     // See if all of the elements in the buildvector agree across.
1524     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1525       if (N->getOperand(i).isUndef()) continue;
1526       // If the element isn't a constant, bail fully out.
1527       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1528 
1529 
1530       if (!UniquedVals[i&(Multiple-1)].getNode())
1531         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1532       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1533         return SDValue();  // no match.
1534     }
1535 
1536     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1537     // either constant or undef values that are identical for each chunk.  See
1538     // if these chunks can form into a larger vspltis*.
1539 
1540     // Check to see if all of the leading entries are either 0 or -1.  If
1541     // neither, then this won't fit into the immediate field.
1542     bool LeadingZero = true;
1543     bool LeadingOnes = true;
1544     for (unsigned i = 0; i != Multiple-1; ++i) {
1545       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1546 
1547       LeadingZero &= isNullConstant(UniquedVals[i]);
1548       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1549     }
1550     // Finally, check the least significant entry.
1551     if (LeadingZero) {
1552       if (!UniquedVals[Multiple-1].getNode())
1553         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1554       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1555       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1556         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1557     }
1558     if (LeadingOnes) {
1559       if (!UniquedVals[Multiple-1].getNode())
1560         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1561       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1562       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1563         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1564     }
1565 
1566     return SDValue();
1567   }
1568 
1569   // Check to see if this buildvec has a single non-undef value in its elements.
1570   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1571     if (N->getOperand(i).isUndef()) continue;
1572     if (!OpVal.getNode())
1573       OpVal = N->getOperand(i);
1574     else if (OpVal != N->getOperand(i))
1575       return SDValue();
1576   }
1577 
1578   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1579 
1580   unsigned ValSizeInBytes = EltSize;
1581   uint64_t Value = 0;
1582   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1583     Value = CN->getZExtValue();
1584   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1585     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1586     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1587   }
1588 
1589   // If the splat value is larger than the element value, then we can never do
1590   // this splat.  The only case that we could fit the replicated bits into our
1591   // immediate field for would be zero, and we prefer to use vxor for it.
1592   if (ValSizeInBytes < ByteSize) return SDValue();
1593 
1594   // If the element value is larger than the splat value, check if it consists
1595   // of a repeated bit pattern of size ByteSize.
1596   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1597     return SDValue();
1598 
1599   // Properly sign extend the value.
1600   int MaskVal = SignExtend32(Value, ByteSize * 8);
1601 
1602   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1603   if (MaskVal == 0) return SDValue();
1604 
1605   // Finally, if this value fits in a 5 bit sext field, return it
1606   if (SignExtend32<5>(MaskVal) == MaskVal)
1607     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1608   return SDValue();
1609 }
1610 
1611 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1612 /// amount, otherwise return -1.
1613 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1614   EVT VT = N->getValueType(0);
1615   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1616     return -1;
1617 
1618   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1619 
1620   // Find the first non-undef value in the shuffle mask.
1621   unsigned i;
1622   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1623     /*search*/;
1624 
1625   if (i == 4) return -1;  // all undef.
1626 
1627   // Otherwise, check to see if the rest of the elements are consecutively
1628   // numbered from this value.
1629   unsigned ShiftAmt = SVOp->getMaskElt(i);
1630   if (ShiftAmt < i) return -1;
1631   ShiftAmt -= i;
1632 
1633   // Check the rest of the elements to see if they are consecutive.
1634   for (++i; i != 4; ++i)
1635     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1636       return -1;
1637 
1638   return ShiftAmt;
1639 }
1640 
1641 //===----------------------------------------------------------------------===//
1642 //  Addressing Mode Selection
1643 //===----------------------------------------------------------------------===//
1644 
1645 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1646 /// or 64-bit immediate, and if the value can be accurately represented as a
1647 /// sign extension from a 16-bit value.  If so, this returns true and the
1648 /// immediate.
1649 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1650   if (!isa<ConstantSDNode>(N))
1651     return false;
1652 
1653   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1654   if (N->getValueType(0) == MVT::i32)
1655     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1656   else
1657     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1658 }
1659 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1660   return isIntS16Immediate(Op.getNode(), Imm);
1661 }
1662 
1663 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1664 /// can be represented as an indexed [r+r] operation.  Returns false if it
1665 /// can be more efficiently represented with [r+imm].
1666 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1667                                             SDValue &Index,
1668                                             SelectionDAG &DAG) const {
1669   short imm = 0;
1670   if (N.getOpcode() == ISD::ADD) {
1671     if (isIntS16Immediate(N.getOperand(1), imm))
1672       return false;    // r+i
1673     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1674       return false;    // r+i
1675 
1676     Base = N.getOperand(0);
1677     Index = N.getOperand(1);
1678     return true;
1679   } else if (N.getOpcode() == ISD::OR) {
1680     if (isIntS16Immediate(N.getOperand(1), imm))
1681       return false;    // r+i can fold it if we can.
1682 
1683     // If this is an or of disjoint bitfields, we can codegen this as an add
1684     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1685     // disjoint.
1686     APInt LHSKnownZero, LHSKnownOne;
1687     APInt RHSKnownZero, RHSKnownOne;
1688     DAG.computeKnownBits(N.getOperand(0),
1689                          LHSKnownZero, LHSKnownOne);
1690 
1691     if (LHSKnownZero.getBoolValue()) {
1692       DAG.computeKnownBits(N.getOperand(1),
1693                            RHSKnownZero, RHSKnownOne);
1694       // If all of the bits are known zero on the LHS or RHS, the add won't
1695       // carry.
1696       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1697         Base = N.getOperand(0);
1698         Index = N.getOperand(1);
1699         return true;
1700       }
1701     }
1702   }
1703 
1704   return false;
1705 }
1706 
1707 // If we happen to be doing an i64 load or store into a stack slot that has
1708 // less than a 4-byte alignment, then the frame-index elimination may need to
1709 // use an indexed load or store instruction (because the offset may not be a
1710 // multiple of 4). The extra register needed to hold the offset comes from the
1711 // register scavenger, and it is possible that the scavenger will need to use
1712 // an emergency spill slot. As a result, we need to make sure that a spill slot
1713 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1714 // stack slot.
1715 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1716   // FIXME: This does not handle the LWA case.
1717   if (VT != MVT::i64)
1718     return;
1719 
1720   // NOTE: We'll exclude negative FIs here, which come from argument
1721   // lowering, because there are no known test cases triggering this problem
1722   // using packed structures (or similar). We can remove this exclusion if
1723   // we find such a test case. The reason why this is so test-case driven is
1724   // because this entire 'fixup' is only to prevent crashes (from the
1725   // register scavenger) on not-really-valid inputs. For example, if we have:
1726   //   %a = alloca i1
1727   //   %b = bitcast i1* %a to i64*
1728   //   store i64* a, i64 b
1729   // then the store should really be marked as 'align 1', but is not. If it
1730   // were marked as 'align 1' then the indexed form would have been
1731   // instruction-selected initially, and the problem this 'fixup' is preventing
1732   // won't happen regardless.
1733   if (FrameIdx < 0)
1734     return;
1735 
1736   MachineFunction &MF = DAG.getMachineFunction();
1737   MachineFrameInfo *MFI = MF.getFrameInfo();
1738 
1739   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1740   if (Align >= 4)
1741     return;
1742 
1743   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1744   FuncInfo->setHasNonRISpills();
1745 }
1746 
1747 /// Returns true if the address N can be represented by a base register plus
1748 /// a signed 16-bit displacement [r+imm], and if it is not better
1749 /// represented as reg+reg.  If Aligned is true, only accept displacements
1750 /// suitable for STD and friends, i.e. multiples of 4.
1751 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1752                                             SDValue &Base,
1753                                             SelectionDAG &DAG,
1754                                             bool Aligned) const {
1755   // FIXME dl should come from parent load or store, not from address
1756   SDLoc dl(N);
1757   // If this can be more profitably realized as r+r, fail.
1758   if (SelectAddressRegReg(N, Disp, Base, DAG))
1759     return false;
1760 
1761   if (N.getOpcode() == ISD::ADD) {
1762     short imm = 0;
1763     if (isIntS16Immediate(N.getOperand(1), imm) &&
1764         (!Aligned || (imm & 3) == 0)) {
1765       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1766       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1767         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1768         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1769       } else {
1770         Base = N.getOperand(0);
1771       }
1772       return true; // [r+i]
1773     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1774       // Match LOAD (ADD (X, Lo(G))).
1775       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1776              && "Cannot handle constant offsets yet!");
1777       Disp = N.getOperand(1).getOperand(0);  // The global address.
1778       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1779              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1780              Disp.getOpcode() == ISD::TargetConstantPool ||
1781              Disp.getOpcode() == ISD::TargetJumpTable);
1782       Base = N.getOperand(0);
1783       return true;  // [&g+r]
1784     }
1785   } else if (N.getOpcode() == ISD::OR) {
1786     short imm = 0;
1787     if (isIntS16Immediate(N.getOperand(1), imm) &&
1788         (!Aligned || (imm & 3) == 0)) {
1789       // If this is an or of disjoint bitfields, we can codegen this as an add
1790       // (for better address arithmetic) if the LHS and RHS of the OR are
1791       // provably disjoint.
1792       APInt LHSKnownZero, LHSKnownOne;
1793       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1794 
1795       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1796         // If all of the bits are known zero on the LHS or RHS, the add won't
1797         // carry.
1798         if (FrameIndexSDNode *FI =
1799               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1800           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1801           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1802         } else {
1803           Base = N.getOperand(0);
1804         }
1805         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1806         return true;
1807       }
1808     }
1809   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1810     // Loading from a constant address.
1811 
1812     // If this address fits entirely in a 16-bit sext immediate field, codegen
1813     // this as "d, 0"
1814     short Imm;
1815     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1816       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1817       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1818                              CN->getValueType(0));
1819       return true;
1820     }
1821 
1822     // Handle 32-bit sext immediates with LIS + addr mode.
1823     if ((CN->getValueType(0) == MVT::i32 ||
1824          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1825         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1826       int Addr = (int)CN->getZExtValue();
1827 
1828       // Otherwise, break this down into an LIS + disp.
1829       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1830 
1831       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1832                                    MVT::i32);
1833       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1834       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1835       return true;
1836     }
1837   }
1838 
1839   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1840   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1841     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1842     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1843   } else
1844     Base = N;
1845   return true;      // [r+0]
1846 }
1847 
1848 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1849 /// represented as an indexed [r+r] operation.
1850 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1851                                                 SDValue &Index,
1852                                                 SelectionDAG &DAG) const {
1853   // Check to see if we can easily represent this as an [r+r] address.  This
1854   // will fail if it thinks that the address is more profitably represented as
1855   // reg+imm, e.g. where imm = 0.
1856   if (SelectAddressRegReg(N, Base, Index, DAG))
1857     return true;
1858 
1859   // If the operand is an addition, always emit this as [r+r], since this is
1860   // better (for code size, and execution, as the memop does the add for free)
1861   // than emitting an explicit add.
1862   if (N.getOpcode() == ISD::ADD) {
1863     Base = N.getOperand(0);
1864     Index = N.getOperand(1);
1865     return true;
1866   }
1867 
1868   // Otherwise, do it the hard way, using R0 as the base register.
1869   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1870                          N.getValueType());
1871   Index = N;
1872   return true;
1873 }
1874 
1875 /// getPreIndexedAddressParts - returns true by value, base pointer and
1876 /// offset pointer and addressing mode by reference if the node's address
1877 /// can be legally represented as pre-indexed load / store address.
1878 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1879                                                   SDValue &Offset,
1880                                                   ISD::MemIndexedMode &AM,
1881                                                   SelectionDAG &DAG) const {
1882   if (DisablePPCPreinc) return false;
1883 
1884   bool isLoad = true;
1885   SDValue Ptr;
1886   EVT VT;
1887   unsigned Alignment;
1888   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1889     Ptr = LD->getBasePtr();
1890     VT = LD->getMemoryVT();
1891     Alignment = LD->getAlignment();
1892   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1893     Ptr = ST->getBasePtr();
1894     VT  = ST->getMemoryVT();
1895     Alignment = ST->getAlignment();
1896     isLoad = false;
1897   } else
1898     return false;
1899 
1900   // PowerPC doesn't have preinc load/store instructions for vectors (except
1901   // for QPX, which does have preinc r+r forms).
1902   if (VT.isVector()) {
1903     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1904       return false;
1905     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1906       AM = ISD::PRE_INC;
1907       return true;
1908     }
1909   }
1910 
1911   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1912 
1913     // Common code will reject creating a pre-inc form if the base pointer
1914     // is a frame index, or if N is a store and the base pointer is either
1915     // the same as or a predecessor of the value being stored.  Check for
1916     // those situations here, and try with swapped Base/Offset instead.
1917     bool Swap = false;
1918 
1919     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1920       Swap = true;
1921     else if (!isLoad) {
1922       SDValue Val = cast<StoreSDNode>(N)->getValue();
1923       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1924         Swap = true;
1925     }
1926 
1927     if (Swap)
1928       std::swap(Base, Offset);
1929 
1930     AM = ISD::PRE_INC;
1931     return true;
1932   }
1933 
1934   // LDU/STU can only handle immediates that are a multiple of 4.
1935   if (VT != MVT::i64) {
1936     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1937       return false;
1938   } else {
1939     // LDU/STU need an address with at least 4-byte alignment.
1940     if (Alignment < 4)
1941       return false;
1942 
1943     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1944       return false;
1945   }
1946 
1947   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1948     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1949     // sext i32 to i64 when addr mode is r+i.
1950     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1951         LD->getExtensionType() == ISD::SEXTLOAD &&
1952         isa<ConstantSDNode>(Offset))
1953       return false;
1954   }
1955 
1956   AM = ISD::PRE_INC;
1957   return true;
1958 }
1959 
1960 //===----------------------------------------------------------------------===//
1961 //  LowerOperation implementation
1962 //===----------------------------------------------------------------------===//
1963 
1964 /// GetLabelAccessInfo - Return true if we should reference labels using a
1965 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1966 static bool GetLabelAccessInfo(const TargetMachine &TM,
1967                                const PPCSubtarget &Subtarget,
1968                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1969                                const GlobalValue *GV = nullptr) {
1970   HiOpFlags = PPCII::MO_HA;
1971   LoOpFlags = PPCII::MO_LO;
1972 
1973   // Don't use the pic base if not in PIC relocation model.
1974   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1975 
1976   if (isPIC) {
1977     HiOpFlags |= PPCII::MO_PIC_FLAG;
1978     LoOpFlags |= PPCII::MO_PIC_FLAG;
1979   }
1980 
1981   // If this is a reference to a global value that requires a non-lazy-ptr, make
1982   // sure that instruction lowering adds it.
1983   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1984     HiOpFlags |= PPCII::MO_NLP_FLAG;
1985     LoOpFlags |= PPCII::MO_NLP_FLAG;
1986 
1987     if (GV->hasHiddenVisibility()) {
1988       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1989       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1990     }
1991   }
1992 
1993   return isPIC;
1994 }
1995 
1996 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1997                              SelectionDAG &DAG) {
1998   SDLoc DL(HiPart);
1999   EVT PtrVT = HiPart.getValueType();
2000   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2001 
2002   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2003   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2004 
2005   // With PIC, the first instruction is actually "GR+hi(&G)".
2006   if (isPIC)
2007     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2008                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2009 
2010   // Generate non-pic code that has direct accesses to the constant pool.
2011   // The address of the global is just (hi(&g)+lo(&g)).
2012   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2013 }
2014 
2015 static void setUsesTOCBasePtr(MachineFunction &MF) {
2016   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2017   FuncInfo->setUsesTOCBasePtr();
2018 }
2019 
2020 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2021   setUsesTOCBasePtr(DAG.getMachineFunction());
2022 }
2023 
2024 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2025                            SDValue GA) {
2026   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2027   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2028                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2029 
2030   SDValue Ops[] = { GA, Reg };
2031   return DAG.getMemIntrinsicNode(
2032       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2033       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2034       false, 0);
2035 }
2036 
2037 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2038                                              SelectionDAG &DAG) const {
2039   EVT PtrVT = Op.getValueType();
2040   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2041   const Constant *C = CP->getConstVal();
2042 
2043   // 64-bit SVR4 ABI code is always position-independent.
2044   // The actual address of the GlobalValue is stored in the TOC.
2045   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2046     setUsesTOCBasePtr(DAG);
2047     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2048     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2049   }
2050 
2051   unsigned MOHiFlag, MOLoFlag;
2052   bool isPIC =
2053       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2054 
2055   if (isPIC && Subtarget.isSVR4ABI()) {
2056     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2057                                            PPCII::MO_PIC_FLAG);
2058     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2059   }
2060 
2061   SDValue CPIHi =
2062     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2063   SDValue CPILo =
2064     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2065   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
2066 }
2067 
2068 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2069   EVT PtrVT = Op.getValueType();
2070   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2071 
2072   // 64-bit SVR4 ABI code is always position-independent.
2073   // The actual address of the GlobalValue is stored in the TOC.
2074   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2075     setUsesTOCBasePtr(DAG);
2076     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2077     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2078   }
2079 
2080   unsigned MOHiFlag, MOLoFlag;
2081   bool isPIC =
2082       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2083 
2084   if (isPIC && Subtarget.isSVR4ABI()) {
2085     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2086                                         PPCII::MO_PIC_FLAG);
2087     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2088   }
2089 
2090   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2091   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2092   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
2093 }
2094 
2095 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2096                                              SelectionDAG &DAG) const {
2097   EVT PtrVT = Op.getValueType();
2098   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2099   const BlockAddress *BA = BASDN->getBlockAddress();
2100 
2101   // 64-bit SVR4 ABI code is always position-independent.
2102   // The actual BlockAddress is stored in the TOC.
2103   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2104     setUsesTOCBasePtr(DAG);
2105     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2106     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2107   }
2108 
2109   unsigned MOHiFlag, MOLoFlag;
2110   bool isPIC =
2111       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2112   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2113   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2114   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
2115 }
2116 
2117 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2118                                               SelectionDAG &DAG) const {
2119 
2120   // FIXME: TLS addresses currently use medium model code sequences,
2121   // which is the most useful form.  Eventually support for small and
2122   // large models could be added if users need it, at the cost of
2123   // additional complexity.
2124   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2125   if (DAG.getTarget().Options.EmulatedTLS)
2126     return LowerToTLSEmulatedModel(GA, DAG);
2127 
2128   SDLoc dl(GA);
2129   const GlobalValue *GV = GA->getGlobal();
2130   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2131   bool is64bit = Subtarget.isPPC64();
2132   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2133   PICLevel::Level picLevel = M->getPICLevel();
2134 
2135   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2136 
2137   if (Model == TLSModel::LocalExec) {
2138     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2139                                                PPCII::MO_TPREL_HA);
2140     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2141                                                PPCII::MO_TPREL_LO);
2142     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2143                                      is64bit ? MVT::i64 : MVT::i32);
2144     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2145     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2146   }
2147 
2148   if (Model == TLSModel::InitialExec) {
2149     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2150     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2151                                                 PPCII::MO_TLS);
2152     SDValue GOTPtr;
2153     if (is64bit) {
2154       setUsesTOCBasePtr(DAG);
2155       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2156       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2157                            PtrVT, GOTReg, TGA);
2158     } else
2159       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2160     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2161                                    PtrVT, TGA, GOTPtr);
2162     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2163   }
2164 
2165   if (Model == TLSModel::GeneralDynamic) {
2166     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2167     SDValue GOTPtr;
2168     if (is64bit) {
2169       setUsesTOCBasePtr(DAG);
2170       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2171       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2172                                    GOTReg, TGA);
2173     } else {
2174       if (picLevel == PICLevel::SmallPIC)
2175         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2176       else
2177         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2178     }
2179     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2180                        GOTPtr, TGA, TGA);
2181   }
2182 
2183   if (Model == TLSModel::LocalDynamic) {
2184     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2185     SDValue GOTPtr;
2186     if (is64bit) {
2187       setUsesTOCBasePtr(DAG);
2188       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2189       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2190                            GOTReg, TGA);
2191     } else {
2192       if (picLevel == PICLevel::SmallPIC)
2193         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2194       else
2195         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2196     }
2197     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2198                                   PtrVT, GOTPtr, TGA, TGA);
2199     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2200                                       PtrVT, TLSAddr, TGA);
2201     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2202   }
2203 
2204   llvm_unreachable("Unknown TLS model!");
2205 }
2206 
2207 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2208                                               SelectionDAG &DAG) const {
2209   EVT PtrVT = Op.getValueType();
2210   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2211   SDLoc DL(GSDN);
2212   const GlobalValue *GV = GSDN->getGlobal();
2213 
2214   // 64-bit SVR4 ABI code is always position-independent.
2215   // The actual address of the GlobalValue is stored in the TOC.
2216   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2217     setUsesTOCBasePtr(DAG);
2218     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2219     return getTOCEntry(DAG, DL, true, GA);
2220   }
2221 
2222   unsigned MOHiFlag, MOLoFlag;
2223   bool isPIC =
2224       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2225 
2226   if (isPIC && Subtarget.isSVR4ABI()) {
2227     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2228                                             GSDN->getOffset(),
2229                                             PPCII::MO_PIC_FLAG);
2230     return getTOCEntry(DAG, DL, false, GA);
2231   }
2232 
2233   SDValue GAHi =
2234     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2235   SDValue GALo =
2236     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2237 
2238   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2239 
2240   // If the global reference is actually to a non-lazy-pointer, we have to do an
2241   // extra load to get the address of the global.
2242   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2243     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2244                       false, false, false, 0);
2245   return Ptr;
2246 }
2247 
2248 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2249   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2250   SDLoc dl(Op);
2251 
2252   if (Op.getValueType() == MVT::v2i64) {
2253     // When the operands themselves are v2i64 values, we need to do something
2254     // special because VSX has no underlying comparison operations for these.
2255     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2256       // Equality can be handled by casting to the legal type for Altivec
2257       // comparisons, everything else needs to be expanded.
2258       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2259         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2260                  DAG.getSetCC(dl, MVT::v4i32,
2261                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2262                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2263                    CC));
2264       }
2265 
2266       return SDValue();
2267     }
2268 
2269     // We handle most of these in the usual way.
2270     return Op;
2271   }
2272 
2273   // If we're comparing for equality to zero, expose the fact that this is
2274   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2275   // fold the new nodes.
2276   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2277     if (C->isNullValue() && CC == ISD::SETEQ) {
2278       EVT VT = Op.getOperand(0).getValueType();
2279       SDValue Zext = Op.getOperand(0);
2280       if (VT.bitsLT(MVT::i32)) {
2281         VT = MVT::i32;
2282         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2283       }
2284       unsigned Log2b = Log2_32(VT.getSizeInBits());
2285       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2286       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2287                                 DAG.getConstant(Log2b, dl, MVT::i32));
2288       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2289     }
2290     // Leave comparisons against 0 and -1 alone for now, since they're usually
2291     // optimized.  FIXME: revisit this when we can custom lower all setcc
2292     // optimizations.
2293     if (C->isAllOnesValue() || C->isNullValue())
2294       return SDValue();
2295   }
2296 
2297   // If we have an integer seteq/setne, turn it into a compare against zero
2298   // by xor'ing the rhs with the lhs, which is faster than setting a
2299   // condition register, reading it back out, and masking the correct bit.  The
2300   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2301   // the result to other bit-twiddling opportunities.
2302   EVT LHSVT = Op.getOperand(0).getValueType();
2303   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2304     EVT VT = Op.getValueType();
2305     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2306                                 Op.getOperand(1));
2307     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2308   }
2309   return SDValue();
2310 }
2311 
2312 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2313                                       const PPCSubtarget &Subtarget) const {
2314   SDNode *Node = Op.getNode();
2315   EVT VT = Node->getValueType(0);
2316   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2317   SDValue InChain = Node->getOperand(0);
2318   SDValue VAListPtr = Node->getOperand(1);
2319   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2320   SDLoc dl(Node);
2321 
2322   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2323 
2324   // gpr_index
2325   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2326                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2327                                     false, false, false, 0);
2328   InChain = GprIndex.getValue(1);
2329 
2330   if (VT == MVT::i64) {
2331     // Check if GprIndex is even
2332     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2333                                  DAG.getConstant(1, dl, MVT::i32));
2334     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2335                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2336     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2337                                           DAG.getConstant(1, dl, MVT::i32));
2338     // Align GprIndex to be even if it isn't
2339     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2340                            GprIndex);
2341   }
2342 
2343   // fpr index is 1 byte after gpr
2344   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2345                                DAG.getConstant(1, dl, MVT::i32));
2346 
2347   // fpr
2348   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2349                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2350                                     false, false, false, 0);
2351   InChain = FprIndex.getValue(1);
2352 
2353   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2354                                        DAG.getConstant(8, dl, MVT::i32));
2355 
2356   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2357                                         DAG.getConstant(4, dl, MVT::i32));
2358 
2359   // areas
2360   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2361                                      MachinePointerInfo(), false, false,
2362                                      false, 0);
2363   InChain = OverflowArea.getValue(1);
2364 
2365   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2366                                     MachinePointerInfo(), false, false,
2367                                     false, 0);
2368   InChain = RegSaveArea.getValue(1);
2369 
2370   // select overflow_area if index > 8
2371   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2372                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2373 
2374   // adjustment constant gpr_index * 4/8
2375   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2376                                     VT.isInteger() ? GprIndex : FprIndex,
2377                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2378                                                     MVT::i32));
2379 
2380   // OurReg = RegSaveArea + RegConstant
2381   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2382                                RegConstant);
2383 
2384   // Floating types are 32 bytes into RegSaveArea
2385   if (VT.isFloatingPoint())
2386     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2387                          DAG.getConstant(32, dl, MVT::i32));
2388 
2389   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2390   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2391                                    VT.isInteger() ? GprIndex : FprIndex,
2392                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2393                                                    MVT::i32));
2394 
2395   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2396                               VT.isInteger() ? VAListPtr : FprPtr,
2397                               MachinePointerInfo(SV),
2398                               MVT::i8, false, false, 0);
2399 
2400   // determine if we should load from reg_save_area or overflow_area
2401   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2402 
2403   // increase overflow_area by 4/8 if gpr/fpr > 8
2404   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2405                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2406                                           dl, MVT::i32));
2407 
2408   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2409                              OverflowAreaPlusN);
2410 
2411   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2412                               OverflowAreaPtr,
2413                               MachinePointerInfo(),
2414                               MVT::i32, false, false, 0);
2415 
2416   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2417                      false, false, false, 0);
2418 }
2419 
2420 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2421                                        const PPCSubtarget &Subtarget) const {
2422   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2423 
2424   // We have to copy the entire va_list struct:
2425   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2426   return DAG.getMemcpy(Op.getOperand(0), Op,
2427                        Op.getOperand(1), Op.getOperand(2),
2428                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2429                        false, MachinePointerInfo(), MachinePointerInfo());
2430 }
2431 
2432 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2433                                                   SelectionDAG &DAG) const {
2434   return Op.getOperand(0);
2435 }
2436 
2437 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2438                                                 SelectionDAG &DAG) const {
2439   SDValue Chain = Op.getOperand(0);
2440   SDValue Trmp = Op.getOperand(1); // trampoline
2441   SDValue FPtr = Op.getOperand(2); // nested function
2442   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2443   SDLoc dl(Op);
2444 
2445   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2446   bool isPPC64 = (PtrVT == MVT::i64);
2447   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2448 
2449   TargetLowering::ArgListTy Args;
2450   TargetLowering::ArgListEntry Entry;
2451 
2452   Entry.Ty = IntPtrTy;
2453   Entry.Node = Trmp; Args.push_back(Entry);
2454 
2455   // TrampSize == (isPPC64 ? 48 : 40);
2456   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2457                                isPPC64 ? MVT::i64 : MVT::i32);
2458   Args.push_back(Entry);
2459 
2460   Entry.Node = FPtr; Args.push_back(Entry);
2461   Entry.Node = Nest; Args.push_back(Entry);
2462 
2463   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2464   TargetLowering::CallLoweringInfo CLI(DAG);
2465   CLI.setDebugLoc(dl).setChain(Chain)
2466     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2467                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2468                std::move(Args), 0);
2469 
2470   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2471   return CallResult.second;
2472 }
2473 
2474 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2475                                         const PPCSubtarget &Subtarget) const {
2476   MachineFunction &MF = DAG.getMachineFunction();
2477   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2478 
2479   SDLoc dl(Op);
2480 
2481   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2482     // vastart just stores the address of the VarArgsFrameIndex slot into the
2483     // memory location argument.
2484     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2485     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2486     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2487     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2488                         MachinePointerInfo(SV),
2489                         false, false, 0);
2490   }
2491 
2492   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2493   // We suppose the given va_list is already allocated.
2494   //
2495   // typedef struct {
2496   //  char gpr;     /* index into the array of 8 GPRs
2497   //                 * stored in the register save area
2498   //                 * gpr=0 corresponds to r3,
2499   //                 * gpr=1 to r4, etc.
2500   //                 */
2501   //  char fpr;     /* index into the array of 8 FPRs
2502   //                 * stored in the register save area
2503   //                 * fpr=0 corresponds to f1,
2504   //                 * fpr=1 to f2, etc.
2505   //                 */
2506   //  char *overflow_arg_area;
2507   //                /* location on stack that holds
2508   //                 * the next overflow argument
2509   //                 */
2510   //  char *reg_save_area;
2511   //               /* where r3:r10 and f1:f8 (if saved)
2512   //                * are stored
2513   //                */
2514   // } va_list[1];
2515 
2516   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2517   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2518 
2519   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2520 
2521   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2522                                             PtrVT);
2523   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2524                                  PtrVT);
2525 
2526   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2527   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2528 
2529   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2530   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2531 
2532   uint64_t FPROffset = 1;
2533   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2534 
2535   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2536 
2537   // Store first byte : number of int regs
2538   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2539                                          Op.getOperand(1),
2540                                          MachinePointerInfo(SV),
2541                                          MVT::i8, false, false, 0);
2542   uint64_t nextOffset = FPROffset;
2543   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2544                                   ConstFPROffset);
2545 
2546   // Store second byte : number of float regs
2547   SDValue secondStore =
2548     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2549                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2550                       false, false, 0);
2551   nextOffset += StackOffset;
2552   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2553 
2554   // Store second word : arguments given on stack
2555   SDValue thirdStore =
2556     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2557                  MachinePointerInfo(SV, nextOffset),
2558                  false, false, 0);
2559   nextOffset += FrameOffset;
2560   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2561 
2562   // Store third word : arguments given in registers
2563   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2564                       MachinePointerInfo(SV, nextOffset),
2565                       false, false, 0);
2566 
2567 }
2568 
2569 #include "PPCGenCallingConv.inc"
2570 
2571 // Function whose sole purpose is to kill compiler warnings
2572 // stemming from unused functions included from PPCGenCallingConv.inc.
2573 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2574   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2575 }
2576 
2577 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2578                                       CCValAssign::LocInfo &LocInfo,
2579                                       ISD::ArgFlagsTy &ArgFlags,
2580                                       CCState &State) {
2581   return true;
2582 }
2583 
2584 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2585                                              MVT &LocVT,
2586                                              CCValAssign::LocInfo &LocInfo,
2587                                              ISD::ArgFlagsTy &ArgFlags,
2588                                              CCState &State) {
2589   static const MCPhysReg ArgRegs[] = {
2590     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2591     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2592   };
2593   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2594 
2595   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2596 
2597   // Skip one register if the first unallocated register has an even register
2598   // number and there are still argument registers available which have not been
2599   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2600   // need to skip a register if RegNum is odd.
2601   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2602     State.AllocateReg(ArgRegs[RegNum]);
2603   }
2604 
2605   // Always return false here, as this function only makes sure that the first
2606   // unallocated register has an odd register number and does not actually
2607   // allocate a register for the current argument.
2608   return false;
2609 }
2610 
2611 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2612                                                MVT &LocVT,
2613                                                CCValAssign::LocInfo &LocInfo,
2614                                                ISD::ArgFlagsTy &ArgFlags,
2615                                                CCState &State) {
2616   static const MCPhysReg ArgRegs[] = {
2617     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2618     PPC::F8
2619   };
2620 
2621   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2622 
2623   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2624 
2625   // If there is only one Floating-point register left we need to put both f64
2626   // values of a split ppc_fp128 value on the stack.
2627   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2628     State.AllocateReg(ArgRegs[RegNum]);
2629   }
2630 
2631   // Always return false here, as this function only makes sure that the two f64
2632   // values a ppc_fp128 value is split into are both passed in registers or both
2633   // passed on the stack and does not actually allocate a register for the
2634   // current argument.
2635   return false;
2636 }
2637 
2638 /// FPR - The set of FP registers that should be allocated for arguments,
2639 /// on Darwin.
2640 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2641                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2642                                 PPC::F11, PPC::F12, PPC::F13};
2643 
2644 /// QFPR - The set of QPX registers that should be allocated for arguments.
2645 static const MCPhysReg QFPR[] = {
2646     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2647     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2648 
2649 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2650 /// the stack.
2651 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2652                                        unsigned PtrByteSize) {
2653   unsigned ArgSize = ArgVT.getStoreSize();
2654   if (Flags.isByVal())
2655     ArgSize = Flags.getByValSize();
2656 
2657   // Round up to multiples of the pointer size, except for array members,
2658   // which are always packed.
2659   if (!Flags.isInConsecutiveRegs())
2660     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2661 
2662   return ArgSize;
2663 }
2664 
2665 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2666 /// on the stack.
2667 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2668                                             ISD::ArgFlagsTy Flags,
2669                                             unsigned PtrByteSize) {
2670   unsigned Align = PtrByteSize;
2671 
2672   // Altivec parameters are padded to a 16 byte boundary.
2673   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2674       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2675       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2676       ArgVT == MVT::v1i128)
2677     Align = 16;
2678   // QPX vector types stored in double-precision are padded to a 32 byte
2679   // boundary.
2680   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2681     Align = 32;
2682 
2683   // ByVal parameters are aligned as requested.
2684   if (Flags.isByVal()) {
2685     unsigned BVAlign = Flags.getByValAlign();
2686     if (BVAlign > PtrByteSize) {
2687       if (BVAlign % PtrByteSize != 0)
2688           llvm_unreachable(
2689             "ByVal alignment is not a multiple of the pointer size");
2690 
2691       Align = BVAlign;
2692     }
2693   }
2694 
2695   // Array members are always packed to their original alignment.
2696   if (Flags.isInConsecutiveRegs()) {
2697     // If the array member was split into multiple registers, the first
2698     // needs to be aligned to the size of the full type.  (Except for
2699     // ppcf128, which is only aligned as its f64 components.)
2700     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2701       Align = OrigVT.getStoreSize();
2702     else
2703       Align = ArgVT.getStoreSize();
2704   }
2705 
2706   return Align;
2707 }
2708 
2709 /// CalculateStackSlotUsed - Return whether this argument will use its
2710 /// stack slot (instead of being passed in registers).  ArgOffset,
2711 /// AvailableFPRs, and AvailableVRs must hold the current argument
2712 /// position, and will be updated to account for this argument.
2713 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2714                                    ISD::ArgFlagsTy Flags,
2715                                    unsigned PtrByteSize,
2716                                    unsigned LinkageSize,
2717                                    unsigned ParamAreaSize,
2718                                    unsigned &ArgOffset,
2719                                    unsigned &AvailableFPRs,
2720                                    unsigned &AvailableVRs, bool HasQPX) {
2721   bool UseMemory = false;
2722 
2723   // Respect alignment of argument on the stack.
2724   unsigned Align =
2725     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2726   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2727   // If there's no space left in the argument save area, we must
2728   // use memory (this check also catches zero-sized arguments).
2729   if (ArgOffset >= LinkageSize + ParamAreaSize)
2730     UseMemory = true;
2731 
2732   // Allocate argument on the stack.
2733   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2734   if (Flags.isInConsecutiveRegsLast())
2735     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2736   // If we overran the argument save area, we must use memory
2737   // (this check catches arguments passed partially in memory)
2738   if (ArgOffset > LinkageSize + ParamAreaSize)
2739     UseMemory = true;
2740 
2741   // However, if the argument is actually passed in an FPR or a VR,
2742   // we don't use memory after all.
2743   if (!Flags.isByVal()) {
2744     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2745         // QPX registers overlap with the scalar FP registers.
2746         (HasQPX && (ArgVT == MVT::v4f32 ||
2747                     ArgVT == MVT::v4f64 ||
2748                     ArgVT == MVT::v4i1)))
2749       if (AvailableFPRs > 0) {
2750         --AvailableFPRs;
2751         return false;
2752       }
2753     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2754         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2755         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2756         ArgVT == MVT::v1i128)
2757       if (AvailableVRs > 0) {
2758         --AvailableVRs;
2759         return false;
2760       }
2761   }
2762 
2763   return UseMemory;
2764 }
2765 
2766 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2767 /// ensure minimum alignment required for target.
2768 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2769                                      unsigned NumBytes) {
2770   unsigned TargetAlign = Lowering->getStackAlignment();
2771   unsigned AlignMask = TargetAlign - 1;
2772   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2773   return NumBytes;
2774 }
2775 
2776 SDValue PPCTargetLowering::LowerFormalArguments(
2777     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2778     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2779     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2780   if (Subtarget.isSVR4ABI()) {
2781     if (Subtarget.isPPC64())
2782       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2783                                          dl, DAG, InVals);
2784     else
2785       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2786                                          dl, DAG, InVals);
2787   } else {
2788     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2789                                        dl, DAG, InVals);
2790   }
2791 }
2792 
2793 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2794     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2795     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2796     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2797 
2798   // 32-bit SVR4 ABI Stack Frame Layout:
2799   //              +-----------------------------------+
2800   //        +-->  |            Back chain             |
2801   //        |     +-----------------------------------+
2802   //        |     | Floating-point register save area |
2803   //        |     +-----------------------------------+
2804   //        |     |    General register save area     |
2805   //        |     +-----------------------------------+
2806   //        |     |          CR save word             |
2807   //        |     +-----------------------------------+
2808   //        |     |         VRSAVE save word          |
2809   //        |     +-----------------------------------+
2810   //        |     |         Alignment padding         |
2811   //        |     +-----------------------------------+
2812   //        |     |     Vector register save area     |
2813   //        |     +-----------------------------------+
2814   //        |     |       Local variable space        |
2815   //        |     +-----------------------------------+
2816   //        |     |        Parameter list area        |
2817   //        |     +-----------------------------------+
2818   //        |     |           LR save word            |
2819   //        |     +-----------------------------------+
2820   // SP-->  +---  |            Back chain             |
2821   //              +-----------------------------------+
2822   //
2823   // Specifications:
2824   //   System V Application Binary Interface PowerPC Processor Supplement
2825   //   AltiVec Technology Programming Interface Manual
2826 
2827   MachineFunction &MF = DAG.getMachineFunction();
2828   MachineFrameInfo *MFI = MF.getFrameInfo();
2829   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2830 
2831   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2832   // Potential tail calls could cause overwriting of argument stack slots.
2833   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2834                        (CallConv == CallingConv::Fast));
2835   unsigned PtrByteSize = 4;
2836 
2837   // Assign locations to all of the incoming arguments.
2838   SmallVector<CCValAssign, 16> ArgLocs;
2839   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2840                  *DAG.getContext());
2841 
2842   // Reserve space for the linkage area on the stack.
2843   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2844   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2845   if (Subtarget.useSoftFloat())
2846     CCInfo.PreAnalyzeFormalArguments(Ins);
2847 
2848   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2849   CCInfo.clearWasPPCF128();
2850 
2851   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2852     CCValAssign &VA = ArgLocs[i];
2853 
2854     // Arguments stored in registers.
2855     if (VA.isRegLoc()) {
2856       const TargetRegisterClass *RC;
2857       EVT ValVT = VA.getValVT();
2858 
2859       switch (ValVT.getSimpleVT().SimpleTy) {
2860         default:
2861           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2862         case MVT::i1:
2863         case MVT::i32:
2864           RC = &PPC::GPRCRegClass;
2865           break;
2866         case MVT::f32:
2867           if (Subtarget.hasP8Vector())
2868             RC = &PPC::VSSRCRegClass;
2869           else
2870             RC = &PPC::F4RCRegClass;
2871           break;
2872         case MVT::f64:
2873           if (Subtarget.hasVSX())
2874             RC = &PPC::VSFRCRegClass;
2875           else
2876             RC = &PPC::F8RCRegClass;
2877           break;
2878         case MVT::v16i8:
2879         case MVT::v8i16:
2880         case MVT::v4i32:
2881           RC = &PPC::VRRCRegClass;
2882           break;
2883         case MVT::v4f32:
2884           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2885           break;
2886         case MVT::v2f64:
2887         case MVT::v2i64:
2888           RC = &PPC::VSHRCRegClass;
2889           break;
2890         case MVT::v4f64:
2891           RC = &PPC::QFRCRegClass;
2892           break;
2893         case MVT::v4i1:
2894           RC = &PPC::QBRCRegClass;
2895           break;
2896       }
2897 
2898       // Transform the arguments stored in physical registers into virtual ones.
2899       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2900       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2901                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2902 
2903       if (ValVT == MVT::i1)
2904         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2905 
2906       InVals.push_back(ArgValue);
2907     } else {
2908       // Argument stored in memory.
2909       assert(VA.isMemLoc());
2910 
2911       unsigned ArgSize = VA.getLocVT().getStoreSize();
2912       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2913                                       isImmutable);
2914 
2915       // Create load nodes to retrieve arguments from the stack.
2916       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2917       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2918                                    MachinePointerInfo(),
2919                                    false, false, false, 0));
2920     }
2921   }
2922 
2923   // Assign locations to all of the incoming aggregate by value arguments.
2924   // Aggregates passed by value are stored in the local variable space of the
2925   // caller's stack frame, right above the parameter list area.
2926   SmallVector<CCValAssign, 16> ByValArgLocs;
2927   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2928                       ByValArgLocs, *DAG.getContext());
2929 
2930   // Reserve stack space for the allocations in CCInfo.
2931   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2932 
2933   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2934 
2935   // Area that is at least reserved in the caller of this function.
2936   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2937   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2938 
2939   // Set the size that is at least reserved in caller of this function.  Tail
2940   // call optimized function's reserved stack space needs to be aligned so that
2941   // taking the difference between two stack areas will result in an aligned
2942   // stack.
2943   MinReservedArea =
2944       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2945   FuncInfo->setMinReservedArea(MinReservedArea);
2946 
2947   SmallVector<SDValue, 8> MemOps;
2948 
2949   // If the function takes variable number of arguments, make a frame index for
2950   // the start of the first vararg value... for expansion of llvm.va_start.
2951   if (isVarArg) {
2952     static const MCPhysReg GPArgRegs[] = {
2953       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2954       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2955     };
2956     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2957 
2958     static const MCPhysReg FPArgRegs[] = {
2959       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2960       PPC::F8
2961     };
2962     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2963 
2964     if (Subtarget.useSoftFloat())
2965        NumFPArgRegs = 0;
2966 
2967     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2968     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2969 
2970     // Make room for NumGPArgRegs and NumFPArgRegs.
2971     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2972                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2973 
2974     FuncInfo->setVarArgsStackOffset(
2975       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2976                              CCInfo.getNextStackOffset(), true));
2977 
2978     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2979     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2980 
2981     // The fixed integer arguments of a variadic function are stored to the
2982     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2983     // the result of va_next.
2984     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2985       // Get an existing live-in vreg, or add a new one.
2986       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2987       if (!VReg)
2988         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2989 
2990       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2991       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2992                                    MachinePointerInfo(), false, false, 0);
2993       MemOps.push_back(Store);
2994       // Increment the address by four for the next argument to store
2995       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2996       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2997     }
2998 
2999     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3000     // is set.
3001     // The double arguments are stored to the VarArgsFrameIndex
3002     // on the stack.
3003     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3004       // Get an existing live-in vreg, or add a new one.
3005       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3006       if (!VReg)
3007         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3008 
3009       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3010       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3011                                    MachinePointerInfo(), false, false, 0);
3012       MemOps.push_back(Store);
3013       // Increment the address by eight for the next argument to store
3014       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3015                                          PtrVT);
3016       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3017     }
3018   }
3019 
3020   if (!MemOps.empty())
3021     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3022 
3023   return Chain;
3024 }
3025 
3026 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3027 // value to MVT::i64 and then truncate to the correct register size.
3028 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3029                                              EVT ObjectVT, SelectionDAG &DAG,
3030                                              SDValue ArgVal,
3031                                              const SDLoc &dl) const {
3032   if (Flags.isSExt())
3033     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3034                          DAG.getValueType(ObjectVT));
3035   else if (Flags.isZExt())
3036     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3037                          DAG.getValueType(ObjectVT));
3038 
3039   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3040 }
3041 
3042 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3043     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3044     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3045     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3046   // TODO: add description of PPC stack frame format, or at least some docs.
3047   //
3048   bool isELFv2ABI = Subtarget.isELFv2ABI();
3049   bool isLittleEndian = Subtarget.isLittleEndian();
3050   MachineFunction &MF = DAG.getMachineFunction();
3051   MachineFrameInfo *MFI = MF.getFrameInfo();
3052   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3053 
3054   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3055          "fastcc not supported on varargs functions");
3056 
3057   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3058   // Potential tail calls could cause overwriting of argument stack slots.
3059   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3060                        (CallConv == CallingConv::Fast));
3061   unsigned PtrByteSize = 8;
3062   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3063 
3064   static const MCPhysReg GPR[] = {
3065     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3066     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3067   };
3068   static const MCPhysReg VR[] = {
3069     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3070     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3071   };
3072   static const MCPhysReg VSRH[] = {
3073     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3074     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3075   };
3076 
3077   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3078   const unsigned Num_FPR_Regs = 13;
3079   const unsigned Num_VR_Regs  = array_lengthof(VR);
3080   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3081 
3082   // Do a first pass over the arguments to determine whether the ABI
3083   // guarantees that our caller has allocated the parameter save area
3084   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3085   // in the ELFv2 ABI, it is true if this is a vararg function or if
3086   // any parameter is located in a stack slot.
3087 
3088   bool HasParameterArea = !isELFv2ABI || isVarArg;
3089   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3090   unsigned NumBytes = LinkageSize;
3091   unsigned AvailableFPRs = Num_FPR_Regs;
3092   unsigned AvailableVRs = Num_VR_Regs;
3093   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3094     if (Ins[i].Flags.isNest())
3095       continue;
3096 
3097     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3098                                PtrByteSize, LinkageSize, ParamAreaSize,
3099                                NumBytes, AvailableFPRs, AvailableVRs,
3100                                Subtarget.hasQPX()))
3101       HasParameterArea = true;
3102   }
3103 
3104   // Add DAG nodes to load the arguments or copy them out of registers.  On
3105   // entry to a function on PPC, the arguments start after the linkage area,
3106   // although the first ones are often in registers.
3107 
3108   unsigned ArgOffset = LinkageSize;
3109   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3110   unsigned &QFPR_idx = FPR_idx;
3111   SmallVector<SDValue, 8> MemOps;
3112   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3113   unsigned CurArgIdx = 0;
3114   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3115     SDValue ArgVal;
3116     bool needsLoad = false;
3117     EVT ObjectVT = Ins[ArgNo].VT;
3118     EVT OrigVT = Ins[ArgNo].ArgVT;
3119     unsigned ObjSize = ObjectVT.getStoreSize();
3120     unsigned ArgSize = ObjSize;
3121     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3122     if (Ins[ArgNo].isOrigArg()) {
3123       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3124       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3125     }
3126     // We re-align the argument offset for each argument, except when using the
3127     // fast calling convention, when we need to make sure we do that only when
3128     // we'll actually use a stack slot.
3129     unsigned CurArgOffset, Align;
3130     auto ComputeArgOffset = [&]() {
3131       /* Respect alignment of argument on the stack.  */
3132       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3133       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3134       CurArgOffset = ArgOffset;
3135     };
3136 
3137     if (CallConv != CallingConv::Fast) {
3138       ComputeArgOffset();
3139 
3140       /* Compute GPR index associated with argument offset.  */
3141       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3142       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3143     }
3144 
3145     // FIXME the codegen can be much improved in some cases.
3146     // We do not have to keep everything in memory.
3147     if (Flags.isByVal()) {
3148       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3149 
3150       if (CallConv == CallingConv::Fast)
3151         ComputeArgOffset();
3152 
3153       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3154       ObjSize = Flags.getByValSize();
3155       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3156       // Empty aggregate parameters do not take up registers.  Examples:
3157       //   struct { } a;
3158       //   union  { } b;
3159       //   int c[0];
3160       // etc.  However, we have to provide a place-holder in InVals, so
3161       // pretend we have an 8-byte item at the current address for that
3162       // purpose.
3163       if (!ObjSize) {
3164         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3165         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3166         InVals.push_back(FIN);
3167         continue;
3168       }
3169 
3170       // Create a stack object covering all stack doublewords occupied
3171       // by the argument.  If the argument is (fully or partially) on
3172       // the stack, or if the argument is fully in registers but the
3173       // caller has allocated the parameter save anyway, we can refer
3174       // directly to the caller's stack frame.  Otherwise, create a
3175       // local copy in our own frame.
3176       int FI;
3177       if (HasParameterArea ||
3178           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3179         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3180       else
3181         FI = MFI->CreateStackObject(ArgSize, Align, false);
3182       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3183 
3184       // Handle aggregates smaller than 8 bytes.
3185       if (ObjSize < PtrByteSize) {
3186         // The value of the object is its address, which differs from the
3187         // address of the enclosing doubleword on big-endian systems.
3188         SDValue Arg = FIN;
3189         if (!isLittleEndian) {
3190           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3191           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3192         }
3193         InVals.push_back(Arg);
3194 
3195         if (GPR_idx != Num_GPR_Regs) {
3196           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3197           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3198           SDValue Store;
3199 
3200           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3201             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3202                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3203             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3204                                       MachinePointerInfo(&*FuncArg), ObjType,
3205                                       false, false, 0);
3206           } else {
3207             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3208             // store the whole register as-is to the parameter save area
3209             // slot.
3210             Store =
3211                 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3212                              MachinePointerInfo(&*FuncArg), false, false, 0);
3213           }
3214 
3215           MemOps.push_back(Store);
3216         }
3217         // Whether we copied from a register or not, advance the offset
3218         // into the parameter save area by a full doubleword.
3219         ArgOffset += PtrByteSize;
3220         continue;
3221       }
3222 
3223       // The value of the object is its address, which is the address of
3224       // its first stack doubleword.
3225       InVals.push_back(FIN);
3226 
3227       // Store whatever pieces of the object are in registers to memory.
3228       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3229         if (GPR_idx == Num_GPR_Regs)
3230           break;
3231 
3232         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3233         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3234         SDValue Addr = FIN;
3235         if (j) {
3236           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3237           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3238         }
3239         SDValue Store =
3240             DAG.getStore(Val.getValue(1), dl, Val, Addr,
3241                          MachinePointerInfo(&*FuncArg, j), false, false, 0);
3242         MemOps.push_back(Store);
3243         ++GPR_idx;
3244       }
3245       ArgOffset += ArgSize;
3246       continue;
3247     }
3248 
3249     switch (ObjectVT.getSimpleVT().SimpleTy) {
3250     default: llvm_unreachable("Unhandled argument type!");
3251     case MVT::i1:
3252     case MVT::i32:
3253     case MVT::i64:
3254       if (Flags.isNest()) {
3255         // The 'nest' parameter, if any, is passed in R11.
3256         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3257         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3258 
3259         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3260           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3261 
3262         break;
3263       }
3264 
3265       // These can be scalar arguments or elements of an integer array type
3266       // passed directly.  Clang may use those instead of "byval" aggregate
3267       // types to avoid forcing arguments to memory unnecessarily.
3268       if (GPR_idx != Num_GPR_Regs) {
3269         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3270         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3271 
3272         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3273           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3274           // value to MVT::i64 and then truncate to the correct register size.
3275           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3276       } else {
3277         if (CallConv == CallingConv::Fast)
3278           ComputeArgOffset();
3279 
3280         needsLoad = true;
3281         ArgSize = PtrByteSize;
3282       }
3283       if (CallConv != CallingConv::Fast || needsLoad)
3284         ArgOffset += 8;
3285       break;
3286 
3287     case MVT::f32:
3288     case MVT::f64:
3289       // These can be scalar arguments or elements of a float array type
3290       // passed directly.  The latter are used to implement ELFv2 homogenous
3291       // float aggregates.
3292       if (FPR_idx != Num_FPR_Regs) {
3293         unsigned VReg;
3294 
3295         if (ObjectVT == MVT::f32)
3296           VReg = MF.addLiveIn(FPR[FPR_idx],
3297                               Subtarget.hasP8Vector()
3298                                   ? &PPC::VSSRCRegClass
3299                                   : &PPC::F4RCRegClass);
3300         else
3301           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3302                                                 ? &PPC::VSFRCRegClass
3303                                                 : &PPC::F8RCRegClass);
3304 
3305         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3306         ++FPR_idx;
3307       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3308         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3309         // once we support fp <-> gpr moves.
3310 
3311         // This can only ever happen in the presence of f32 array types,
3312         // since otherwise we never run out of FPRs before running out
3313         // of GPRs.
3314         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3315         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3316 
3317         if (ObjectVT == MVT::f32) {
3318           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3319             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3320                                  DAG.getConstant(32, dl, MVT::i32));
3321           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3322         }
3323 
3324         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3325       } else {
3326         if (CallConv == CallingConv::Fast)
3327           ComputeArgOffset();
3328 
3329         needsLoad = true;
3330       }
3331 
3332       // When passing an array of floats, the array occupies consecutive
3333       // space in the argument area; only round up to the next doubleword
3334       // at the end of the array.  Otherwise, each float takes 8 bytes.
3335       if (CallConv != CallingConv::Fast || needsLoad) {
3336         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3337         ArgOffset += ArgSize;
3338         if (Flags.isInConsecutiveRegsLast())
3339           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3340       }
3341       break;
3342     case MVT::v4f32:
3343     case MVT::v4i32:
3344     case MVT::v8i16:
3345     case MVT::v16i8:
3346     case MVT::v2f64:
3347     case MVT::v2i64:
3348     case MVT::v1i128:
3349       if (!Subtarget.hasQPX()) {
3350       // These can be scalar arguments or elements of a vector array type
3351       // passed directly.  The latter are used to implement ELFv2 homogenous
3352       // vector aggregates.
3353       if (VR_idx != Num_VR_Regs) {
3354         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3355                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3356                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3357         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3358         ++VR_idx;
3359       } else {
3360         if (CallConv == CallingConv::Fast)
3361           ComputeArgOffset();
3362 
3363         needsLoad = true;
3364       }
3365       if (CallConv != CallingConv::Fast || needsLoad)
3366         ArgOffset += 16;
3367       break;
3368       } // not QPX
3369 
3370       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3371              "Invalid QPX parameter type");
3372       /* fall through */
3373 
3374     case MVT::v4f64:
3375     case MVT::v4i1:
3376       // QPX vectors are treated like their scalar floating-point subregisters
3377       // (except that they're larger).
3378       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3379       if (QFPR_idx != Num_QFPR_Regs) {
3380         const TargetRegisterClass *RC;
3381         switch (ObjectVT.getSimpleVT().SimpleTy) {
3382         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3383         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3384         default:         RC = &PPC::QBRCRegClass; break;
3385         }
3386 
3387         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3388         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3389         ++QFPR_idx;
3390       } else {
3391         if (CallConv == CallingConv::Fast)
3392           ComputeArgOffset();
3393         needsLoad = true;
3394       }
3395       if (CallConv != CallingConv::Fast || needsLoad)
3396         ArgOffset += Sz;
3397       break;
3398     }
3399 
3400     // We need to load the argument to a virtual register if we determined
3401     // above that we ran out of physical registers of the appropriate type.
3402     if (needsLoad) {
3403       if (ObjSize < ArgSize && !isLittleEndian)
3404         CurArgOffset += ArgSize - ObjSize;
3405       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3406       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3407       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3408                            false, false, false, 0);
3409     }
3410 
3411     InVals.push_back(ArgVal);
3412   }
3413 
3414   // Area that is at least reserved in the caller of this function.
3415   unsigned MinReservedArea;
3416   if (HasParameterArea)
3417     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3418   else
3419     MinReservedArea = LinkageSize;
3420 
3421   // Set the size that is at least reserved in caller of this function.  Tail
3422   // call optimized functions' reserved stack space needs to be aligned so that
3423   // taking the difference between two stack areas will result in an aligned
3424   // stack.
3425   MinReservedArea =
3426       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3427   FuncInfo->setMinReservedArea(MinReservedArea);
3428 
3429   // If the function takes variable number of arguments, make a frame index for
3430   // the start of the first vararg value... for expansion of llvm.va_start.
3431   if (isVarArg) {
3432     int Depth = ArgOffset;
3433 
3434     FuncInfo->setVarArgsFrameIndex(
3435       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3436     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3437 
3438     // If this function is vararg, store any remaining integer argument regs
3439     // to their spots on the stack so that they may be loaded by deferencing the
3440     // result of va_next.
3441     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3442          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3443       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3444       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3445       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3446                                    MachinePointerInfo(), false, false, 0);
3447       MemOps.push_back(Store);
3448       // Increment the address by four for the next argument to store
3449       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3450       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3451     }
3452   }
3453 
3454   if (!MemOps.empty())
3455     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3456 
3457   return Chain;
3458 }
3459 
3460 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3461     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3462     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3463     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3464   // TODO: add description of PPC stack frame format, or at least some docs.
3465   //
3466   MachineFunction &MF = DAG.getMachineFunction();
3467   MachineFrameInfo *MFI = MF.getFrameInfo();
3468   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3469 
3470   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3471   bool isPPC64 = PtrVT == MVT::i64;
3472   // Potential tail calls could cause overwriting of argument stack slots.
3473   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3474                        (CallConv == CallingConv::Fast));
3475   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3476   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3477   unsigned ArgOffset = LinkageSize;
3478   // Area that is at least reserved in caller of this function.
3479   unsigned MinReservedArea = ArgOffset;
3480 
3481   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3482     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3483     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3484   };
3485   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3486     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3487     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3488   };
3489   static const MCPhysReg VR[] = {
3490     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3491     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3492   };
3493 
3494   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3495   const unsigned Num_FPR_Regs = 13;
3496   const unsigned Num_VR_Regs  = array_lengthof( VR);
3497 
3498   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3499 
3500   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3501 
3502   // In 32-bit non-varargs functions, the stack space for vectors is after the
3503   // stack space for non-vectors.  We do not use this space unless we have
3504   // too many vectors to fit in registers, something that only occurs in
3505   // constructed examples:), but we have to walk the arglist to figure
3506   // that out...for the pathological case, compute VecArgOffset as the
3507   // start of the vector parameter area.  Computing VecArgOffset is the
3508   // entire point of the following loop.
3509   unsigned VecArgOffset = ArgOffset;
3510   if (!isVarArg && !isPPC64) {
3511     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3512          ++ArgNo) {
3513       EVT ObjectVT = Ins[ArgNo].VT;
3514       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3515 
3516       if (Flags.isByVal()) {
3517         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3518         unsigned ObjSize = Flags.getByValSize();
3519         unsigned ArgSize =
3520                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3521         VecArgOffset += ArgSize;
3522         continue;
3523       }
3524 
3525       switch(ObjectVT.getSimpleVT().SimpleTy) {
3526       default: llvm_unreachable("Unhandled argument type!");
3527       case MVT::i1:
3528       case MVT::i32:
3529       case MVT::f32:
3530         VecArgOffset += 4;
3531         break;
3532       case MVT::i64:  // PPC64
3533       case MVT::f64:
3534         // FIXME: We are guaranteed to be !isPPC64 at this point.
3535         // Does MVT::i64 apply?
3536         VecArgOffset += 8;
3537         break;
3538       case MVT::v4f32:
3539       case MVT::v4i32:
3540       case MVT::v8i16:
3541       case MVT::v16i8:
3542         // Nothing to do, we're only looking at Nonvector args here.
3543         break;
3544       }
3545     }
3546   }
3547   // We've found where the vector parameter area in memory is.  Skip the
3548   // first 12 parameters; these don't use that memory.
3549   VecArgOffset = ((VecArgOffset+15)/16)*16;
3550   VecArgOffset += 12*16;
3551 
3552   // Add DAG nodes to load the arguments or copy them out of registers.  On
3553   // entry to a function on PPC, the arguments start after the linkage area,
3554   // although the first ones are often in registers.
3555 
3556   SmallVector<SDValue, 8> MemOps;
3557   unsigned nAltivecParamsAtEnd = 0;
3558   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3559   unsigned CurArgIdx = 0;
3560   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3561     SDValue ArgVal;
3562     bool needsLoad = false;
3563     EVT ObjectVT = Ins[ArgNo].VT;
3564     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3565     unsigned ArgSize = ObjSize;
3566     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3567     if (Ins[ArgNo].isOrigArg()) {
3568       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3569       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3570     }
3571     unsigned CurArgOffset = ArgOffset;
3572 
3573     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3574     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3575         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3576       if (isVarArg || isPPC64) {
3577         MinReservedArea = ((MinReservedArea+15)/16)*16;
3578         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3579                                                   Flags,
3580                                                   PtrByteSize);
3581       } else  nAltivecParamsAtEnd++;
3582     } else
3583       // Calculate min reserved area.
3584       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3585                                                 Flags,
3586                                                 PtrByteSize);
3587 
3588     // FIXME the codegen can be much improved in some cases.
3589     // We do not have to keep everything in memory.
3590     if (Flags.isByVal()) {
3591       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3592 
3593       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3594       ObjSize = Flags.getByValSize();
3595       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3596       // Objects of size 1 and 2 are right justified, everything else is
3597       // left justified.  This means the memory address is adjusted forwards.
3598       if (ObjSize==1 || ObjSize==2) {
3599         CurArgOffset = CurArgOffset + (4 - ObjSize);
3600       }
3601       // The value of the object is its address.
3602       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3603       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3604       InVals.push_back(FIN);
3605       if (ObjSize==1 || ObjSize==2) {
3606         if (GPR_idx != Num_GPR_Regs) {
3607           unsigned VReg;
3608           if (isPPC64)
3609             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3610           else
3611             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3612           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3613           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3614           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3615                                             MachinePointerInfo(&*FuncArg),
3616                                             ObjType, false, false, 0);
3617           MemOps.push_back(Store);
3618           ++GPR_idx;
3619         }
3620 
3621         ArgOffset += PtrByteSize;
3622 
3623         continue;
3624       }
3625       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3626         // Store whatever pieces of the object are in registers
3627         // to memory.  ArgOffset will be the address of the beginning
3628         // of the object.
3629         if (GPR_idx != Num_GPR_Regs) {
3630           unsigned VReg;
3631           if (isPPC64)
3632             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3633           else
3634             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3635           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3636           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3637           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3638           SDValue Store =
3639               DAG.getStore(Val.getValue(1), dl, Val, FIN,
3640                            MachinePointerInfo(&*FuncArg, j), false, false, 0);
3641           MemOps.push_back(Store);
3642           ++GPR_idx;
3643           ArgOffset += PtrByteSize;
3644         } else {
3645           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3646           break;
3647         }
3648       }
3649       continue;
3650     }
3651 
3652     switch (ObjectVT.getSimpleVT().SimpleTy) {
3653     default: llvm_unreachable("Unhandled argument type!");
3654     case MVT::i1:
3655     case MVT::i32:
3656       if (!isPPC64) {
3657         if (GPR_idx != Num_GPR_Regs) {
3658           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3659           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3660 
3661           if (ObjectVT == MVT::i1)
3662             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3663 
3664           ++GPR_idx;
3665         } else {
3666           needsLoad = true;
3667           ArgSize = PtrByteSize;
3668         }
3669         // All int arguments reserve stack space in the Darwin ABI.
3670         ArgOffset += PtrByteSize;
3671         break;
3672       }
3673       // FALLTHROUGH
3674     case MVT::i64:  // PPC64
3675       if (GPR_idx != Num_GPR_Regs) {
3676         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3677         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3678 
3679         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3680           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3681           // value to MVT::i64 and then truncate to the correct register size.
3682           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3683 
3684         ++GPR_idx;
3685       } else {
3686         needsLoad = true;
3687         ArgSize = PtrByteSize;
3688       }
3689       // All int arguments reserve stack space in the Darwin ABI.
3690       ArgOffset += 8;
3691       break;
3692 
3693     case MVT::f32:
3694     case MVT::f64:
3695       // Every 4 bytes of argument space consumes one of the GPRs available for
3696       // argument passing.
3697       if (GPR_idx != Num_GPR_Regs) {
3698         ++GPR_idx;
3699         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3700           ++GPR_idx;
3701       }
3702       if (FPR_idx != Num_FPR_Regs) {
3703         unsigned VReg;
3704 
3705         if (ObjectVT == MVT::f32)
3706           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3707         else
3708           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3709 
3710         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3711         ++FPR_idx;
3712       } else {
3713         needsLoad = true;
3714       }
3715 
3716       // All FP arguments reserve stack space in the Darwin ABI.
3717       ArgOffset += isPPC64 ? 8 : ObjSize;
3718       break;
3719     case MVT::v4f32:
3720     case MVT::v4i32:
3721     case MVT::v8i16:
3722     case MVT::v16i8:
3723       // Note that vector arguments in registers don't reserve stack space,
3724       // except in varargs functions.
3725       if (VR_idx != Num_VR_Regs) {
3726         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3727         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3728         if (isVarArg) {
3729           while ((ArgOffset % 16) != 0) {
3730             ArgOffset += PtrByteSize;
3731             if (GPR_idx != Num_GPR_Regs)
3732               GPR_idx++;
3733           }
3734           ArgOffset += 16;
3735           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3736         }
3737         ++VR_idx;
3738       } else {
3739         if (!isVarArg && !isPPC64) {
3740           // Vectors go after all the nonvectors.
3741           CurArgOffset = VecArgOffset;
3742           VecArgOffset += 16;
3743         } else {
3744           // Vectors are aligned.
3745           ArgOffset = ((ArgOffset+15)/16)*16;
3746           CurArgOffset = ArgOffset;
3747           ArgOffset += 16;
3748         }
3749         needsLoad = true;
3750       }
3751       break;
3752     }
3753 
3754     // We need to load the argument to a virtual register if we determined above
3755     // that we ran out of physical registers of the appropriate type.
3756     if (needsLoad) {
3757       int FI = MFI->CreateFixedObject(ObjSize,
3758                                       CurArgOffset + (ArgSize - ObjSize),
3759                                       isImmutable);
3760       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3761       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3762                            false, false, false, 0);
3763     }
3764 
3765     InVals.push_back(ArgVal);
3766   }
3767 
3768   // Allow for Altivec parameters at the end, if needed.
3769   if (nAltivecParamsAtEnd) {
3770     MinReservedArea = ((MinReservedArea+15)/16)*16;
3771     MinReservedArea += 16*nAltivecParamsAtEnd;
3772   }
3773 
3774   // Area that is at least reserved in the caller of this function.
3775   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3776 
3777   // Set the size that is at least reserved in caller of this function.  Tail
3778   // call optimized functions' reserved stack space needs to be aligned so that
3779   // taking the difference between two stack areas will result in an aligned
3780   // stack.
3781   MinReservedArea =
3782       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3783   FuncInfo->setMinReservedArea(MinReservedArea);
3784 
3785   // If the function takes variable number of arguments, make a frame index for
3786   // the start of the first vararg value... for expansion of llvm.va_start.
3787   if (isVarArg) {
3788     int Depth = ArgOffset;
3789 
3790     FuncInfo->setVarArgsFrameIndex(
3791       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3792                              Depth, true));
3793     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3794 
3795     // If this function is vararg, store any remaining integer argument regs
3796     // to their spots on the stack so that they may be loaded by deferencing the
3797     // result of va_next.
3798     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3799       unsigned VReg;
3800 
3801       if (isPPC64)
3802         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3803       else
3804         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3805 
3806       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3807       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3808                                    MachinePointerInfo(), false, false, 0);
3809       MemOps.push_back(Store);
3810       // Increment the address by four for the next argument to store
3811       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3812       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3813     }
3814   }
3815 
3816   if (!MemOps.empty())
3817     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3818 
3819   return Chain;
3820 }
3821 
3822 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3823 /// adjusted to accommodate the arguments for the tailcall.
3824 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3825                                    unsigned ParamSize) {
3826 
3827   if (!isTailCall) return 0;
3828 
3829   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3830   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3831   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3832   // Remember only if the new adjustement is bigger.
3833   if (SPDiff < FI->getTailCallSPDelta())
3834     FI->setTailCallSPDelta(SPDiff);
3835 
3836   return SPDiff;
3837 }
3838 
3839 static bool isFunctionGlobalAddress(SDValue Callee);
3840 
3841 static bool
3842 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3843   // If !G, Callee can be an external symbol.
3844   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3845   if (!G) return false;
3846 
3847   const GlobalValue *GV = G->getGlobal();
3848 
3849   if (GV->isDeclaration()) return false;
3850 
3851   switch(GV->getLinkage()) {
3852   default: llvm_unreachable("unknow linkage type");
3853   case GlobalValue::AvailableExternallyLinkage:
3854   case GlobalValue::ExternalWeakLinkage:
3855     return false;
3856 
3857   // Callee with weak linkage is allowed if it has hidden or protected
3858   // visibility
3859   case GlobalValue::LinkOnceAnyLinkage:
3860   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3861   case GlobalValue::WeakAnyLinkage:
3862   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3863     if (GV->hasDefaultVisibility())
3864       return false;
3865 
3866   case GlobalValue::ExternalLinkage:
3867   case GlobalValue::InternalLinkage:
3868   case GlobalValue::PrivateLinkage:
3869     break;
3870   }
3871 
3872   // With '-fPIC', calling default visiblity function need insert 'nop' after
3873   // function call, no matter that function resides in same module or not, so
3874   // we treat it as in different module.
3875   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3876     return false;
3877 
3878   return true;
3879 }
3880 
3881 static bool
3882 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3883                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3884   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3885 
3886   const unsigned PtrByteSize = 8;
3887   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3888 
3889   static const MCPhysReg GPR[] = {
3890     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3891     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3892   };
3893   static const MCPhysReg VR[] = {
3894     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3895     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3896   };
3897 
3898   const unsigned NumGPRs = array_lengthof(GPR);
3899   const unsigned NumFPRs = 13;
3900   const unsigned NumVRs = array_lengthof(VR);
3901   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3902 
3903   unsigned NumBytes = LinkageSize;
3904   unsigned AvailableFPRs = NumFPRs;
3905   unsigned AvailableVRs = NumVRs;
3906 
3907   for (const ISD::OutputArg& Param : Outs) {
3908     if (Param.Flags.isNest()) continue;
3909 
3910     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3911                                PtrByteSize, LinkageSize, ParamAreaSize,
3912                                NumBytes, AvailableFPRs, AvailableVRs,
3913                                Subtarget.hasQPX()))
3914       return true;
3915   }
3916   return false;
3917 }
3918 
3919 static bool
3920 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
3921   if (CS->arg_size() != CallerFn->getArgumentList().size())
3922     return false;
3923 
3924   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
3925   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
3926   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
3927 
3928   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
3929     const Value* CalleeArg = *CalleeArgIter;
3930     const Value* CallerArg = &(*CallerArgIter);
3931     if (CalleeArg == CallerArg)
3932       continue;
3933 
3934     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
3935     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
3936     //      }
3937     // 1st argument of callee is undef and has the same type as caller.
3938     if (CalleeArg->getType() == CallerArg->getType() &&
3939         isa<UndefValue>(CalleeArg))
3940       continue;
3941 
3942     return false;
3943   }
3944 
3945   return true;
3946 }
3947 
3948 bool
3949 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
3950                                     SDValue Callee,
3951                                     CallingConv::ID CalleeCC,
3952                                     ImmutableCallSite *CS,
3953                                     bool isVarArg,
3954                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3955                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3956                                     SelectionDAG& DAG) const {
3957   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
3958 
3959   if (DisableSCO && !TailCallOpt) return false;
3960 
3961   // Variadic argument functions are not supported.
3962   if (isVarArg) return false;
3963 
3964   MachineFunction &MF = DAG.getMachineFunction();
3965   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3966 
3967   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
3968   // the same calling convention
3969   if (CallerCC != CalleeCC) return false;
3970 
3971   // SCO support C calling convention
3972   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
3973     return false;
3974 
3975   // Functions containing by val parameters are not supported.
3976   if (std::any_of(Ins.begin(), Ins.end(),
3977                   [](const ISD::InputArg& IA) { return IA.Flags.isByVal(); }))
3978     return false;
3979 
3980   // No TCO/SCO on indirect call because Caller have to restore its TOC
3981   if (!isFunctionGlobalAddress(Callee) &&
3982       !isa<ExternalSymbolSDNode>(Callee))
3983     return false;
3984 
3985   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
3986   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
3987   // module.
3988   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
3989   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
3990     return false;
3991 
3992   // TCO allows altering callee ABI, so we don't have to check further.
3993   if (CalleeCC == CallingConv::Fast && TailCallOpt)
3994     return true;
3995 
3996   if (DisableSCO) return false;
3997 
3998   // If callee use the same argument list that caller is using, then we can
3999   // apply SCO on this case. If it is not, then we need to check if callee needs
4000   // stack for passing arguments.
4001   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4002       needStackSlotPassParameters(Subtarget, Outs)) {
4003     return false;
4004   }
4005 
4006   return true;
4007 }
4008 
4009 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4010 /// for tail call optimization. Targets which want to do tail call
4011 /// optimization should implement this function.
4012 bool
4013 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4014                                                      CallingConv::ID CalleeCC,
4015                                                      bool isVarArg,
4016                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4017                                                      SelectionDAG& DAG) const {
4018   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4019     return false;
4020 
4021   // Variable argument functions are not supported.
4022   if (isVarArg)
4023     return false;
4024 
4025   MachineFunction &MF = DAG.getMachineFunction();
4026   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4027   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4028     // Functions containing by val parameters are not supported.
4029     for (unsigned i = 0; i != Ins.size(); i++) {
4030        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4031        if (Flags.isByVal()) return false;
4032     }
4033 
4034     // Non-PIC/GOT tail calls are supported.
4035     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4036       return true;
4037 
4038     // At the moment we can only do local tail calls (in same module, hidden
4039     // or protected) if we are generating PIC.
4040     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4041       return G->getGlobal()->hasHiddenVisibility()
4042           || G->getGlobal()->hasProtectedVisibility();
4043   }
4044 
4045   return false;
4046 }
4047 
4048 /// isCallCompatibleAddress - Return the immediate to use if the specified
4049 /// 32-bit value is representable in the immediate field of a BxA instruction.
4050 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4051   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4052   if (!C) return nullptr;
4053 
4054   int Addr = C->getZExtValue();
4055   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4056       SignExtend32<26>(Addr) != Addr)
4057     return nullptr;  // Top 6 bits have to be sext of immediate.
4058 
4059   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
4060                          DAG.getTargetLoweringInfo().getPointerTy(
4061                              DAG.getDataLayout())).getNode();
4062 }
4063 
4064 namespace {
4065 
4066 struct TailCallArgumentInfo {
4067   SDValue Arg;
4068   SDValue FrameIdxOp;
4069   int       FrameIdx;
4070 
4071   TailCallArgumentInfo() : FrameIdx(0) {}
4072 };
4073 }
4074 
4075 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4076 static void StoreTailCallArgumentsToStackSlot(
4077     SelectionDAG &DAG, SDValue Chain,
4078     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4079     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4080   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4081     SDValue Arg = TailCallArgs[i].Arg;
4082     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4083     int FI = TailCallArgs[i].FrameIdx;
4084     // Store relative to framepointer.
4085     MemOpChains.push_back(DAG.getStore(
4086         Chain, dl, Arg, FIN,
4087         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
4088         false, 0));
4089   }
4090 }
4091 
4092 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4093 /// the appropriate stack slot for the tail call optimized function call.
4094 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
4095                                              MachineFunction &MF, SDValue Chain,
4096                                              SDValue OldRetAddr, SDValue OldFP,
4097                                              int SPDiff, bool isPPC64,
4098                                              bool isDarwinABI,
4099                                              const SDLoc &dl) {
4100   if (SPDiff) {
4101     // Calculate the new stack slot for the return address.
4102     int SlotSize = isPPC64 ? 8 : 4;
4103     const PPCFrameLowering *FL =
4104         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
4105     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4106     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
4107                                                           NewRetAddrLoc, true);
4108     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4109     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4110     Chain = DAG.getStore(
4111         Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4112         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewRetAddr),
4113         false, false, 0);
4114 
4115     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4116     // slot as the FP is never overwritten.
4117     if (isDarwinABI) {
4118       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4119       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
4120                                                           true);
4121       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4122       Chain = DAG.getStore(
4123           Chain, dl, OldFP, NewFramePtrIdx,
4124           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx),
4125           false, false, 0);
4126     }
4127   }
4128   return Chain;
4129 }
4130 
4131 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4132 /// the position of the argument.
4133 static void
4134 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4135                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4136                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4137   int Offset = ArgOffset + SPDiff;
4138   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4139   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
4140   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4141   SDValue FIN = DAG.getFrameIndex(FI, VT);
4142   TailCallArgumentInfo Info;
4143   Info.Arg = Arg;
4144   Info.FrameIdxOp = FIN;
4145   Info.FrameIdx = FI;
4146   TailCallArguments.push_back(Info);
4147 }
4148 
4149 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4150 /// stack slot. Returns the chain as result and the loaded frame pointers in
4151 /// LROpOut/FPOpout. Used when tail calling.
4152 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4153     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4154     SDValue &FPOpOut, bool isDarwinABI, const SDLoc &dl) const {
4155   if (SPDiff) {
4156     // Load the LR and FP stack slot for later adjusting.
4157     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4158     LROpOut = getReturnAddrFrameIndex(DAG);
4159     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
4160                           false, false, false, 0);
4161     Chain = SDValue(LROpOut.getNode(), 1);
4162 
4163     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4164     // slot as the FP is never overwritten.
4165     if (isDarwinABI) {
4166       FPOpOut = getFramePointerFrameIndex(DAG);
4167       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
4168                             false, false, false, 0);
4169       Chain = SDValue(FPOpOut.getNode(), 1);
4170     }
4171   }
4172   return Chain;
4173 }
4174 
4175 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4176 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4177 /// specified by the specific parameter attribute. The copy will be passed as
4178 /// a byval function parameter.
4179 /// Sometimes what we are copying is the end of a larger object, the part that
4180 /// does not fit in registers.
4181 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4182                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4183                                          SelectionDAG &DAG, const SDLoc &dl) {
4184   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4185   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4186                        false, false, false, MachinePointerInfo(),
4187                        MachinePointerInfo());
4188 }
4189 
4190 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4191 /// tail calls.
4192 static void LowerMemOpCallTo(
4193     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4194     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4195     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4196     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4197   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4198   if (!isTailCall) {
4199     if (isVector) {
4200       SDValue StackPtr;
4201       if (isPPC64)
4202         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4203       else
4204         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4205       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4206                            DAG.getConstant(ArgOffset, dl, PtrVT));
4207     }
4208     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4209                                        MachinePointerInfo(), false, false, 0));
4210   // Calculate and remember argument location.
4211   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4212                                   TailCallArguments);
4213 }
4214 
4215 static void
4216 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4217                 const SDLoc &dl, bool isPPC64, int SPDiff, unsigned NumBytes,
4218                 SDValue LROp, SDValue FPOp, bool isDarwinABI,
4219                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4220   MachineFunction &MF = DAG.getMachineFunction();
4221 
4222   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4223   // might overwrite each other in case of tail call optimization.
4224   SmallVector<SDValue, 8> MemOpChains2;
4225   // Do not flag preceding copytoreg stuff together with the following stuff.
4226   InFlag = SDValue();
4227   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4228                                     MemOpChains2, dl);
4229   if (!MemOpChains2.empty())
4230     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4231 
4232   // Store the return address to the appropriate stack slot.
4233   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
4234                                         isPPC64, isDarwinABI, dl);
4235 
4236   // Emit callseq_end just before tailcall node.
4237   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4238                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4239   InFlag = Chain.getValue(1);
4240 }
4241 
4242 // Is this global address that of a function that can be called by name? (as
4243 // opposed to something that must hold a descriptor for an indirect call).
4244 static bool isFunctionGlobalAddress(SDValue Callee) {
4245   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4246     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4247         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4248       return false;
4249 
4250     return G->getGlobal()->getValueType()->isFunctionTy();
4251   }
4252 
4253   return false;
4254 }
4255 
4256 static unsigned
4257 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4258             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4259             bool IsPatchPoint, bool hasNest,
4260             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4261             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4262             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4263 
4264   bool isPPC64 = Subtarget.isPPC64();
4265   bool isSVR4ABI = Subtarget.isSVR4ABI();
4266   bool isELFv2ABI = Subtarget.isELFv2ABI();
4267 
4268   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4269   NodeTys.push_back(MVT::Other);   // Returns a chain
4270   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4271 
4272   unsigned CallOpc = PPCISD::CALL;
4273 
4274   bool needIndirectCall = true;
4275   if (!isSVR4ABI || !isPPC64)
4276     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4277       // If this is an absolute destination address, use the munged value.
4278       Callee = SDValue(Dest, 0);
4279       needIndirectCall = false;
4280     }
4281 
4282   if (isFunctionGlobalAddress(Callee)) {
4283     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4284     // A call to a TLS address is actually an indirect call to a
4285     // thread-specific pointer.
4286     unsigned OpFlags = 0;
4287     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4288          (Subtarget.getTargetTriple().isMacOSX() &&
4289           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
4290          !G->getGlobal()->isStrongDefinitionForLinker()) ||
4291         (Subtarget.isTargetELF() && !isPPC64 &&
4292          !G->getGlobal()->hasLocalLinkage() &&
4293          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4294       // PC-relative references to external symbols should go through $stub,
4295       // unless we're building with the leopard linker or later, which
4296       // automatically synthesizes these stubs.
4297       OpFlags = PPCII::MO_PLT_OR_STUB;
4298     }
4299 
4300     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4301     // every direct call is) turn it into a TargetGlobalAddress /
4302     // TargetExternalSymbol node so that legalize doesn't hack it.
4303     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4304                                         Callee.getValueType(), 0, OpFlags);
4305     needIndirectCall = false;
4306   }
4307 
4308   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4309     unsigned char OpFlags = 0;
4310 
4311     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4312          (Subtarget.getTargetTriple().isMacOSX() &&
4313           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4314         (Subtarget.isTargetELF() && !isPPC64 &&
4315          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4316       // PC-relative references to external symbols should go through $stub,
4317       // unless we're building with the leopard linker or later, which
4318       // automatically synthesizes these stubs.
4319       OpFlags = PPCII::MO_PLT_OR_STUB;
4320     }
4321 
4322     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4323                                          OpFlags);
4324     needIndirectCall = false;
4325   }
4326 
4327   if (IsPatchPoint) {
4328     // We'll form an invalid direct call when lowering a patchpoint; the full
4329     // sequence for an indirect call is complicated, and many of the
4330     // instructions introduced might have side effects (and, thus, can't be
4331     // removed later). The call itself will be removed as soon as the
4332     // argument/return lowering is complete, so the fact that it has the wrong
4333     // kind of operands should not really matter.
4334     needIndirectCall = false;
4335   }
4336 
4337   if (needIndirectCall) {
4338     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4339     // to do the call, we can't use PPCISD::CALL.
4340     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4341 
4342     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4343       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4344       // entry point, but to the function descriptor (the function entry point
4345       // address is part of the function descriptor though).
4346       // The function descriptor is a three doubleword structure with the
4347       // following fields: function entry point, TOC base address and
4348       // environment pointer.
4349       // Thus for a call through a function pointer, the following actions need
4350       // to be performed:
4351       //   1. Save the TOC of the caller in the TOC save area of its stack
4352       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4353       //   2. Load the address of the function entry point from the function
4354       //      descriptor.
4355       //   3. Load the TOC of the callee from the function descriptor into r2.
4356       //   4. Load the environment pointer from the function descriptor into
4357       //      r11.
4358       //   5. Branch to the function entry point address.
4359       //   6. On return of the callee, the TOC of the caller needs to be
4360       //      restored (this is done in FinishCall()).
4361       //
4362       // The loads are scheduled at the beginning of the call sequence, and the
4363       // register copies are flagged together to ensure that no other
4364       // operations can be scheduled in between. E.g. without flagging the
4365       // copies together, a TOC access in the caller could be scheduled between
4366       // the assignment of the callee TOC and the branch to the callee, which
4367       // results in the TOC access going through the TOC of the callee instead
4368       // of going through the TOC of the caller, which leads to incorrect code.
4369 
4370       // Load the address of the function entry point from the function
4371       // descriptor.
4372       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4373       if (LDChain.getValueType() == MVT::Glue)
4374         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4375 
4376       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4377 
4378       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4379       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4380                                         false, false, LoadsInv, 8);
4381 
4382       // Load environment pointer into r11.
4383       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4384       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4385       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4386                                        MPI.getWithOffset(16), false, false,
4387                                        LoadsInv, 8);
4388 
4389       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4390       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4391       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4392                                    MPI.getWithOffset(8), false, false,
4393                                    LoadsInv, 8);
4394 
4395       setUsesTOCBasePtr(DAG);
4396       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4397                                         InFlag);
4398       Chain = TOCVal.getValue(0);
4399       InFlag = TOCVal.getValue(1);
4400 
4401       // If the function call has an explicit 'nest' parameter, it takes the
4402       // place of the environment pointer.
4403       if (!hasNest) {
4404         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4405                                           InFlag);
4406 
4407         Chain = EnvVal.getValue(0);
4408         InFlag = EnvVal.getValue(1);
4409       }
4410 
4411       MTCTROps[0] = Chain;
4412       MTCTROps[1] = LoadFuncPtr;
4413       MTCTROps[2] = InFlag;
4414     }
4415 
4416     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4417                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4418     InFlag = Chain.getValue(1);
4419 
4420     NodeTys.clear();
4421     NodeTys.push_back(MVT::Other);
4422     NodeTys.push_back(MVT::Glue);
4423     Ops.push_back(Chain);
4424     CallOpc = PPCISD::BCTRL;
4425     Callee.setNode(nullptr);
4426     // Add use of X11 (holding environment pointer)
4427     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4428       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4429     // Add CTR register as callee so a bctr can be emitted later.
4430     if (isTailCall)
4431       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4432   }
4433 
4434   // If this is a direct call, pass the chain and the callee.
4435   if (Callee.getNode()) {
4436     Ops.push_back(Chain);
4437     Ops.push_back(Callee);
4438   }
4439   // If this is a tail call add stack pointer delta.
4440   if (isTailCall)
4441     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4442 
4443   // Add argument registers to the end of the list so that they are known live
4444   // into the call.
4445   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4446     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4447                                   RegsToPass[i].second.getValueType()));
4448 
4449   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4450   // into the call.
4451   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4452     setUsesTOCBasePtr(DAG);
4453     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4454   }
4455 
4456   return CallOpc;
4457 }
4458 
4459 static
4460 bool isLocalCall(const SDValue &Callee)
4461 {
4462   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4463     return G->getGlobal()->isStrongDefinitionForLinker();
4464   return false;
4465 }
4466 
4467 SDValue PPCTargetLowering::LowerCallResult(
4468     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4469     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4470     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4471 
4472   SmallVector<CCValAssign, 16> RVLocs;
4473   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4474                     *DAG.getContext());
4475   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4476 
4477   // Copy all of the result registers out of their specified physreg.
4478   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4479     CCValAssign &VA = RVLocs[i];
4480     assert(VA.isRegLoc() && "Can only return in registers!");
4481 
4482     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4483                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4484     Chain = Val.getValue(1);
4485     InFlag = Val.getValue(2);
4486 
4487     switch (VA.getLocInfo()) {
4488     default: llvm_unreachable("Unknown loc info!");
4489     case CCValAssign::Full: break;
4490     case CCValAssign::AExt:
4491       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4492       break;
4493     case CCValAssign::ZExt:
4494       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4495                         DAG.getValueType(VA.getValVT()));
4496       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4497       break;
4498     case CCValAssign::SExt:
4499       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4500                         DAG.getValueType(VA.getValVT()));
4501       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4502       break;
4503     }
4504 
4505     InVals.push_back(Val);
4506   }
4507 
4508   return Chain;
4509 }
4510 
4511 SDValue PPCTargetLowering::FinishCall(
4512     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4513     bool IsPatchPoint, bool hasNest, SelectionDAG &DAG,
4514     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4515     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4516     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4517     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4518 
4519   std::vector<EVT> NodeTys;
4520   SmallVector<SDValue, 8> Ops;
4521   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4522                                  SPDiff, isTailCall, IsPatchPoint, hasNest,
4523                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4524 
4525   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4526   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4527     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4528 
4529   // When performing tail call optimization the callee pops its arguments off
4530   // the stack. Account for this here so these bytes can be pushed back on in
4531   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4532   int BytesCalleePops =
4533     (CallConv == CallingConv::Fast &&
4534      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4535 
4536   // Add a register mask operand representing the call-preserved registers.
4537   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4538   const uint32_t *Mask =
4539       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4540   assert(Mask && "Missing call preserved mask for calling convention");
4541   Ops.push_back(DAG.getRegisterMask(Mask));
4542 
4543   if (InFlag.getNode())
4544     Ops.push_back(InFlag);
4545 
4546   // Emit tail call.
4547   if (isTailCall) {
4548     assert(((Callee.getOpcode() == ISD::Register &&
4549              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4550             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4551             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4552             isa<ConstantSDNode>(Callee)) &&
4553     "Expecting an global address, external symbol, absolute value or register");
4554 
4555     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4556     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4557   }
4558 
4559   // Add a NOP immediately after the branch instruction when using the 64-bit
4560   // SVR4 ABI. At link time, if caller and callee are in a different module and
4561   // thus have a different TOC, the call will be replaced with a call to a stub
4562   // function which saves the current TOC, loads the TOC of the callee and
4563   // branches to the callee. The NOP will be replaced with a load instruction
4564   // which restores the TOC of the caller from the TOC save slot of the current
4565   // stack frame. If caller and callee belong to the same module (and have the
4566   // same TOC), the NOP will remain unchanged.
4567 
4568   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4569       !IsPatchPoint) {
4570     if (CallOpc == PPCISD::BCTRL) {
4571       // This is a call through a function pointer.
4572       // Restore the caller TOC from the save area into R2.
4573       // See PrepareCall() for more information about calls through function
4574       // pointers in the 64-bit SVR4 ABI.
4575       // We are using a target-specific load with r2 hard coded, because the
4576       // result of a target-independent load would never go directly into r2,
4577       // since r2 is a reserved register (which prevents the register allocator
4578       // from allocating it), resulting in an additional register being
4579       // allocated and an unnecessary move instruction being generated.
4580       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4581 
4582       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4583       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4584       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4585       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4586       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4587 
4588       // The address needs to go after the chain input but before the flag (or
4589       // any other variadic arguments).
4590       Ops.insert(std::next(Ops.begin()), AddTOC);
4591     } else if ((CallOpc == PPCISD::CALL) &&
4592                (!isLocalCall(Callee) ||
4593                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4594       // Otherwise insert NOP for non-local calls.
4595       CallOpc = PPCISD::CALL_NOP;
4596   }
4597 
4598   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4599   InFlag = Chain.getValue(1);
4600 
4601   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4602                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4603                              InFlag, dl);
4604   if (!Ins.empty())
4605     InFlag = Chain.getValue(1);
4606 
4607   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4608                          Ins, dl, DAG, InVals);
4609 }
4610 
4611 SDValue
4612 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4613                              SmallVectorImpl<SDValue> &InVals) const {
4614   SelectionDAG &DAG                     = CLI.DAG;
4615   SDLoc &dl                             = CLI.DL;
4616   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4617   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4618   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4619   SDValue Chain                         = CLI.Chain;
4620   SDValue Callee                        = CLI.Callee;
4621   bool &isTailCall                      = CLI.IsTailCall;
4622   CallingConv::ID CallConv              = CLI.CallConv;
4623   bool isVarArg                         = CLI.IsVarArg;
4624   bool IsPatchPoint                     = CLI.IsPatchPoint;
4625   ImmutableCallSite *CS                 = CLI.CS;
4626 
4627   if (isTailCall) {
4628     if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4629       isTailCall =
4630         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4631                                                  isVarArg, Outs, Ins, DAG);
4632     else
4633       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4634                                                      Ins, DAG);
4635     if (isTailCall) {
4636       ++NumTailCalls;
4637       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4638         ++NumSiblingCalls;
4639 
4640       assert(isa<GlobalAddressSDNode>(Callee) &&
4641              "Callee should be an llvm::Function object.");
4642       DEBUG(
4643         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4644         const unsigned Width = 80 - strlen("TCO caller: ")
4645                                   - strlen(", callee linkage: 0, 0");
4646         dbgs() << "TCO caller: "
4647                << left_justify(DAG.getMachineFunction().getName(), Width)
4648                << ", callee linkage: "
4649                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4650       );
4651     }
4652   }
4653 
4654   if (!isTailCall && CS && CS->isMustTailCall())
4655     report_fatal_error("failed to perform tail call elimination on a call "
4656                        "site marked musttail");
4657 
4658   if (Subtarget.isSVR4ABI()) {
4659     if (Subtarget.isPPC64())
4660       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4661                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4662                               dl, DAG, InVals, CS);
4663     else
4664       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4665                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4666                               dl, DAG, InVals, CS);
4667   }
4668 
4669   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4670                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4671                           dl, DAG, InVals, CS);
4672 }
4673 
4674 SDValue PPCTargetLowering::LowerCall_32SVR4(
4675     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4676     bool isTailCall, bool IsPatchPoint,
4677     const SmallVectorImpl<ISD::OutputArg> &Outs,
4678     const SmallVectorImpl<SDValue> &OutVals,
4679     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4680     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4681     ImmutableCallSite *CS) const {
4682   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4683   // of the 32-bit SVR4 ABI stack frame layout.
4684 
4685   assert((CallConv == CallingConv::C ||
4686           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4687 
4688   unsigned PtrByteSize = 4;
4689 
4690   MachineFunction &MF = DAG.getMachineFunction();
4691 
4692   // Mark this function as potentially containing a function that contains a
4693   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4694   // and restoring the callers stack pointer in this functions epilog. This is
4695   // done because by tail calling the called function might overwrite the value
4696   // in this function's (MF) stack pointer stack slot 0(SP).
4697   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4698       CallConv == CallingConv::Fast)
4699     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4700 
4701   // Count how many bytes are to be pushed on the stack, including the linkage
4702   // area, parameter list area and the part of the local variable space which
4703   // contains copies of aggregates which are passed by value.
4704 
4705   // Assign locations to all of the outgoing arguments.
4706   SmallVector<CCValAssign, 16> ArgLocs;
4707   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4708                  *DAG.getContext());
4709 
4710   // Reserve space for the linkage area on the stack.
4711   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4712                        PtrByteSize);
4713   if (Subtarget.useSoftFloat())
4714     CCInfo.PreAnalyzeCallOperands(Outs);
4715 
4716   if (isVarArg) {
4717     // Handle fixed and variable vector arguments differently.
4718     // Fixed vector arguments go into registers as long as registers are
4719     // available. Variable vector arguments always go into memory.
4720     unsigned NumArgs = Outs.size();
4721 
4722     for (unsigned i = 0; i != NumArgs; ++i) {
4723       MVT ArgVT = Outs[i].VT;
4724       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4725       bool Result;
4726 
4727       if (Outs[i].IsFixed) {
4728         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4729                                CCInfo);
4730       } else {
4731         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4732                                       ArgFlags, CCInfo);
4733       }
4734 
4735       if (Result) {
4736 #ifndef NDEBUG
4737         errs() << "Call operand #" << i << " has unhandled type "
4738              << EVT(ArgVT).getEVTString() << "\n";
4739 #endif
4740         llvm_unreachable(nullptr);
4741       }
4742     }
4743   } else {
4744     // All arguments are treated the same.
4745     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4746   }
4747   CCInfo.clearWasPPCF128();
4748 
4749   // Assign locations to all of the outgoing aggregate by value arguments.
4750   SmallVector<CCValAssign, 16> ByValArgLocs;
4751   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4752                       ByValArgLocs, *DAG.getContext());
4753 
4754   // Reserve stack space for the allocations in CCInfo.
4755   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4756 
4757   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4758 
4759   // Size of the linkage area, parameter list area and the part of the local
4760   // space variable where copies of aggregates which are passed by value are
4761   // stored.
4762   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4763 
4764   // Calculate by how many bytes the stack has to be adjusted in case of tail
4765   // call optimization.
4766   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4767 
4768   // Adjust the stack pointer for the new arguments...
4769   // These operations are automatically eliminated by the prolog/epilog pass
4770   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4771                                dl);
4772   SDValue CallSeqStart = Chain;
4773 
4774   // Load the return address and frame pointer so it can be moved somewhere else
4775   // later.
4776   SDValue LROp, FPOp;
4777   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4778                                        dl);
4779 
4780   // Set up a copy of the stack pointer for use loading and storing any
4781   // arguments that may not fit in the registers available for argument
4782   // passing.
4783   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4784 
4785   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4786   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4787   SmallVector<SDValue, 8> MemOpChains;
4788 
4789   bool seenFloatArg = false;
4790   // Walk the register/memloc assignments, inserting copies/loads.
4791   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4792        i != e;
4793        ++i) {
4794     CCValAssign &VA = ArgLocs[i];
4795     SDValue Arg = OutVals[i];
4796     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4797 
4798     if (Flags.isByVal()) {
4799       // Argument is an aggregate which is passed by value, thus we need to
4800       // create a copy of it in the local variable space of the current stack
4801       // frame (which is the stack frame of the caller) and pass the address of
4802       // this copy to the callee.
4803       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4804       CCValAssign &ByValVA = ByValArgLocs[j++];
4805       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4806 
4807       // Memory reserved in the local variable space of the callers stack frame.
4808       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4809 
4810       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4811       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4812                            StackPtr, PtrOff);
4813 
4814       // Create a copy of the argument in the local area of the current
4815       // stack frame.
4816       SDValue MemcpyCall =
4817         CreateCopyOfByValArgument(Arg, PtrOff,
4818                                   CallSeqStart.getNode()->getOperand(0),
4819                                   Flags, DAG, dl);
4820 
4821       // This must go outside the CALLSEQ_START..END.
4822       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4823                            CallSeqStart.getNode()->getOperand(1),
4824                            SDLoc(MemcpyCall));
4825       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4826                              NewCallSeqStart.getNode());
4827       Chain = CallSeqStart = NewCallSeqStart;
4828 
4829       // Pass the address of the aggregate copy on the stack either in a
4830       // physical register or in the parameter list area of the current stack
4831       // frame to the callee.
4832       Arg = PtrOff;
4833     }
4834 
4835     if (VA.isRegLoc()) {
4836       if (Arg.getValueType() == MVT::i1)
4837         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4838 
4839       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4840       // Put argument in a physical register.
4841       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4842     } else {
4843       // Put argument in the parameter list area of the current stack frame.
4844       assert(VA.isMemLoc());
4845       unsigned LocMemOffset = VA.getLocMemOffset();
4846 
4847       if (!isTailCall) {
4848         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4849         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4850                              StackPtr, PtrOff);
4851 
4852         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4853                                            MachinePointerInfo(),
4854                                            false, false, 0));
4855       } else {
4856         // Calculate and remember argument location.
4857         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4858                                  TailCallArguments);
4859       }
4860     }
4861   }
4862 
4863   if (!MemOpChains.empty())
4864     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4865 
4866   // Build a sequence of copy-to-reg nodes chained together with token chain
4867   // and flag operands which copy the outgoing args into the appropriate regs.
4868   SDValue InFlag;
4869   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4870     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4871                              RegsToPass[i].second, InFlag);
4872     InFlag = Chain.getValue(1);
4873   }
4874 
4875   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4876   // registers.
4877   if (isVarArg) {
4878     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4879     SDValue Ops[] = { Chain, InFlag };
4880 
4881     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4882                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4883 
4884     InFlag = Chain.getValue(1);
4885   }
4886 
4887   if (isTailCall)
4888     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4889                     false, TailCallArguments);
4890 
4891   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
4892                     /* unused except on PPC64 ELFv1 */ false, DAG,
4893                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4894                     NumBytes, Ins, InVals, CS);
4895 }
4896 
4897 // Copy an argument into memory, being careful to do this outside the
4898 // call sequence for the call to which the argument belongs.
4899 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4900     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4901     SelectionDAG &DAG, const SDLoc &dl) const {
4902   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4903                         CallSeqStart.getNode()->getOperand(0),
4904                         Flags, DAG, dl);
4905   // The MEMCPY must go outside the CALLSEQ_START..END.
4906   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4907                              CallSeqStart.getNode()->getOperand(1),
4908                              SDLoc(MemcpyCall));
4909   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4910                          NewCallSeqStart.getNode());
4911   return NewCallSeqStart;
4912 }
4913 
4914 SDValue PPCTargetLowering::LowerCall_64SVR4(
4915     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4916     bool isTailCall, bool IsPatchPoint,
4917     const SmallVectorImpl<ISD::OutputArg> &Outs,
4918     const SmallVectorImpl<SDValue> &OutVals,
4919     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4920     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4921     ImmutableCallSite *CS) const {
4922 
4923   bool isELFv2ABI = Subtarget.isELFv2ABI();
4924   bool isLittleEndian = Subtarget.isLittleEndian();
4925   unsigned NumOps = Outs.size();
4926   bool hasNest = false;
4927   bool IsSibCall = false;
4928 
4929   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4930   unsigned PtrByteSize = 8;
4931 
4932   MachineFunction &MF = DAG.getMachineFunction();
4933 
4934   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
4935     IsSibCall = true;
4936 
4937   // Mark this function as potentially containing a function that contains a
4938   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4939   // and restoring the callers stack pointer in this functions epilog. This is
4940   // done because by tail calling the called function might overwrite the value
4941   // in this function's (MF) stack pointer stack slot 0(SP).
4942   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4943       CallConv == CallingConv::Fast)
4944     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4945 
4946   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4947          "fastcc not supported on varargs functions");
4948 
4949   // Count how many bytes are to be pushed on the stack, including the linkage
4950   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4951   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4952   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4953   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4954   unsigned NumBytes = LinkageSize;
4955   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4956   unsigned &QFPR_idx = FPR_idx;
4957 
4958   static const MCPhysReg GPR[] = {
4959     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4960     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4961   };
4962   static const MCPhysReg VR[] = {
4963     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4964     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4965   };
4966   static const MCPhysReg VSRH[] = {
4967     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4968     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4969   };
4970 
4971   const unsigned NumGPRs = array_lengthof(GPR);
4972   const unsigned NumFPRs = 13;
4973   const unsigned NumVRs  = array_lengthof(VR);
4974   const unsigned NumQFPRs = NumFPRs;
4975 
4976   // When using the fast calling convention, we don't provide backing for
4977   // arguments that will be in registers.
4978   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4979 
4980   // Add up all the space actually used.
4981   for (unsigned i = 0; i != NumOps; ++i) {
4982     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4983     EVT ArgVT = Outs[i].VT;
4984     EVT OrigVT = Outs[i].ArgVT;
4985 
4986     if (Flags.isNest())
4987       continue;
4988 
4989     if (CallConv == CallingConv::Fast) {
4990       if (Flags.isByVal())
4991         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4992       else
4993         switch (ArgVT.getSimpleVT().SimpleTy) {
4994         default: llvm_unreachable("Unexpected ValueType for argument!");
4995         case MVT::i1:
4996         case MVT::i32:
4997         case MVT::i64:
4998           if (++NumGPRsUsed <= NumGPRs)
4999             continue;
5000           break;
5001         case MVT::v4i32:
5002         case MVT::v8i16:
5003         case MVT::v16i8:
5004         case MVT::v2f64:
5005         case MVT::v2i64:
5006         case MVT::v1i128:
5007           if (++NumVRsUsed <= NumVRs)
5008             continue;
5009           break;
5010         case MVT::v4f32:
5011           // When using QPX, this is handled like a FP register, otherwise, it
5012           // is an Altivec register.
5013           if (Subtarget.hasQPX()) {
5014             if (++NumFPRsUsed <= NumFPRs)
5015               continue;
5016           } else {
5017             if (++NumVRsUsed <= NumVRs)
5018               continue;
5019           }
5020           break;
5021         case MVT::f32:
5022         case MVT::f64:
5023         case MVT::v4f64: // QPX
5024         case MVT::v4i1:  // QPX
5025           if (++NumFPRsUsed <= NumFPRs)
5026             continue;
5027           break;
5028         }
5029     }
5030 
5031     /* Respect alignment of argument on the stack.  */
5032     unsigned Align =
5033       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5034     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5035 
5036     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5037     if (Flags.isInConsecutiveRegsLast())
5038       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5039   }
5040 
5041   unsigned NumBytesActuallyUsed = NumBytes;
5042 
5043   // The prolog code of the callee may store up to 8 GPR argument registers to
5044   // the stack, allowing va_start to index over them in memory if its varargs.
5045   // Because we cannot tell if this is needed on the caller side, we have to
5046   // conservatively assume that it is needed.  As such, make sure we have at
5047   // least enough stack space for the caller to store the 8 GPRs.
5048   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5049   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5050 
5051   // Tail call needs the stack to be aligned.
5052   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5053       CallConv == CallingConv::Fast)
5054     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5055 
5056   int SPDiff = 0;
5057 
5058   // Calculate by how many bytes the stack has to be adjusted in case of tail
5059   // call optimization.
5060   if (!IsSibCall)
5061     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5062 
5063   // To protect arguments on the stack from being clobbered in a tail call,
5064   // force all the loads to happen before doing any other lowering.
5065   if (isTailCall)
5066     Chain = DAG.getStackArgumentTokenFactor(Chain);
5067 
5068   // Adjust the stack pointer for the new arguments...
5069   // These operations are automatically eliminated by the prolog/epilog pass
5070   if (!IsSibCall)
5071     Chain = DAG.getCALLSEQ_START(Chain,
5072                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5073   SDValue CallSeqStart = Chain;
5074 
5075   // Load the return address and frame pointer so it can be move somewhere else
5076   // later.
5077   SDValue LROp, FPOp;
5078   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5079                                        dl);
5080 
5081   // Set up a copy of the stack pointer for use loading and storing any
5082   // arguments that may not fit in the registers available for argument
5083   // passing.
5084   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5085 
5086   // Figure out which arguments are going to go in registers, and which in
5087   // memory.  Also, if this is a vararg function, floating point operations
5088   // must be stored to our stack, and loaded into integer regs as well, if
5089   // any integer regs are available for argument passing.
5090   unsigned ArgOffset = LinkageSize;
5091 
5092   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5093   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5094 
5095   SmallVector<SDValue, 8> MemOpChains;
5096   for (unsigned i = 0; i != NumOps; ++i) {
5097     SDValue Arg = OutVals[i];
5098     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5099     EVT ArgVT = Outs[i].VT;
5100     EVT OrigVT = Outs[i].ArgVT;
5101 
5102     // PtrOff will be used to store the current argument to the stack if a
5103     // register cannot be found for it.
5104     SDValue PtrOff;
5105 
5106     // We re-align the argument offset for each argument, except when using the
5107     // fast calling convention, when we need to make sure we do that only when
5108     // we'll actually use a stack slot.
5109     auto ComputePtrOff = [&]() {
5110       /* Respect alignment of argument on the stack.  */
5111       unsigned Align =
5112         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5113       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5114 
5115       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5116 
5117       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5118     };
5119 
5120     if (CallConv != CallingConv::Fast) {
5121       ComputePtrOff();
5122 
5123       /* Compute GPR index associated with argument offset.  */
5124       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5125       GPR_idx = std::min(GPR_idx, NumGPRs);
5126     }
5127 
5128     // Promote integers to 64-bit values.
5129     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5130       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5131       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5132       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5133     }
5134 
5135     // FIXME memcpy is used way more than necessary.  Correctness first.
5136     // Note: "by value" is code for passing a structure by value, not
5137     // basic types.
5138     if (Flags.isByVal()) {
5139       // Note: Size includes alignment padding, so
5140       //   struct x { short a; char b; }
5141       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5142       // These are the proper values we need for right-justifying the
5143       // aggregate in a parameter register.
5144       unsigned Size = Flags.getByValSize();
5145 
5146       // An empty aggregate parameter takes up no storage and no
5147       // registers.
5148       if (Size == 0)
5149         continue;
5150 
5151       if (CallConv == CallingConv::Fast)
5152         ComputePtrOff();
5153 
5154       // All aggregates smaller than 8 bytes must be passed right-justified.
5155       if (Size==1 || Size==2 || Size==4) {
5156         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5157         if (GPR_idx != NumGPRs) {
5158           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5159                                         MachinePointerInfo(), VT,
5160                                         false, false, false, 0);
5161           MemOpChains.push_back(Load.getValue(1));
5162           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5163 
5164           ArgOffset += PtrByteSize;
5165           continue;
5166         }
5167       }
5168 
5169       if (GPR_idx == NumGPRs && Size < 8) {
5170         SDValue AddPtr = PtrOff;
5171         if (!isLittleEndian) {
5172           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5173                                           PtrOff.getValueType());
5174           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5175         }
5176         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5177                                                           CallSeqStart,
5178                                                           Flags, DAG, dl);
5179         ArgOffset += PtrByteSize;
5180         continue;
5181       }
5182       // Copy entire object into memory.  There are cases where gcc-generated
5183       // code assumes it is there, even if it could be put entirely into
5184       // registers.  (This is not what the doc says.)
5185 
5186       // FIXME: The above statement is likely due to a misunderstanding of the
5187       // documents.  All arguments must be copied into the parameter area BY
5188       // THE CALLEE in the event that the callee takes the address of any
5189       // formal argument.  That has not yet been implemented.  However, it is
5190       // reasonable to use the stack area as a staging area for the register
5191       // load.
5192 
5193       // Skip this for small aggregates, as we will use the same slot for a
5194       // right-justified copy, below.
5195       if (Size >= 8)
5196         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5197                                                           CallSeqStart,
5198                                                           Flags, DAG, dl);
5199 
5200       // When a register is available, pass a small aggregate right-justified.
5201       if (Size < 8 && GPR_idx != NumGPRs) {
5202         // The easiest way to get this right-justified in a register
5203         // is to copy the structure into the rightmost portion of a
5204         // local variable slot, then load the whole slot into the
5205         // register.
5206         // FIXME: The memcpy seems to produce pretty awful code for
5207         // small aggregates, particularly for packed ones.
5208         // FIXME: It would be preferable to use the slot in the
5209         // parameter save area instead of a new local variable.
5210         SDValue AddPtr = PtrOff;
5211         if (!isLittleEndian) {
5212           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5213           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5214         }
5215         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5216                                                           CallSeqStart,
5217                                                           Flags, DAG, dl);
5218 
5219         // Load the slot into the register.
5220         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5221                                    MachinePointerInfo(),
5222                                    false, false, false, 0);
5223         MemOpChains.push_back(Load.getValue(1));
5224         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5225 
5226         // Done with this argument.
5227         ArgOffset += PtrByteSize;
5228         continue;
5229       }
5230 
5231       // For aggregates larger than PtrByteSize, copy the pieces of the
5232       // object that fit into registers from the parameter save area.
5233       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5234         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5235         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5236         if (GPR_idx != NumGPRs) {
5237           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5238                                      MachinePointerInfo(),
5239                                      false, false, false, 0);
5240           MemOpChains.push_back(Load.getValue(1));
5241           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5242           ArgOffset += PtrByteSize;
5243         } else {
5244           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5245           break;
5246         }
5247       }
5248       continue;
5249     }
5250 
5251     switch (Arg.getSimpleValueType().SimpleTy) {
5252     default: llvm_unreachable("Unexpected ValueType for argument!");
5253     case MVT::i1:
5254     case MVT::i32:
5255     case MVT::i64:
5256       if (Flags.isNest()) {
5257         // The 'nest' parameter, if any, is passed in R11.
5258         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5259         hasNest = true;
5260         break;
5261       }
5262 
5263       // These can be scalar arguments or elements of an integer array type
5264       // passed directly.  Clang may use those instead of "byval" aggregate
5265       // types to avoid forcing arguments to memory unnecessarily.
5266       if (GPR_idx != NumGPRs) {
5267         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5268       } else {
5269         if (CallConv == CallingConv::Fast)
5270           ComputePtrOff();
5271 
5272         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5273                          true, isTailCall, false, MemOpChains,
5274                          TailCallArguments, dl);
5275         if (CallConv == CallingConv::Fast)
5276           ArgOffset += PtrByteSize;
5277       }
5278       if (CallConv != CallingConv::Fast)
5279         ArgOffset += PtrByteSize;
5280       break;
5281     case MVT::f32:
5282     case MVT::f64: {
5283       // These can be scalar arguments or elements of a float array type
5284       // passed directly.  The latter are used to implement ELFv2 homogenous
5285       // float aggregates.
5286 
5287       // Named arguments go into FPRs first, and once they overflow, the
5288       // remaining arguments go into GPRs and then the parameter save area.
5289       // Unnamed arguments for vararg functions always go to GPRs and
5290       // then the parameter save area.  For now, put all arguments to vararg
5291       // routines always in both locations (FPR *and* GPR or stack slot).
5292       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5293       bool NeededLoad = false;
5294 
5295       // First load the argument into the next available FPR.
5296       if (FPR_idx != NumFPRs)
5297         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5298 
5299       // Next, load the argument into GPR or stack slot if needed.
5300       if (!NeedGPROrStack)
5301         ;
5302       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5303         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5304         // once we support fp <-> gpr moves.
5305 
5306         // In the non-vararg case, this can only ever happen in the
5307         // presence of f32 array types, since otherwise we never run
5308         // out of FPRs before running out of GPRs.
5309         SDValue ArgVal;
5310 
5311         // Double values are always passed in a single GPR.
5312         if (Arg.getValueType() != MVT::f32) {
5313           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5314 
5315         // Non-array float values are extended and passed in a GPR.
5316         } else if (!Flags.isInConsecutiveRegs()) {
5317           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5318           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5319 
5320         // If we have an array of floats, we collect every odd element
5321         // together with its predecessor into one GPR.
5322         } else if (ArgOffset % PtrByteSize != 0) {
5323           SDValue Lo, Hi;
5324           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5325           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5326           if (!isLittleEndian)
5327             std::swap(Lo, Hi);
5328           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5329 
5330         // The final element, if even, goes into the first half of a GPR.
5331         } else if (Flags.isInConsecutiveRegsLast()) {
5332           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5333           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5334           if (!isLittleEndian)
5335             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5336                                  DAG.getConstant(32, dl, MVT::i32));
5337 
5338         // Non-final even elements are skipped; they will be handled
5339         // together the with subsequent argument on the next go-around.
5340         } else
5341           ArgVal = SDValue();
5342 
5343         if (ArgVal.getNode())
5344           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5345       } else {
5346         if (CallConv == CallingConv::Fast)
5347           ComputePtrOff();
5348 
5349         // Single-precision floating-point values are mapped to the
5350         // second (rightmost) word of the stack doubleword.
5351         if (Arg.getValueType() == MVT::f32 &&
5352             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5353           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5354           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5355         }
5356 
5357         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5358                          true, isTailCall, false, MemOpChains,
5359                          TailCallArguments, dl);
5360 
5361         NeededLoad = true;
5362       }
5363       // When passing an array of floats, the array occupies consecutive
5364       // space in the argument area; only round up to the next doubleword
5365       // at the end of the array.  Otherwise, each float takes 8 bytes.
5366       if (CallConv != CallingConv::Fast || NeededLoad) {
5367         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5368                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5369         if (Flags.isInConsecutiveRegsLast())
5370           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5371       }
5372       break;
5373     }
5374     case MVT::v4f32:
5375     case MVT::v4i32:
5376     case MVT::v8i16:
5377     case MVT::v16i8:
5378     case MVT::v2f64:
5379     case MVT::v2i64:
5380     case MVT::v1i128:
5381       if (!Subtarget.hasQPX()) {
5382       // These can be scalar arguments or elements of a vector array type
5383       // passed directly.  The latter are used to implement ELFv2 homogenous
5384       // vector aggregates.
5385 
5386       // For a varargs call, named arguments go into VRs or on the stack as
5387       // usual; unnamed arguments always go to the stack or the corresponding
5388       // GPRs when within range.  For now, we always put the value in both
5389       // locations (or even all three).
5390       if (isVarArg) {
5391         // We could elide this store in the case where the object fits
5392         // entirely in R registers.  Maybe later.
5393         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5394                                      MachinePointerInfo(), false, false, 0);
5395         MemOpChains.push_back(Store);
5396         if (VR_idx != NumVRs) {
5397           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5398                                      MachinePointerInfo(),
5399                                      false, false, false, 0);
5400           MemOpChains.push_back(Load.getValue(1));
5401 
5402           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5403                            Arg.getSimpleValueType() == MVT::v2i64) ?
5404                           VSRH[VR_idx] : VR[VR_idx];
5405           ++VR_idx;
5406 
5407           RegsToPass.push_back(std::make_pair(VReg, Load));
5408         }
5409         ArgOffset += 16;
5410         for (unsigned i=0; i<16; i+=PtrByteSize) {
5411           if (GPR_idx == NumGPRs)
5412             break;
5413           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5414                                    DAG.getConstant(i, dl, PtrVT));
5415           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5416                                      false, false, false, 0);
5417           MemOpChains.push_back(Load.getValue(1));
5418           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5419         }
5420         break;
5421       }
5422 
5423       // Non-varargs Altivec params go into VRs or on the stack.
5424       if (VR_idx != NumVRs) {
5425         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5426                          Arg.getSimpleValueType() == MVT::v2i64) ?
5427                         VSRH[VR_idx] : VR[VR_idx];
5428         ++VR_idx;
5429 
5430         RegsToPass.push_back(std::make_pair(VReg, Arg));
5431       } else {
5432         if (CallConv == CallingConv::Fast)
5433           ComputePtrOff();
5434 
5435         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5436                          true, isTailCall, true, MemOpChains,
5437                          TailCallArguments, dl);
5438         if (CallConv == CallingConv::Fast)
5439           ArgOffset += 16;
5440       }
5441 
5442       if (CallConv != CallingConv::Fast)
5443         ArgOffset += 16;
5444       break;
5445       } // not QPX
5446 
5447       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5448              "Invalid QPX parameter type");
5449 
5450       /* fall through */
5451     case MVT::v4f64:
5452     case MVT::v4i1: {
5453       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5454       if (isVarArg) {
5455         // We could elide this store in the case where the object fits
5456         // entirely in R registers.  Maybe later.
5457         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5458                                      MachinePointerInfo(), false, false, 0);
5459         MemOpChains.push_back(Store);
5460         if (QFPR_idx != NumQFPRs) {
5461           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5462                                      Store, PtrOff, MachinePointerInfo(),
5463                                      false, false, false, 0);
5464           MemOpChains.push_back(Load.getValue(1));
5465           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5466         }
5467         ArgOffset += (IsF32 ? 16 : 32);
5468         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5469           if (GPR_idx == NumGPRs)
5470             break;
5471           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5472                                    DAG.getConstant(i, dl, PtrVT));
5473           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5474                                      false, false, false, 0);
5475           MemOpChains.push_back(Load.getValue(1));
5476           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5477         }
5478         break;
5479       }
5480 
5481       // Non-varargs QPX params go into registers or on the stack.
5482       if (QFPR_idx != NumQFPRs) {
5483         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5484       } else {
5485         if (CallConv == CallingConv::Fast)
5486           ComputePtrOff();
5487 
5488         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5489                          true, isTailCall, true, MemOpChains,
5490                          TailCallArguments, dl);
5491         if (CallConv == CallingConv::Fast)
5492           ArgOffset += (IsF32 ? 16 : 32);
5493       }
5494 
5495       if (CallConv != CallingConv::Fast)
5496         ArgOffset += (IsF32 ? 16 : 32);
5497       break;
5498       }
5499     }
5500   }
5501 
5502   assert(NumBytesActuallyUsed == ArgOffset);
5503   (void)NumBytesActuallyUsed;
5504 
5505   if (!MemOpChains.empty())
5506     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5507 
5508   // Check if this is an indirect call (MTCTR/BCTRL).
5509   // See PrepareCall() for more information about calls through function
5510   // pointers in the 64-bit SVR4 ABI.
5511   if (!isTailCall && !IsPatchPoint &&
5512       !isFunctionGlobalAddress(Callee) &&
5513       !isa<ExternalSymbolSDNode>(Callee)) {
5514     // Load r2 into a virtual register and store it to the TOC save area.
5515     setUsesTOCBasePtr(DAG);
5516     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5517     // TOC save area offset.
5518     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5519     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5520     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5521     Chain = DAG.getStore(
5522         Val.getValue(1), dl, Val, AddPtr,
5523         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset),
5524         false, false, 0);
5525     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5526     // This does not mean the MTCTR instruction must use R12; it's easier
5527     // to model this as an extra parameter, so do that.
5528     if (isELFv2ABI && !IsPatchPoint)
5529       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5530   }
5531 
5532   // Build a sequence of copy-to-reg nodes chained together with token chain
5533   // and flag operands which copy the outgoing args into the appropriate regs.
5534   SDValue InFlag;
5535   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5536     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5537                              RegsToPass[i].second, InFlag);
5538     InFlag = Chain.getValue(1);
5539   }
5540 
5541   if (isTailCall && !IsSibCall)
5542     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5543                     FPOp, true, TailCallArguments);
5544 
5545   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, hasNest,
5546                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5547                     SPDiff, NumBytes, Ins, InVals, CS);
5548 }
5549 
5550 SDValue PPCTargetLowering::LowerCall_Darwin(
5551     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5552     bool isTailCall, bool IsPatchPoint,
5553     const SmallVectorImpl<ISD::OutputArg> &Outs,
5554     const SmallVectorImpl<SDValue> &OutVals,
5555     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5556     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5557     ImmutableCallSite *CS) const {
5558 
5559   unsigned NumOps = Outs.size();
5560 
5561   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5562   bool isPPC64 = PtrVT == MVT::i64;
5563   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5564 
5565   MachineFunction &MF = DAG.getMachineFunction();
5566 
5567   // Mark this function as potentially containing a function that contains a
5568   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5569   // and restoring the callers stack pointer in this functions epilog. This is
5570   // done because by tail calling the called function might overwrite the value
5571   // in this function's (MF) stack pointer stack slot 0(SP).
5572   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5573       CallConv == CallingConv::Fast)
5574     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5575 
5576   // Count how many bytes are to be pushed on the stack, including the linkage
5577   // area, and parameter passing area.  We start with 24/48 bytes, which is
5578   // prereserved space for [SP][CR][LR][3 x unused].
5579   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5580   unsigned NumBytes = LinkageSize;
5581 
5582   // Add up all the space actually used.
5583   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5584   // they all go in registers, but we must reserve stack space for them for
5585   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5586   // assigned stack space in order, with padding so Altivec parameters are
5587   // 16-byte aligned.
5588   unsigned nAltivecParamsAtEnd = 0;
5589   for (unsigned i = 0; i != NumOps; ++i) {
5590     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5591     EVT ArgVT = Outs[i].VT;
5592     // Varargs Altivec parameters are padded to a 16 byte boundary.
5593     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5594         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5595         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5596       if (!isVarArg && !isPPC64) {
5597         // Non-varargs Altivec parameters go after all the non-Altivec
5598         // parameters; handle those later so we know how much padding we need.
5599         nAltivecParamsAtEnd++;
5600         continue;
5601       }
5602       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5603       NumBytes = ((NumBytes+15)/16)*16;
5604     }
5605     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5606   }
5607 
5608   // Allow for Altivec parameters at the end, if needed.
5609   if (nAltivecParamsAtEnd) {
5610     NumBytes = ((NumBytes+15)/16)*16;
5611     NumBytes += 16*nAltivecParamsAtEnd;
5612   }
5613 
5614   // The prolog code of the callee may store up to 8 GPR argument registers to
5615   // the stack, allowing va_start to index over them in memory if its varargs.
5616   // Because we cannot tell if this is needed on the caller side, we have to
5617   // conservatively assume that it is needed.  As such, make sure we have at
5618   // least enough stack space for the caller to store the 8 GPRs.
5619   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5620 
5621   // Tail call needs the stack to be aligned.
5622   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5623       CallConv == CallingConv::Fast)
5624     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5625 
5626   // Calculate by how many bytes the stack has to be adjusted in case of tail
5627   // call optimization.
5628   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5629 
5630   // To protect arguments on the stack from being clobbered in a tail call,
5631   // force all the loads to happen before doing any other lowering.
5632   if (isTailCall)
5633     Chain = DAG.getStackArgumentTokenFactor(Chain);
5634 
5635   // Adjust the stack pointer for the new arguments...
5636   // These operations are automatically eliminated by the prolog/epilog pass
5637   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5638                                dl);
5639   SDValue CallSeqStart = Chain;
5640 
5641   // Load the return address and frame pointer so it can be move somewhere else
5642   // later.
5643   SDValue LROp, FPOp;
5644   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5645                                        dl);
5646 
5647   // Set up a copy of the stack pointer for use loading and storing any
5648   // arguments that may not fit in the registers available for argument
5649   // passing.
5650   SDValue StackPtr;
5651   if (isPPC64)
5652     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5653   else
5654     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5655 
5656   // Figure out which arguments are going to go in registers, and which in
5657   // memory.  Also, if this is a vararg function, floating point operations
5658   // must be stored to our stack, and loaded into integer regs as well, if
5659   // any integer regs are available for argument passing.
5660   unsigned ArgOffset = LinkageSize;
5661   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5662 
5663   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5664     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5665     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5666   };
5667   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5668     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5669     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5670   };
5671   static const MCPhysReg VR[] = {
5672     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5673     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5674   };
5675   const unsigned NumGPRs = array_lengthof(GPR_32);
5676   const unsigned NumFPRs = 13;
5677   const unsigned NumVRs  = array_lengthof(VR);
5678 
5679   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5680 
5681   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5682   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5683 
5684   SmallVector<SDValue, 8> MemOpChains;
5685   for (unsigned i = 0; i != NumOps; ++i) {
5686     SDValue Arg = OutVals[i];
5687     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5688 
5689     // PtrOff will be used to store the current argument to the stack if a
5690     // register cannot be found for it.
5691     SDValue PtrOff;
5692 
5693     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5694 
5695     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5696 
5697     // On PPC64, promote integers to 64-bit values.
5698     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5699       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5700       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5701       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5702     }
5703 
5704     // FIXME memcpy is used way more than necessary.  Correctness first.
5705     // Note: "by value" is code for passing a structure by value, not
5706     // basic types.
5707     if (Flags.isByVal()) {
5708       unsigned Size = Flags.getByValSize();
5709       // Very small objects are passed right-justified.  Everything else is
5710       // passed left-justified.
5711       if (Size==1 || Size==2) {
5712         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5713         if (GPR_idx != NumGPRs) {
5714           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5715                                         MachinePointerInfo(), VT,
5716                                         false, false, false, 0);
5717           MemOpChains.push_back(Load.getValue(1));
5718           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5719 
5720           ArgOffset += PtrByteSize;
5721         } else {
5722           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5723                                           PtrOff.getValueType());
5724           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5725           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5726                                                             CallSeqStart,
5727                                                             Flags, DAG, dl);
5728           ArgOffset += PtrByteSize;
5729         }
5730         continue;
5731       }
5732       // Copy entire object into memory.  There are cases where gcc-generated
5733       // code assumes it is there, even if it could be put entirely into
5734       // registers.  (This is not what the doc says.)
5735       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5736                                                         CallSeqStart,
5737                                                         Flags, DAG, dl);
5738 
5739       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5740       // copy the pieces of the object that fit into registers from the
5741       // parameter save area.
5742       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5743         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5744         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5745         if (GPR_idx != NumGPRs) {
5746           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5747                                      MachinePointerInfo(),
5748                                      false, false, false, 0);
5749           MemOpChains.push_back(Load.getValue(1));
5750           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5751           ArgOffset += PtrByteSize;
5752         } else {
5753           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5754           break;
5755         }
5756       }
5757       continue;
5758     }
5759 
5760     switch (Arg.getSimpleValueType().SimpleTy) {
5761     default: llvm_unreachable("Unexpected ValueType for argument!");
5762     case MVT::i1:
5763     case MVT::i32:
5764     case MVT::i64:
5765       if (GPR_idx != NumGPRs) {
5766         if (Arg.getValueType() == MVT::i1)
5767           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5768 
5769         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5770       } else {
5771         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5772                          isPPC64, isTailCall, false, MemOpChains,
5773                          TailCallArguments, dl);
5774       }
5775       ArgOffset += PtrByteSize;
5776       break;
5777     case MVT::f32:
5778     case MVT::f64:
5779       if (FPR_idx != NumFPRs) {
5780         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5781 
5782         if (isVarArg) {
5783           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5784                                        MachinePointerInfo(), false, false, 0);
5785           MemOpChains.push_back(Store);
5786 
5787           // Float varargs are always shadowed in available integer registers
5788           if (GPR_idx != NumGPRs) {
5789             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5790                                        MachinePointerInfo(), false, false,
5791                                        false, 0);
5792             MemOpChains.push_back(Load.getValue(1));
5793             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5794           }
5795           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5796             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5797             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5798             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5799                                        MachinePointerInfo(),
5800                                        false, false, false, 0);
5801             MemOpChains.push_back(Load.getValue(1));
5802             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5803           }
5804         } else {
5805           // If we have any FPRs remaining, we may also have GPRs remaining.
5806           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5807           // GPRs.
5808           if (GPR_idx != NumGPRs)
5809             ++GPR_idx;
5810           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5811               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5812             ++GPR_idx;
5813         }
5814       } else
5815         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5816                          isPPC64, isTailCall, false, MemOpChains,
5817                          TailCallArguments, dl);
5818       if (isPPC64)
5819         ArgOffset += 8;
5820       else
5821         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5822       break;
5823     case MVT::v4f32:
5824     case MVT::v4i32:
5825     case MVT::v8i16:
5826     case MVT::v16i8:
5827       if (isVarArg) {
5828         // These go aligned on the stack, or in the corresponding R registers
5829         // when within range.  The Darwin PPC ABI doc claims they also go in
5830         // V registers; in fact gcc does this only for arguments that are
5831         // prototyped, not for those that match the ...  We do it for all
5832         // arguments, seems to work.
5833         while (ArgOffset % 16 !=0) {
5834           ArgOffset += PtrByteSize;
5835           if (GPR_idx != NumGPRs)
5836             GPR_idx++;
5837         }
5838         // We could elide this store in the case where the object fits
5839         // entirely in R registers.  Maybe later.
5840         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5841                              DAG.getConstant(ArgOffset, dl, PtrVT));
5842         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5843                                      MachinePointerInfo(), false, false, 0);
5844         MemOpChains.push_back(Store);
5845         if (VR_idx != NumVRs) {
5846           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5847                                      MachinePointerInfo(),
5848                                      false, false, false, 0);
5849           MemOpChains.push_back(Load.getValue(1));
5850           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5851         }
5852         ArgOffset += 16;
5853         for (unsigned i=0; i<16; i+=PtrByteSize) {
5854           if (GPR_idx == NumGPRs)
5855             break;
5856           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5857                                    DAG.getConstant(i, dl, PtrVT));
5858           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5859                                      false, false, false, 0);
5860           MemOpChains.push_back(Load.getValue(1));
5861           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5862         }
5863         break;
5864       }
5865 
5866       // Non-varargs Altivec params generally go in registers, but have
5867       // stack space allocated at the end.
5868       if (VR_idx != NumVRs) {
5869         // Doesn't have GPR space allocated.
5870         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5871       } else if (nAltivecParamsAtEnd==0) {
5872         // We are emitting Altivec params in order.
5873         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5874                          isPPC64, isTailCall, true, MemOpChains,
5875                          TailCallArguments, dl);
5876         ArgOffset += 16;
5877       }
5878       break;
5879     }
5880   }
5881   // If all Altivec parameters fit in registers, as they usually do,
5882   // they get stack space following the non-Altivec parameters.  We
5883   // don't track this here because nobody below needs it.
5884   // If there are more Altivec parameters than fit in registers emit
5885   // the stores here.
5886   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5887     unsigned j = 0;
5888     // Offset is aligned; skip 1st 12 params which go in V registers.
5889     ArgOffset = ((ArgOffset+15)/16)*16;
5890     ArgOffset += 12*16;
5891     for (unsigned i = 0; i != NumOps; ++i) {
5892       SDValue Arg = OutVals[i];
5893       EVT ArgType = Outs[i].VT;
5894       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5895           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5896         if (++j > NumVRs) {
5897           SDValue PtrOff;
5898           // We are emitting Altivec params in order.
5899           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5900                            isPPC64, isTailCall, true, MemOpChains,
5901                            TailCallArguments, dl);
5902           ArgOffset += 16;
5903         }
5904       }
5905     }
5906   }
5907 
5908   if (!MemOpChains.empty())
5909     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5910 
5911   // On Darwin, R12 must contain the address of an indirect callee.  This does
5912   // not mean the MTCTR instruction must use R12; it's easier to model this as
5913   // an extra parameter, so do that.
5914   if (!isTailCall &&
5915       !isFunctionGlobalAddress(Callee) &&
5916       !isa<ExternalSymbolSDNode>(Callee) &&
5917       !isBLACompatibleAddress(Callee, DAG))
5918     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5919                                                    PPC::R12), Callee));
5920 
5921   // Build a sequence of copy-to-reg nodes chained together with token chain
5922   // and flag operands which copy the outgoing args into the appropriate regs.
5923   SDValue InFlag;
5924   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5925     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5926                              RegsToPass[i].second, InFlag);
5927     InFlag = Chain.getValue(1);
5928   }
5929 
5930   if (isTailCall)
5931     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5932                     FPOp, true, TailCallArguments);
5933 
5934   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5935                     /* unused except on PPC64 ELFv1 */ false, DAG,
5936                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5937                     NumBytes, Ins, InVals, CS);
5938 }
5939 
5940 bool
5941 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5942                                   MachineFunction &MF, bool isVarArg,
5943                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5944                                   LLVMContext &Context) const {
5945   SmallVector<CCValAssign, 16> RVLocs;
5946   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5947   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5948 }
5949 
5950 SDValue
5951 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5952                                bool isVarArg,
5953                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5954                                const SmallVectorImpl<SDValue> &OutVals,
5955                                const SDLoc &dl, SelectionDAG &DAG) const {
5956 
5957   SmallVector<CCValAssign, 16> RVLocs;
5958   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5959                  *DAG.getContext());
5960   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5961 
5962   SDValue Flag;
5963   SmallVector<SDValue, 4> RetOps(1, Chain);
5964 
5965   // Copy the result values into the output registers.
5966   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5967     CCValAssign &VA = RVLocs[i];
5968     assert(VA.isRegLoc() && "Can only return in registers!");
5969 
5970     SDValue Arg = OutVals[i];
5971 
5972     switch (VA.getLocInfo()) {
5973     default: llvm_unreachable("Unknown loc info!");
5974     case CCValAssign::Full: break;
5975     case CCValAssign::AExt:
5976       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5977       break;
5978     case CCValAssign::ZExt:
5979       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5980       break;
5981     case CCValAssign::SExt:
5982       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5983       break;
5984     }
5985 
5986     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5987     Flag = Chain.getValue(1);
5988     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5989   }
5990 
5991   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
5992   const MCPhysReg *I =
5993     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5994   if (I) {
5995     for (; *I; ++I) {
5996 
5997       if (PPC::G8RCRegClass.contains(*I))
5998         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5999       else if (PPC::F8RCRegClass.contains(*I))
6000         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6001       else if (PPC::CRRCRegClass.contains(*I))
6002         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6003       else if (PPC::VRRCRegClass.contains(*I))
6004         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6005       else
6006         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6007     }
6008   }
6009 
6010   RetOps[0] = Chain;  // Update chain.
6011 
6012   // Add the flag if we have it.
6013   if (Flag.getNode())
6014     RetOps.push_back(Flag);
6015 
6016   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6017 }
6018 
6019 SDValue PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(
6020     SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const {
6021   SDLoc dl(Op);
6022 
6023   // Get the corect type for integers.
6024   EVT IntVT = Op.getValueType();
6025 
6026   // Get the inputs.
6027   SDValue Chain = Op.getOperand(0);
6028   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6029   // Build a DYNAREAOFFSET node.
6030   SDValue Ops[2] = {Chain, FPSIdx};
6031   SDVTList VTs = DAG.getVTList(IntVT);
6032   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6033 }
6034 
6035 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
6036                                    const PPCSubtarget &Subtarget) const {
6037   // When we pop the dynamic allocation we need to restore the SP link.
6038   SDLoc dl(Op);
6039 
6040   // Get the corect type for pointers.
6041   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6042 
6043   // Construct the stack pointer operand.
6044   bool isPPC64 = Subtarget.isPPC64();
6045   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6046   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6047 
6048   // Get the operands for the STACKRESTORE.
6049   SDValue Chain = Op.getOperand(0);
6050   SDValue SaveSP = Op.getOperand(1);
6051 
6052   // Load the old link SP.
6053   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
6054                                    MachinePointerInfo(),
6055                                    false, false, false, 0);
6056 
6057   // Restore the stack pointer.
6058   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6059 
6060   // Store the old link SP.
6061   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
6062                       false, false, 0);
6063 }
6064 
6065 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6066   MachineFunction &MF = DAG.getMachineFunction();
6067   bool isPPC64 = Subtarget.isPPC64();
6068   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6069 
6070   // Get current frame pointer save index.  The users of this index will be
6071   // primarily DYNALLOC instructions.
6072   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6073   int RASI = FI->getReturnAddrSaveIndex();
6074 
6075   // If the frame pointer save index hasn't been defined yet.
6076   if (!RASI) {
6077     // Find out what the fix offset of the frame pointer save area.
6078     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6079     // Allocate the frame index for frame pointer save area.
6080     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6081     // Save the result.
6082     FI->setReturnAddrSaveIndex(RASI);
6083   }
6084   return DAG.getFrameIndex(RASI, PtrVT);
6085 }
6086 
6087 SDValue
6088 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6089   MachineFunction &MF = DAG.getMachineFunction();
6090   bool isPPC64 = Subtarget.isPPC64();
6091   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6092 
6093   // Get current frame pointer save index.  The users of this index will be
6094   // primarily DYNALLOC instructions.
6095   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6096   int FPSI = FI->getFramePointerSaveIndex();
6097 
6098   // If the frame pointer save index hasn't been defined yet.
6099   if (!FPSI) {
6100     // Find out what the fix offset of the frame pointer save area.
6101     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6102     // Allocate the frame index for frame pointer save area.
6103     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6104     // Save the result.
6105     FI->setFramePointerSaveIndex(FPSI);
6106   }
6107   return DAG.getFrameIndex(FPSI, PtrVT);
6108 }
6109 
6110 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6111                                          SelectionDAG &DAG,
6112                                          const PPCSubtarget &Subtarget) const {
6113   // Get the inputs.
6114   SDValue Chain = Op.getOperand(0);
6115   SDValue Size  = Op.getOperand(1);
6116   SDLoc dl(Op);
6117 
6118   // Get the corect type for pointers.
6119   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6120   // Negate the size.
6121   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6122                                 DAG.getConstant(0, dl, PtrVT), Size);
6123   // Construct a node for the frame pointer save index.
6124   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6125   // Build a DYNALLOC node.
6126   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6127   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6128   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6129 }
6130 
6131 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6132                                                SelectionDAG &DAG) const {
6133   SDLoc DL(Op);
6134   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6135                      DAG.getVTList(MVT::i32, MVT::Other),
6136                      Op.getOperand(0), Op.getOperand(1));
6137 }
6138 
6139 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6140                                                 SelectionDAG &DAG) const {
6141   SDLoc DL(Op);
6142   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6143                      Op.getOperand(0), Op.getOperand(1));
6144 }
6145 
6146 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6147   if (Op.getValueType().isVector())
6148     return LowerVectorLoad(Op, DAG);
6149 
6150   assert(Op.getValueType() == MVT::i1 &&
6151          "Custom lowering only for i1 loads");
6152 
6153   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6154 
6155   SDLoc dl(Op);
6156   LoadSDNode *LD = cast<LoadSDNode>(Op);
6157 
6158   SDValue Chain = LD->getChain();
6159   SDValue BasePtr = LD->getBasePtr();
6160   MachineMemOperand *MMO = LD->getMemOperand();
6161 
6162   SDValue NewLD =
6163       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6164                      BasePtr, MVT::i8, MMO);
6165   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6166 
6167   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6168   return DAG.getMergeValues(Ops, dl);
6169 }
6170 
6171 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6172   if (Op.getOperand(1).getValueType().isVector())
6173     return LowerVectorStore(Op, DAG);
6174 
6175   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6176          "Custom lowering only for i1 stores");
6177 
6178   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6179 
6180   SDLoc dl(Op);
6181   StoreSDNode *ST = cast<StoreSDNode>(Op);
6182 
6183   SDValue Chain = ST->getChain();
6184   SDValue BasePtr = ST->getBasePtr();
6185   SDValue Value = ST->getValue();
6186   MachineMemOperand *MMO = ST->getMemOperand();
6187 
6188   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6189                       Value);
6190   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6191 }
6192 
6193 // FIXME: Remove this once the ANDI glue bug is fixed:
6194 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6195   assert(Op.getValueType() == MVT::i1 &&
6196          "Custom lowering only for i1 results");
6197 
6198   SDLoc DL(Op);
6199   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6200                      Op.getOperand(0));
6201 }
6202 
6203 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6204 /// possible.
6205 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6206   // Not FP? Not a fsel.
6207   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6208       !Op.getOperand(2).getValueType().isFloatingPoint())
6209     return Op;
6210 
6211   // We might be able to do better than this under some circumstances, but in
6212   // general, fsel-based lowering of select is a finite-math-only optimization.
6213   // For more information, see section F.3 of the 2.06 ISA specification.
6214   if (!DAG.getTarget().Options.NoInfsFPMath ||
6215       !DAG.getTarget().Options.NoNaNsFPMath)
6216     return Op;
6217   // TODO: Propagate flags from the select rather than global settings.
6218   SDNodeFlags Flags;
6219   Flags.setNoInfs(true);
6220   Flags.setNoNaNs(true);
6221 
6222   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6223 
6224   EVT ResVT = Op.getValueType();
6225   EVT CmpVT = Op.getOperand(0).getValueType();
6226   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6227   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6228   SDLoc dl(Op);
6229 
6230   // If the RHS of the comparison is a 0.0, we don't need to do the
6231   // subtraction at all.
6232   SDValue Sel1;
6233   if (isFloatingPointZero(RHS))
6234     switch (CC) {
6235     default: break;       // SETUO etc aren't handled by fsel.
6236     case ISD::SETNE:
6237       std::swap(TV, FV);
6238     case ISD::SETEQ:
6239       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6240         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6241       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6242       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6243         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6244       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6245                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6246     case ISD::SETULT:
6247     case ISD::SETLT:
6248       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6249     case ISD::SETOGE:
6250     case ISD::SETGE:
6251       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6252         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6253       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6254     case ISD::SETUGT:
6255     case ISD::SETGT:
6256       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6257     case ISD::SETOLE:
6258     case ISD::SETLE:
6259       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6260         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6261       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6262                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6263     }
6264 
6265   SDValue Cmp;
6266   switch (CC) {
6267   default: break;       // SETUO etc aren't handled by fsel.
6268   case ISD::SETNE:
6269     std::swap(TV, FV);
6270   case ISD::SETEQ:
6271     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6272     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6273       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6274     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6275     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6276       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6277     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6278                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6279   case ISD::SETULT:
6280   case ISD::SETLT:
6281     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6282     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6283       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6284     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6285   case ISD::SETOGE:
6286   case ISD::SETGE:
6287     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6288     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6289       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6290     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6291   case ISD::SETUGT:
6292   case ISD::SETGT:
6293     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6294     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6295       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6296     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6297   case ISD::SETOLE:
6298   case ISD::SETLE:
6299     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6300     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6301       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6302     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6303   }
6304   return Op;
6305 }
6306 
6307 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6308                                                SelectionDAG &DAG,
6309                                                const SDLoc &dl) const {
6310   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6311   SDValue Src = Op.getOperand(0);
6312   if (Src.getValueType() == MVT::f32)
6313     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6314 
6315   SDValue Tmp;
6316   switch (Op.getSimpleValueType().SimpleTy) {
6317   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6318   case MVT::i32:
6319     Tmp = DAG.getNode(
6320         Op.getOpcode() == ISD::FP_TO_SINT
6321             ? PPCISD::FCTIWZ
6322             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6323         dl, MVT::f64, Src);
6324     break;
6325   case MVT::i64:
6326     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6327            "i64 FP_TO_UINT is supported only with FPCVT");
6328     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6329                                                         PPCISD::FCTIDUZ,
6330                       dl, MVT::f64, Src);
6331     break;
6332   }
6333 
6334   // Convert the FP value to an int value through memory.
6335   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6336     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6337   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6338   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6339   MachinePointerInfo MPI =
6340       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6341 
6342   // Emit a store to the stack slot.
6343   SDValue Chain;
6344   if (i32Stack) {
6345     MachineFunction &MF = DAG.getMachineFunction();
6346     MachineMemOperand *MMO =
6347       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6348     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6349     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6350               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6351   } else
6352     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6353                          MPI, false, false, 0);
6354 
6355   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6356   // add in a bias on big endian.
6357   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6358     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6359                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6360     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6361   }
6362 
6363   RLI.Chain = Chain;
6364   RLI.Ptr = FIPtr;
6365   RLI.MPI = MPI;
6366 }
6367 
6368 /// \brief Custom lowers floating point to integer conversions to use
6369 /// the direct move instructions available in ISA 2.07 to avoid the
6370 /// need for load/store combinations.
6371 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6372                                                     SelectionDAG &DAG,
6373                                                     const SDLoc &dl) const {
6374   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6375   SDValue Src = Op.getOperand(0);
6376 
6377   if (Src.getValueType() == MVT::f32)
6378     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6379 
6380   SDValue Tmp;
6381   switch (Op.getSimpleValueType().SimpleTy) {
6382   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6383   case MVT::i32:
6384     Tmp = DAG.getNode(
6385         Op.getOpcode() == ISD::FP_TO_SINT
6386             ? PPCISD::FCTIWZ
6387             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6388         dl, MVT::f64, Src);
6389     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6390     break;
6391   case MVT::i64:
6392     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6393            "i64 FP_TO_UINT is supported only with FPCVT");
6394     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6395                                                         PPCISD::FCTIDUZ,
6396                       dl, MVT::f64, Src);
6397     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6398     break;
6399   }
6400   return Tmp;
6401 }
6402 
6403 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6404                                           const SDLoc &dl) const {
6405   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6406     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6407 
6408   ReuseLoadInfo RLI;
6409   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6410 
6411   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6412                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6413                      RLI.Ranges);
6414 }
6415 
6416 // We're trying to insert a regular store, S, and then a load, L. If the
6417 // incoming value, O, is a load, we might just be able to have our load use the
6418 // address used by O. However, we don't know if anything else will store to
6419 // that address before we can load from it. To prevent this situation, we need
6420 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6421 // the same chain operand as O, we create a token factor from the chain results
6422 // of O and L, and we replace all uses of O's chain result with that token
6423 // factor (see spliceIntoChain below for this last part).
6424 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6425                                             ReuseLoadInfo &RLI,
6426                                             SelectionDAG &DAG,
6427                                             ISD::LoadExtType ET) const {
6428   SDLoc dl(Op);
6429   if (ET == ISD::NON_EXTLOAD &&
6430       (Op.getOpcode() == ISD::FP_TO_UINT ||
6431        Op.getOpcode() == ISD::FP_TO_SINT) &&
6432       isOperationLegalOrCustom(Op.getOpcode(),
6433                                Op.getOperand(0).getValueType())) {
6434 
6435     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6436     return true;
6437   }
6438 
6439   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6440   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6441       LD->isNonTemporal())
6442     return false;
6443   if (LD->getMemoryVT() != MemVT)
6444     return false;
6445 
6446   RLI.Ptr = LD->getBasePtr();
6447   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6448     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6449            "Non-pre-inc AM on PPC?");
6450     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6451                           LD->getOffset());
6452   }
6453 
6454   RLI.Chain = LD->getChain();
6455   RLI.MPI = LD->getPointerInfo();
6456   RLI.IsInvariant = LD->isInvariant();
6457   RLI.Alignment = LD->getAlignment();
6458   RLI.AAInfo = LD->getAAInfo();
6459   RLI.Ranges = LD->getRanges();
6460 
6461   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6462   return true;
6463 }
6464 
6465 // Given the head of the old chain, ResChain, insert a token factor containing
6466 // it and NewResChain, and make users of ResChain now be users of that token
6467 // factor.
6468 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6469                                         SDValue NewResChain,
6470                                         SelectionDAG &DAG) const {
6471   if (!ResChain)
6472     return;
6473 
6474   SDLoc dl(NewResChain);
6475 
6476   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6477                            NewResChain, DAG.getUNDEF(MVT::Other));
6478   assert(TF.getNode() != NewResChain.getNode() &&
6479          "A new TF really is required here");
6480 
6481   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6482   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6483 }
6484 
6485 /// \brief Analyze profitability of direct move
6486 /// prefer float load to int load plus direct move
6487 /// when there is no integer use of int load
6488 static bool directMoveIsProfitable(const SDValue &Op) {
6489   SDNode *Origin = Op.getOperand(0).getNode();
6490   if (Origin->getOpcode() != ISD::LOAD)
6491     return true;
6492 
6493   for (SDNode::use_iterator UI = Origin->use_begin(),
6494                             UE = Origin->use_end();
6495        UI != UE; ++UI) {
6496 
6497     // Only look at the users of the loaded value.
6498     if (UI.getUse().get().getResNo() != 0)
6499       continue;
6500 
6501     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6502         UI->getOpcode() != ISD::UINT_TO_FP)
6503       return true;
6504   }
6505 
6506   return false;
6507 }
6508 
6509 /// \brief Custom lowers integer to floating point conversions to use
6510 /// the direct move instructions available in ISA 2.07 to avoid the
6511 /// need for load/store combinations.
6512 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6513                                                     SelectionDAG &DAG,
6514                                                     const SDLoc &dl) const {
6515   assert((Op.getValueType() == MVT::f32 ||
6516           Op.getValueType() == MVT::f64) &&
6517          "Invalid floating point type as target of conversion");
6518   assert(Subtarget.hasFPCVT() &&
6519          "Int to FP conversions with direct moves require FPCVT");
6520   SDValue FP;
6521   SDValue Src = Op.getOperand(0);
6522   bool SinglePrec = Op.getValueType() == MVT::f32;
6523   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6524   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6525   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6526                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6527 
6528   if (WordInt) {
6529     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6530                      dl, MVT::f64, Src);
6531     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6532   }
6533   else {
6534     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6535     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6536   }
6537 
6538   return FP;
6539 }
6540 
6541 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6542                                           SelectionDAG &DAG) const {
6543   SDLoc dl(Op);
6544 
6545   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6546     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6547       return SDValue();
6548 
6549     SDValue Value = Op.getOperand(0);
6550     // The values are now known to be -1 (false) or 1 (true). To convert this
6551     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6552     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6553     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6554 
6555     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6556 
6557     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6558 
6559     if (Op.getValueType() != MVT::v4f64)
6560       Value = DAG.getNode(ISD::FP_ROUND, dl,
6561                           Op.getValueType(), Value,
6562                           DAG.getIntPtrConstant(1, dl));
6563     return Value;
6564   }
6565 
6566   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6567   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6568     return SDValue();
6569 
6570   if (Op.getOperand(0).getValueType() == MVT::i1)
6571     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6572                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6573                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6574 
6575   // If we have direct moves, we can do all the conversion, skip the store/load
6576   // however, without FPCVT we can't do most conversions.
6577   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6578       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6579     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6580 
6581   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6582          "UINT_TO_FP is supported only with FPCVT");
6583 
6584   // If we have FCFIDS, then use it when converting to single-precision.
6585   // Otherwise, convert to double-precision and then round.
6586   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6587                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6588                                                             : PPCISD::FCFIDS)
6589                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6590                                                             : PPCISD::FCFID);
6591   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6592                   ? MVT::f32
6593                   : MVT::f64;
6594 
6595   if (Op.getOperand(0).getValueType() == MVT::i64) {
6596     SDValue SINT = Op.getOperand(0);
6597     // When converting to single-precision, we actually need to convert
6598     // to double-precision first and then round to single-precision.
6599     // To avoid double-rounding effects during that operation, we have
6600     // to prepare the input operand.  Bits that might be truncated when
6601     // converting to double-precision are replaced by a bit that won't
6602     // be lost at this stage, but is below the single-precision rounding
6603     // position.
6604     //
6605     // However, if -enable-unsafe-fp-math is in effect, accept double
6606     // rounding to avoid the extra overhead.
6607     if (Op.getValueType() == MVT::f32 &&
6608         !Subtarget.hasFPCVT() &&
6609         !DAG.getTarget().Options.UnsafeFPMath) {
6610 
6611       // Twiddle input to make sure the low 11 bits are zero.  (If this
6612       // is the case, we are guaranteed the value will fit into the 53 bit
6613       // mantissa of an IEEE double-precision value without rounding.)
6614       // If any of those low 11 bits were not zero originally, make sure
6615       // bit 12 (value 2048) is set instead, so that the final rounding
6616       // to single-precision gets the correct result.
6617       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6618                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6619       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6620                           Round, DAG.getConstant(2047, dl, MVT::i64));
6621       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6622       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6623                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6624 
6625       // However, we cannot use that value unconditionally: if the magnitude
6626       // of the input value is small, the bit-twiddling we did above might
6627       // end up visibly changing the output.  Fortunately, in that case, we
6628       // don't need to twiddle bits since the original input will convert
6629       // exactly to double-precision floating-point already.  Therefore,
6630       // construct a conditional to use the original value if the top 11
6631       // bits are all sign-bit copies, and use the rounded value computed
6632       // above otherwise.
6633       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6634                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6635       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6636                          Cond, DAG.getConstant(1, dl, MVT::i64));
6637       Cond = DAG.getSetCC(dl, MVT::i32,
6638                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6639 
6640       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6641     }
6642 
6643     ReuseLoadInfo RLI;
6644     SDValue Bits;
6645 
6646     MachineFunction &MF = DAG.getMachineFunction();
6647     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6648       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6649                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6650                          RLI.Ranges);
6651       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6652     } else if (Subtarget.hasLFIWAX() &&
6653                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6654       MachineMemOperand *MMO =
6655         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6656                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6657       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6658       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6659                                      DAG.getVTList(MVT::f64, MVT::Other),
6660                                      Ops, MVT::i32, MMO);
6661       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6662     } else if (Subtarget.hasFPCVT() &&
6663                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6664       MachineMemOperand *MMO =
6665         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6666                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6667       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6668       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6669                                      DAG.getVTList(MVT::f64, MVT::Other),
6670                                      Ops, MVT::i32, MMO);
6671       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6672     } else if (((Subtarget.hasLFIWAX() &&
6673                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6674                 (Subtarget.hasFPCVT() &&
6675                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6676                SINT.getOperand(0).getValueType() == MVT::i32) {
6677       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6678       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6679 
6680       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6681       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6682 
6683       SDValue Store = DAG.getStore(
6684           DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6685           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6686           false, false, 0);
6687 
6688       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6689              "Expected an i32 store");
6690 
6691       RLI.Ptr = FIdx;
6692       RLI.Chain = Store;
6693       RLI.MPI =
6694           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6695       RLI.Alignment = 4;
6696 
6697       MachineMemOperand *MMO =
6698         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6699                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6700       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6701       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6702                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6703                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6704                                      Ops, MVT::i32, MMO);
6705     } else
6706       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6707 
6708     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6709 
6710     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6711       FP = DAG.getNode(ISD::FP_ROUND, dl,
6712                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6713     return FP;
6714   }
6715 
6716   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6717          "Unhandled INT_TO_FP type in custom expander!");
6718   // Since we only generate this in 64-bit mode, we can take advantage of
6719   // 64-bit registers.  In particular, sign extend the input value into the
6720   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6721   // then lfd it and fcfid it.
6722   MachineFunction &MF = DAG.getMachineFunction();
6723   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6724   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6725 
6726   SDValue Ld;
6727   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6728     ReuseLoadInfo RLI;
6729     bool ReusingLoad;
6730     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6731                                             DAG))) {
6732       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6733       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6734 
6735       SDValue Store = DAG.getStore(
6736           DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6737           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6738           false, false, 0);
6739 
6740       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6741              "Expected an i32 store");
6742 
6743       RLI.Ptr = FIdx;
6744       RLI.Chain = Store;
6745       RLI.MPI =
6746           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6747       RLI.Alignment = 4;
6748     }
6749 
6750     MachineMemOperand *MMO =
6751       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6752                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6753     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6754     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6755                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6756                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6757                                  Ops, MVT::i32, MMO);
6758     if (ReusingLoad)
6759       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6760   } else {
6761     assert(Subtarget.isPPC64() &&
6762            "i32->FP without LFIWAX supported only on PPC64");
6763 
6764     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6765     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6766 
6767     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6768                                 Op.getOperand(0));
6769 
6770     // STD the extended value into the stack slot.
6771     SDValue Store = DAG.getStore(
6772         DAG.getEntryNode(), dl, Ext64, FIdx,
6773         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6774         false, false, 0);
6775 
6776     // Load the value as a double.
6777     Ld = DAG.getLoad(
6778         MVT::f64, dl, Store, FIdx,
6779         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6780         false, false, false, 0);
6781   }
6782 
6783   // FCFID it and return it.
6784   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6785   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6786     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6787                      DAG.getIntPtrConstant(0, dl));
6788   return FP;
6789 }
6790 
6791 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6792                                             SelectionDAG &DAG) const {
6793   SDLoc dl(Op);
6794   /*
6795    The rounding mode is in bits 30:31 of FPSR, and has the following
6796    settings:
6797      00 Round to nearest
6798      01 Round to 0
6799      10 Round to +inf
6800      11 Round to -inf
6801 
6802   FLT_ROUNDS, on the other hand, expects the following:
6803     -1 Undefined
6804      0 Round to 0
6805      1 Round to nearest
6806      2 Round to +inf
6807      3 Round to -inf
6808 
6809   To perform the conversion, we do:
6810     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6811   */
6812 
6813   MachineFunction &MF = DAG.getMachineFunction();
6814   EVT VT = Op.getValueType();
6815   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6816 
6817   // Save FP Control Word to register
6818   EVT NodeTys[] = {
6819     MVT::f64,    // return register
6820     MVT::Glue    // unused in this context
6821   };
6822   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6823 
6824   // Save FP register to stack slot
6825   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6826   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6827   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6828                                StackSlot, MachinePointerInfo(), false, false,0);
6829 
6830   // Load FP Control Word from low 32 bits of stack slot.
6831   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6832   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6833   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6834                             false, false, false, 0);
6835 
6836   // Transform as necessary
6837   SDValue CWD1 =
6838     DAG.getNode(ISD::AND, dl, MVT::i32,
6839                 CWD, DAG.getConstant(3, dl, MVT::i32));
6840   SDValue CWD2 =
6841     DAG.getNode(ISD::SRL, dl, MVT::i32,
6842                 DAG.getNode(ISD::AND, dl, MVT::i32,
6843                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6844                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6845                             DAG.getConstant(3, dl, MVT::i32)),
6846                 DAG.getConstant(1, dl, MVT::i32));
6847 
6848   SDValue RetVal =
6849     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6850 
6851   return DAG.getNode((VT.getSizeInBits() < 16 ?
6852                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6853 }
6854 
6855 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6856   EVT VT = Op.getValueType();
6857   unsigned BitWidth = VT.getSizeInBits();
6858   SDLoc dl(Op);
6859   assert(Op.getNumOperands() == 3 &&
6860          VT == Op.getOperand(1).getValueType() &&
6861          "Unexpected SHL!");
6862 
6863   // Expand into a bunch of logical ops.  Note that these ops
6864   // depend on the PPC behavior for oversized shift amounts.
6865   SDValue Lo = Op.getOperand(0);
6866   SDValue Hi = Op.getOperand(1);
6867   SDValue Amt = Op.getOperand(2);
6868   EVT AmtVT = Amt.getValueType();
6869 
6870   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6871                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6872   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6873   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6874   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6875   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6876                              DAG.getConstant(-BitWidth, dl, AmtVT));
6877   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6878   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6879   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6880   SDValue OutOps[] = { OutLo, OutHi };
6881   return DAG.getMergeValues(OutOps, dl);
6882 }
6883 
6884 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6885   EVT VT = Op.getValueType();
6886   SDLoc dl(Op);
6887   unsigned BitWidth = VT.getSizeInBits();
6888   assert(Op.getNumOperands() == 3 &&
6889          VT == Op.getOperand(1).getValueType() &&
6890          "Unexpected SRL!");
6891 
6892   // Expand into a bunch of logical ops.  Note that these ops
6893   // depend on the PPC behavior for oversized shift amounts.
6894   SDValue Lo = Op.getOperand(0);
6895   SDValue Hi = Op.getOperand(1);
6896   SDValue Amt = Op.getOperand(2);
6897   EVT AmtVT = Amt.getValueType();
6898 
6899   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6900                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6901   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6902   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6903   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6904   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6905                              DAG.getConstant(-BitWidth, dl, AmtVT));
6906   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6907   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6908   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6909   SDValue OutOps[] = { OutLo, OutHi };
6910   return DAG.getMergeValues(OutOps, dl);
6911 }
6912 
6913 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6914   SDLoc dl(Op);
6915   EVT VT = Op.getValueType();
6916   unsigned BitWidth = VT.getSizeInBits();
6917   assert(Op.getNumOperands() == 3 &&
6918          VT == Op.getOperand(1).getValueType() &&
6919          "Unexpected SRA!");
6920 
6921   // Expand into a bunch of logical ops, followed by a select_cc.
6922   SDValue Lo = Op.getOperand(0);
6923   SDValue Hi = Op.getOperand(1);
6924   SDValue Amt = Op.getOperand(2);
6925   EVT AmtVT = Amt.getValueType();
6926 
6927   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6928                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6929   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6930   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6931   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6932   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6933                              DAG.getConstant(-BitWidth, dl, AmtVT));
6934   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6935   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6936   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6937                                   Tmp4, Tmp6, ISD::SETLE);
6938   SDValue OutOps[] = { OutLo, OutHi };
6939   return DAG.getMergeValues(OutOps, dl);
6940 }
6941 
6942 //===----------------------------------------------------------------------===//
6943 // Vector related lowering.
6944 //
6945 
6946 /// BuildSplatI - Build a canonical splati of Val with an element size of
6947 /// SplatSize.  Cast the result to VT.
6948 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6949                            SelectionDAG &DAG, const SDLoc &dl) {
6950   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6951 
6952   static const MVT VTys[] = { // canonical VT to use for each size.
6953     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6954   };
6955 
6956   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6957 
6958   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6959   if (Val == -1)
6960     SplatSize = 1;
6961 
6962   EVT CanonicalVT = VTys[SplatSize-1];
6963 
6964   // Build a canonical splat for this value.
6965   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
6966 }
6967 
6968 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6969 /// specified intrinsic ID.
6970 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
6971                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
6972   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6973   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6974                      DAG.getConstant(IID, dl, MVT::i32), Op);
6975 }
6976 
6977 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6978 /// specified intrinsic ID.
6979 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6980                                 SelectionDAG &DAG, const SDLoc &dl,
6981                                 EVT DestVT = MVT::Other) {
6982   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6983   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6984                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6985 }
6986 
6987 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6988 /// specified intrinsic ID.
6989 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6990                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
6991                                 EVT DestVT = MVT::Other) {
6992   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6993   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6994                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6995 }
6996 
6997 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6998 /// amount.  The result has the specified value type.
6999 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7000                            SelectionDAG &DAG, const SDLoc &dl) {
7001   // Force LHS/RHS to be the right type.
7002   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7003   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7004 
7005   int Ops[16];
7006   for (unsigned i = 0; i != 16; ++i)
7007     Ops[i] = i + Amt;
7008   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7009   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7010 }
7011 
7012 // If this is a case we can't handle, return null and let the default
7013 // expansion code take care of it.  If we CAN select this case, and if it
7014 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7015 // this case more efficiently than a constant pool load, lower it to the
7016 // sequence of ops that should be used.
7017 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7018                                              SelectionDAG &DAG) const {
7019   SDLoc dl(Op);
7020   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7021   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7022 
7023   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7024     // We first build an i32 vector, load it into a QPX register,
7025     // then convert it to a floating-point vector and compare it
7026     // to a zero vector to get the boolean result.
7027     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7028     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7029     MachinePointerInfo PtrInfo =
7030         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7031     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7032     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7033 
7034     assert(BVN->getNumOperands() == 4 &&
7035       "BUILD_VECTOR for v4i1 does not have 4 operands");
7036 
7037     bool IsConst = true;
7038     for (unsigned i = 0; i < 4; ++i) {
7039       if (BVN->getOperand(i).isUndef()) continue;
7040       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7041         IsConst = false;
7042         break;
7043       }
7044     }
7045 
7046     if (IsConst) {
7047       Constant *One =
7048         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7049       Constant *NegOne =
7050         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7051 
7052       Constant *CV[4];
7053       for (unsigned i = 0; i < 4; ++i) {
7054         if (BVN->getOperand(i).isUndef())
7055           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7056         else if (isNullConstant(BVN->getOperand(i)))
7057           CV[i] = NegOne;
7058         else
7059           CV[i] = One;
7060       }
7061 
7062       Constant *CP = ConstantVector::get(CV);
7063       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7064                                           16 /* alignment */);
7065 
7066       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7067       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7068       return DAG.getMemIntrinsicNode(
7069           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7070           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7071     }
7072 
7073     SmallVector<SDValue, 4> Stores;
7074     for (unsigned i = 0; i < 4; ++i) {
7075       if (BVN->getOperand(i).isUndef()) continue;
7076 
7077       unsigned Offset = 4*i;
7078       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7079       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7080 
7081       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7082       if (StoreSize > 4) {
7083         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
7084                                            BVN->getOperand(i), Idx,
7085                                            PtrInfo.getWithOffset(Offset),
7086                                            MVT::i32, false, false, 0));
7087       } else {
7088         SDValue StoreValue = BVN->getOperand(i);
7089         if (StoreSize < 4)
7090           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7091 
7092         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
7093                                       StoreValue, Idx,
7094                                       PtrInfo.getWithOffset(Offset),
7095                                       false, false, 0));
7096       }
7097     }
7098 
7099     SDValue StoreChain;
7100     if (!Stores.empty())
7101       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7102     else
7103       StoreChain = DAG.getEntryNode();
7104 
7105     // Now load from v4i32 into the QPX register; this will extend it to
7106     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7107     // is typed as v4f64 because the QPX register integer states are not
7108     // explicitly represented.
7109 
7110     SDValue Ops[] = {StoreChain,
7111                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7112                      FIdx};
7113     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7114 
7115     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7116       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7117     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7118       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7119       LoadedVect);
7120 
7121     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7122 
7123     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7124   }
7125 
7126   // All other QPX vectors are handled by generic code.
7127   if (Subtarget.hasQPX())
7128     return SDValue();
7129 
7130   // Check if this is a splat of a constant value.
7131   APInt APSplatBits, APSplatUndef;
7132   unsigned SplatBitSize;
7133   bool HasAnyUndefs;
7134   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7135                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7136       SplatBitSize > 32)
7137     return SDValue();
7138 
7139   unsigned SplatBits = APSplatBits.getZExtValue();
7140   unsigned SplatUndef = APSplatUndef.getZExtValue();
7141   unsigned SplatSize = SplatBitSize / 8;
7142 
7143   // First, handle single instruction cases.
7144 
7145   // All zeros?
7146   if (SplatBits == 0) {
7147     // Canonicalize all zero vectors to be v4i32.
7148     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7149       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7150       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7151     }
7152     return Op;
7153   }
7154 
7155   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7156   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7157                     (32-SplatBitSize));
7158   if (SextVal >= -16 && SextVal <= 15)
7159     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7160 
7161   // Two instruction sequences.
7162 
7163   // If this value is in the range [-32,30] and is even, use:
7164   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7165   // If this value is in the range [17,31] and is odd, use:
7166   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7167   // If this value is in the range [-31,-17] and is odd, use:
7168   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7169   // Note the last two are three-instruction sequences.
7170   if (SextVal >= -32 && SextVal <= 31) {
7171     // To avoid having these optimizations undone by constant folding,
7172     // we convert to a pseudo that will be expanded later into one of
7173     // the above forms.
7174     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7175     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7176               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7177     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7178     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7179     if (VT == Op.getValueType())
7180       return RetVal;
7181     else
7182       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7183   }
7184 
7185   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7186   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7187   // for fneg/fabs.
7188   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7189     // Make -1 and vspltisw -1:
7190     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7191 
7192     // Make the VSLW intrinsic, computing 0x8000_0000.
7193     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7194                                    OnesV, DAG, dl);
7195 
7196     // xor by OnesV to invert it.
7197     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7198     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7199   }
7200 
7201   // Check to see if this is a wide variety of vsplti*, binop self cases.
7202   static const signed char SplatCsts[] = {
7203     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7204     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7205   };
7206 
7207   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7208     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7209     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7210     int i = SplatCsts[idx];
7211 
7212     // Figure out what shift amount will be used by altivec if shifted by i in
7213     // this splat size.
7214     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7215 
7216     // vsplti + shl self.
7217     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7218       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7219       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7220         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7221         Intrinsic::ppc_altivec_vslw
7222       };
7223       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7224       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7225     }
7226 
7227     // vsplti + srl self.
7228     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7229       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7230       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7231         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7232         Intrinsic::ppc_altivec_vsrw
7233       };
7234       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7235       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7236     }
7237 
7238     // vsplti + sra self.
7239     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7240       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7241       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7242         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7243         Intrinsic::ppc_altivec_vsraw
7244       };
7245       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7246       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7247     }
7248 
7249     // vsplti + rol self.
7250     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7251                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7252       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7253       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7254         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7255         Intrinsic::ppc_altivec_vrlw
7256       };
7257       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7258       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7259     }
7260 
7261     // t = vsplti c, result = vsldoi t, t, 1
7262     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7263       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7264       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7265       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7266     }
7267     // t = vsplti c, result = vsldoi t, t, 2
7268     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7269       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7270       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7271       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7272     }
7273     // t = vsplti c, result = vsldoi t, t, 3
7274     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7275       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7276       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7277       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7278     }
7279   }
7280 
7281   return SDValue();
7282 }
7283 
7284 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7285 /// the specified operations to build the shuffle.
7286 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7287                                       SDValue RHS, SelectionDAG &DAG,
7288                                       const SDLoc &dl) {
7289   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7290   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7291   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7292 
7293   enum {
7294     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7295     OP_VMRGHW,
7296     OP_VMRGLW,
7297     OP_VSPLTISW0,
7298     OP_VSPLTISW1,
7299     OP_VSPLTISW2,
7300     OP_VSPLTISW3,
7301     OP_VSLDOI4,
7302     OP_VSLDOI8,
7303     OP_VSLDOI12
7304   };
7305 
7306   if (OpNum == OP_COPY) {
7307     if (LHSID == (1*9+2)*9+3) return LHS;
7308     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7309     return RHS;
7310   }
7311 
7312   SDValue OpLHS, OpRHS;
7313   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7314   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7315 
7316   int ShufIdxs[16];
7317   switch (OpNum) {
7318   default: llvm_unreachable("Unknown i32 permute!");
7319   case OP_VMRGHW:
7320     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7321     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7322     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7323     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7324     break;
7325   case OP_VMRGLW:
7326     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7327     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7328     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7329     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7330     break;
7331   case OP_VSPLTISW0:
7332     for (unsigned i = 0; i != 16; ++i)
7333       ShufIdxs[i] = (i&3)+0;
7334     break;
7335   case OP_VSPLTISW1:
7336     for (unsigned i = 0; i != 16; ++i)
7337       ShufIdxs[i] = (i&3)+4;
7338     break;
7339   case OP_VSPLTISW2:
7340     for (unsigned i = 0; i != 16; ++i)
7341       ShufIdxs[i] = (i&3)+8;
7342     break;
7343   case OP_VSPLTISW3:
7344     for (unsigned i = 0; i != 16; ++i)
7345       ShufIdxs[i] = (i&3)+12;
7346     break;
7347   case OP_VSLDOI4:
7348     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7349   case OP_VSLDOI8:
7350     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7351   case OP_VSLDOI12:
7352     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7353   }
7354   EVT VT = OpLHS.getValueType();
7355   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7356   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7357   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7358   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7359 }
7360 
7361 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7362 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7363 /// return the code it can be lowered into.  Worst case, it can always be
7364 /// lowered into a vperm.
7365 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7366                                                SelectionDAG &DAG) const {
7367   SDLoc dl(Op);
7368   SDValue V1 = Op.getOperand(0);
7369   SDValue V2 = Op.getOperand(1);
7370   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7371   EVT VT = Op.getValueType();
7372   bool isLittleEndian = Subtarget.isLittleEndian();
7373 
7374   if (Subtarget.hasVSX()) {
7375     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7376       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7377       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7378       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7379                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7380       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7381     }
7382   }
7383 
7384   if (Subtarget.hasQPX()) {
7385     if (VT.getVectorNumElements() != 4)
7386       return SDValue();
7387 
7388     if (V2.isUndef()) V2 = V1;
7389 
7390     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7391     if (AlignIdx != -1) {
7392       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7393                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7394     } else if (SVOp->isSplat()) {
7395       int SplatIdx = SVOp->getSplatIndex();
7396       if (SplatIdx >= 4) {
7397         std::swap(V1, V2);
7398         SplatIdx -= 4;
7399       }
7400 
7401       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7402                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7403     }
7404 
7405     // Lower this into a qvgpci/qvfperm pair.
7406 
7407     // Compute the qvgpci literal
7408     unsigned idx = 0;
7409     for (unsigned i = 0; i < 4; ++i) {
7410       int m = SVOp->getMaskElt(i);
7411       unsigned mm = m >= 0 ? (unsigned) m : i;
7412       idx |= mm << (3-i)*3;
7413     }
7414 
7415     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7416                              DAG.getConstant(idx, dl, MVT::i32));
7417     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7418   }
7419 
7420   // Cases that are handled by instructions that take permute immediates
7421   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7422   // selected by the instruction selector.
7423   if (V2.isUndef()) {
7424     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7425         PPC::isSplatShuffleMask(SVOp, 2) ||
7426         PPC::isSplatShuffleMask(SVOp, 4) ||
7427         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7428         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7429         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7430         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7431         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7432         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7433         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7434         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7435         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7436         (Subtarget.hasP8Altivec() && (
7437          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7438          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7439          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7440       return Op;
7441     }
7442   }
7443 
7444   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7445   // and produce a fixed permutation.  If any of these match, do not lower to
7446   // VPERM.
7447   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7448   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7449       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7450       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7451       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7452       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7453       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7454       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7455       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7456       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7457       (Subtarget.hasP8Altivec() && (
7458        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7459        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7460        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7461     return Op;
7462 
7463   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7464   // perfect shuffle table to emit an optimal matching sequence.
7465   ArrayRef<int> PermMask = SVOp->getMask();
7466 
7467   unsigned PFIndexes[4];
7468   bool isFourElementShuffle = true;
7469   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7470     unsigned EltNo = 8;   // Start out undef.
7471     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7472       if (PermMask[i*4+j] < 0)
7473         continue;   // Undef, ignore it.
7474 
7475       unsigned ByteSource = PermMask[i*4+j];
7476       if ((ByteSource & 3) != j) {
7477         isFourElementShuffle = false;
7478         break;
7479       }
7480 
7481       if (EltNo == 8) {
7482         EltNo = ByteSource/4;
7483       } else if (EltNo != ByteSource/4) {
7484         isFourElementShuffle = false;
7485         break;
7486       }
7487     }
7488     PFIndexes[i] = EltNo;
7489   }
7490 
7491   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7492   // perfect shuffle vector to determine if it is cost effective to do this as
7493   // discrete instructions, or whether we should use a vperm.
7494   // For now, we skip this for little endian until such time as we have a
7495   // little-endian perfect shuffle table.
7496   if (isFourElementShuffle && !isLittleEndian) {
7497     // Compute the index in the perfect shuffle table.
7498     unsigned PFTableIndex =
7499       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7500 
7501     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7502     unsigned Cost  = (PFEntry >> 30);
7503 
7504     // Determining when to avoid vperm is tricky.  Many things affect the cost
7505     // of vperm, particularly how many times the perm mask needs to be computed.
7506     // For example, if the perm mask can be hoisted out of a loop or is already
7507     // used (perhaps because there are multiple permutes with the same shuffle
7508     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7509     // the loop requires an extra register.
7510     //
7511     // As a compromise, we only emit discrete instructions if the shuffle can be
7512     // generated in 3 or fewer operations.  When we have loop information
7513     // available, if this block is within a loop, we should avoid using vperm
7514     // for 3-operation perms and use a constant pool load instead.
7515     if (Cost < 3)
7516       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7517   }
7518 
7519   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7520   // vector that will get spilled to the constant pool.
7521   if (V2.isUndef()) V2 = V1;
7522 
7523   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7524   // that it is in input element units, not in bytes.  Convert now.
7525 
7526   // For little endian, the order of the input vectors is reversed, and
7527   // the permutation mask is complemented with respect to 31.  This is
7528   // necessary to produce proper semantics with the big-endian-biased vperm
7529   // instruction.
7530   EVT EltVT = V1.getValueType().getVectorElementType();
7531   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7532 
7533   SmallVector<SDValue, 16> ResultMask;
7534   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7535     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7536 
7537     for (unsigned j = 0; j != BytesPerElement; ++j)
7538       if (isLittleEndian)
7539         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7540                                              dl, MVT::i32));
7541       else
7542         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7543                                              MVT::i32));
7544   }
7545 
7546   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7547   if (isLittleEndian)
7548     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7549                        V2, V1, VPermMask);
7550   else
7551     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7552                        V1, V2, VPermMask);
7553 }
7554 
7555 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7556 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7557 /// information about the intrinsic.
7558 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7559                                  bool &isDot, const PPCSubtarget &Subtarget) {
7560   unsigned IntrinsicID =
7561     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7562   CompareOpc = -1;
7563   isDot = false;
7564   switch (IntrinsicID) {
7565   default: return false;
7566     // Comparison predicates.
7567   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7568   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7569   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7570   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7571   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7572   case Intrinsic::ppc_altivec_vcmpequd_p:
7573     if (Subtarget.hasP8Altivec()) {
7574       CompareOpc = 199;
7575       isDot = 1;
7576     } else
7577       return false;
7578 
7579     break;
7580   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7581   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7582   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7583   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7584   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7585   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7586     if (Subtarget.hasP8Altivec()) {
7587       CompareOpc = 967;
7588       isDot = 1;
7589     } else
7590       return false;
7591 
7592     break;
7593   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7594   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7595   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7596   case Intrinsic::ppc_altivec_vcmpgtud_p:
7597     if (Subtarget.hasP8Altivec()) {
7598       CompareOpc = 711;
7599       isDot = 1;
7600     } else
7601       return false;
7602 
7603     break;
7604     // VSX predicate comparisons use the same infrastructure
7605   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7606   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7607   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7608   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7609   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7610   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7611     if (Subtarget.hasVSX()) {
7612       switch (IntrinsicID) {
7613       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7614       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7615       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7616       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7617       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7618       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7619       }
7620       isDot = 1;
7621     }
7622     else
7623       return false;
7624 
7625     break;
7626 
7627     // Normal Comparisons.
7628   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7629   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7630   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7631   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7632   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7633   case Intrinsic::ppc_altivec_vcmpequd:
7634     if (Subtarget.hasP8Altivec()) {
7635       CompareOpc = 199;
7636       isDot = 0;
7637     } else
7638       return false;
7639 
7640     break;
7641   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7642   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7643   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7644   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7645   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7646   case Intrinsic::ppc_altivec_vcmpgtsd:
7647     if (Subtarget.hasP8Altivec()) {
7648       CompareOpc = 967;
7649       isDot = 0;
7650     } else
7651       return false;
7652 
7653     break;
7654   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7655   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7656   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7657   case Intrinsic::ppc_altivec_vcmpgtud:
7658     if (Subtarget.hasP8Altivec()) {
7659       CompareOpc = 711;
7660       isDot = 0;
7661     } else
7662       return false;
7663 
7664     break;
7665   }
7666   return true;
7667 }
7668 
7669 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7670 /// lower, do it, otherwise return null.
7671 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7672                                                    SelectionDAG &DAG) const {
7673   unsigned IntrinsicID =
7674     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7675 
7676   if (IntrinsicID == Intrinsic::thread_pointer) {
7677     // Reads the thread pointer register, used for __builtin_thread_pointer.
7678     bool is64bit = Subtarget.isPPC64();
7679     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7680                            is64bit ? MVT::i64 : MVT::i32);
7681   }
7682 
7683   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7684   // opcode number of the comparison.
7685   SDLoc dl(Op);
7686   int CompareOpc;
7687   bool isDot;
7688   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7689     return SDValue();    // Don't custom lower most intrinsics.
7690 
7691   // If this is a non-dot comparison, make the VCMP node and we are done.
7692   if (!isDot) {
7693     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7694                               Op.getOperand(1), Op.getOperand(2),
7695                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7696     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7697   }
7698 
7699   // Create the PPCISD altivec 'dot' comparison node.
7700   SDValue Ops[] = {
7701     Op.getOperand(2),  // LHS
7702     Op.getOperand(3),  // RHS
7703     DAG.getConstant(CompareOpc, dl, MVT::i32)
7704   };
7705   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7706   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7707 
7708   // Now that we have the comparison, emit a copy from the CR to a GPR.
7709   // This is flagged to the above dot comparison.
7710   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7711                                 DAG.getRegister(PPC::CR6, MVT::i32),
7712                                 CompNode.getValue(1));
7713 
7714   // Unpack the result based on how the target uses it.
7715   unsigned BitNo;   // Bit # of CR6.
7716   bool InvertBit;   // Invert result?
7717   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7718   default:  // Can't happen, don't crash on invalid number though.
7719   case 0:   // Return the value of the EQ bit of CR6.
7720     BitNo = 0; InvertBit = false;
7721     break;
7722   case 1:   // Return the inverted value of the EQ bit of CR6.
7723     BitNo = 0; InvertBit = true;
7724     break;
7725   case 2:   // Return the value of the LT bit of CR6.
7726     BitNo = 2; InvertBit = false;
7727     break;
7728   case 3:   // Return the inverted value of the LT bit of CR6.
7729     BitNo = 2; InvertBit = true;
7730     break;
7731   }
7732 
7733   // Shift the bit into the low position.
7734   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7735                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7736   // Isolate the bit.
7737   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7738                       DAG.getConstant(1, dl, MVT::i32));
7739 
7740   // If we are supposed to, toggle the bit.
7741   if (InvertBit)
7742     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7743                         DAG.getConstant(1, dl, MVT::i32));
7744   return Flags;
7745 }
7746 
7747 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7748                                                   SelectionDAG &DAG) const {
7749   SDLoc dl(Op);
7750   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7751   // instructions), but for smaller types, we need to first extend up to v2i32
7752   // before doing going farther.
7753   if (Op.getValueType() == MVT::v2i64) {
7754     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7755     if (ExtVT != MVT::v2i32) {
7756       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7757       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7758                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7759                                         ExtVT.getVectorElementType(), 4)));
7760       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7761       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7762                        DAG.getValueType(MVT::v2i32));
7763     }
7764 
7765     return Op;
7766   }
7767 
7768   return SDValue();
7769 }
7770 
7771 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7772                                                    SelectionDAG &DAG) const {
7773   SDLoc dl(Op);
7774   // Create a stack slot that is 16-byte aligned.
7775   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7776   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7777   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7778   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7779 
7780   // Store the input value into Value#0 of the stack slot.
7781   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7782                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7783                                false, false, 0);
7784   // Load it out.
7785   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7786                      false, false, false, 0);
7787 }
7788 
7789 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7790                                                    SelectionDAG &DAG) const {
7791   SDLoc dl(Op);
7792   SDNode *N = Op.getNode();
7793 
7794   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7795          "Unknown extract_vector_elt type");
7796 
7797   SDValue Value = N->getOperand(0);
7798 
7799   // The first part of this is like the store lowering except that we don't
7800   // need to track the chain.
7801 
7802   // The values are now known to be -1 (false) or 1 (true). To convert this
7803   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7804   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7805   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7806 
7807   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7808   // understand how to form the extending load.
7809   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7810 
7811   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7812 
7813   // Now convert to an integer and store.
7814   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7815     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7816     Value);
7817 
7818   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7819   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7820   MachinePointerInfo PtrInfo =
7821       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7822   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7823   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7824 
7825   SDValue StoreChain = DAG.getEntryNode();
7826   SDValue Ops[] = {StoreChain,
7827                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7828                    Value, FIdx};
7829   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7830 
7831   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7832     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7833 
7834   // Extract the value requested.
7835   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7836   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7837   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7838 
7839   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7840                                PtrInfo.getWithOffset(Offset),
7841                                false, false, false, 0);
7842 
7843   if (!Subtarget.useCRBits())
7844     return IntVal;
7845 
7846   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7847 }
7848 
7849 /// Lowering for QPX v4i1 loads
7850 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7851                                            SelectionDAG &DAG) const {
7852   SDLoc dl(Op);
7853   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7854   SDValue LoadChain = LN->getChain();
7855   SDValue BasePtr = LN->getBasePtr();
7856 
7857   if (Op.getValueType() == MVT::v4f64 ||
7858       Op.getValueType() == MVT::v4f32) {
7859     EVT MemVT = LN->getMemoryVT();
7860     unsigned Alignment = LN->getAlignment();
7861 
7862     // If this load is properly aligned, then it is legal.
7863     if (Alignment >= MemVT.getStoreSize())
7864       return Op;
7865 
7866     EVT ScalarVT = Op.getValueType().getScalarType(),
7867         ScalarMemVT = MemVT.getScalarType();
7868     unsigned Stride = ScalarMemVT.getStoreSize();
7869 
7870     SDValue Vals[4], LoadChains[4];
7871     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7872       SDValue Load;
7873       if (ScalarVT != ScalarMemVT)
7874         Load =
7875           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7876                          BasePtr,
7877                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7878                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7879                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7880                          LN->getAAInfo());
7881       else
7882         Load =
7883           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7884                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7885                        LN->isVolatile(), LN->isNonTemporal(),
7886                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7887                        LN->getAAInfo());
7888 
7889       if (Idx == 0 && LN->isIndexed()) {
7890         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7891                "Unknown addressing mode on vector load");
7892         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7893                                   LN->getAddressingMode());
7894       }
7895 
7896       Vals[Idx] = Load;
7897       LoadChains[Idx] = Load.getValue(1);
7898 
7899       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7900                             DAG.getConstant(Stride, dl,
7901                                             BasePtr.getValueType()));
7902     }
7903 
7904     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7905     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7906 
7907     if (LN->isIndexed()) {
7908       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7909       return DAG.getMergeValues(RetOps, dl);
7910     }
7911 
7912     SDValue RetOps[] = { Value, TF };
7913     return DAG.getMergeValues(RetOps, dl);
7914   }
7915 
7916   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7917   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7918 
7919   // To lower v4i1 from a byte array, we load the byte elements of the
7920   // vector and then reuse the BUILD_VECTOR logic.
7921 
7922   SDValue VectElmts[4], VectElmtChains[4];
7923   for (unsigned i = 0; i < 4; ++i) {
7924     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7925     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7926 
7927     VectElmts[i] = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
7928                                   LN->getPointerInfo().getWithOffset(i),
7929                                   MVT::i8 /* memory type */, LN->isVolatile(),
7930                                   LN->isNonTemporal(), LN->isInvariant(),
7931                                   1 /* alignment */, LN->getAAInfo());
7932     VectElmtChains[i] = VectElmts[i].getValue(1);
7933   }
7934 
7935   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7936   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
7937 
7938   SDValue RVals[] = { Value, LoadChain };
7939   return DAG.getMergeValues(RVals, dl);
7940 }
7941 
7942 /// Lowering for QPX v4i1 stores
7943 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7944                                             SelectionDAG &DAG) const {
7945   SDLoc dl(Op);
7946   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7947   SDValue StoreChain = SN->getChain();
7948   SDValue BasePtr = SN->getBasePtr();
7949   SDValue Value = SN->getValue();
7950 
7951   if (Value.getValueType() == MVT::v4f64 ||
7952       Value.getValueType() == MVT::v4f32) {
7953     EVT MemVT = SN->getMemoryVT();
7954     unsigned Alignment = SN->getAlignment();
7955 
7956     // If this store is properly aligned, then it is legal.
7957     if (Alignment >= MemVT.getStoreSize())
7958       return Op;
7959 
7960     EVT ScalarVT = Value.getValueType().getScalarType(),
7961         ScalarMemVT = MemVT.getScalarType();
7962     unsigned Stride = ScalarMemVT.getStoreSize();
7963 
7964     SDValue Stores[4];
7965     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7966       SDValue Ex = DAG.getNode(
7967           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7968           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
7969       SDValue Store;
7970       if (ScalarVT != ScalarMemVT)
7971         Store =
7972           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7973                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7974                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7975                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7976       else
7977         Store =
7978           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7979                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7980                        SN->isVolatile(), SN->isNonTemporal(),
7981                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7982 
7983       if (Idx == 0 && SN->isIndexed()) {
7984         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7985                "Unknown addressing mode on vector store");
7986         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7987                                     SN->getAddressingMode());
7988       }
7989 
7990       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7991                             DAG.getConstant(Stride, dl,
7992                                             BasePtr.getValueType()));
7993       Stores[Idx] = Store;
7994     }
7995 
7996     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7997 
7998     if (SN->isIndexed()) {
7999       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8000       return DAG.getMergeValues(RetOps, dl);
8001     }
8002 
8003     return TF;
8004   }
8005 
8006   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8007   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8008 
8009   // The values are now known to be -1 (false) or 1 (true). To convert this
8010   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8011   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8012   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8013 
8014   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8015   // understand how to form the extending load.
8016   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8017 
8018   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8019 
8020   // Now convert to an integer and store.
8021   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8022     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8023     Value);
8024 
8025   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
8026   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
8027   MachinePointerInfo PtrInfo =
8028       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8029   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8030   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8031 
8032   SDValue Ops[] = {StoreChain,
8033                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8034                    Value, FIdx};
8035   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8036 
8037   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8038     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8039 
8040   // Move data into the byte array.
8041   SDValue Loads[4], LoadChains[4];
8042   for (unsigned i = 0; i < 4; ++i) {
8043     unsigned Offset = 4*i;
8044     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8045     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8046 
8047     Loads[i] =
8048         DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8049                     PtrInfo.getWithOffset(Offset), false, false, false, 0);
8050     LoadChains[i] = Loads[i].getValue(1);
8051   }
8052 
8053   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8054 
8055   SDValue Stores[4];
8056   for (unsigned i = 0; i < 4; ++i) {
8057     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8058     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8059 
8060     Stores[i] = DAG.getTruncStore(
8061         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8062         MVT::i8 /* memory type */, SN->isNonTemporal(), SN->isVolatile(),
8063         1 /* alignment */, SN->getAAInfo());
8064   }
8065 
8066   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8067 
8068   return StoreChain;
8069 }
8070 
8071 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8072   SDLoc dl(Op);
8073   if (Op.getValueType() == MVT::v4i32) {
8074     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8075 
8076     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8077     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8078 
8079     SDValue RHSSwap =   // = vrlw RHS, 16
8080       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8081 
8082     // Shrinkify inputs to v8i16.
8083     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8084     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8085     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8086 
8087     // Low parts multiplied together, generating 32-bit results (we ignore the
8088     // top parts).
8089     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8090                                         LHS, RHS, DAG, dl, MVT::v4i32);
8091 
8092     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8093                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8094     // Shift the high parts up 16 bits.
8095     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8096                               Neg16, DAG, dl);
8097     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8098   } else if (Op.getValueType() == MVT::v8i16) {
8099     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8100 
8101     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8102 
8103     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8104                             LHS, RHS, Zero, DAG, dl);
8105   } else if (Op.getValueType() == MVT::v16i8) {
8106     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8107     bool isLittleEndian = Subtarget.isLittleEndian();
8108 
8109     // Multiply the even 8-bit parts, producing 16-bit sums.
8110     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8111                                            LHS, RHS, DAG, dl, MVT::v8i16);
8112     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8113 
8114     // Multiply the odd 8-bit parts, producing 16-bit sums.
8115     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8116                                           LHS, RHS, DAG, dl, MVT::v8i16);
8117     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8118 
8119     // Merge the results together.  Because vmuleub and vmuloub are
8120     // instructions with a big-endian bias, we must reverse the
8121     // element numbering and reverse the meaning of "odd" and "even"
8122     // when generating little endian code.
8123     int Ops[16];
8124     for (unsigned i = 0; i != 8; ++i) {
8125       if (isLittleEndian) {
8126         Ops[i*2  ] = 2*i;
8127         Ops[i*2+1] = 2*i+16;
8128       } else {
8129         Ops[i*2  ] = 2*i+1;
8130         Ops[i*2+1] = 2*i+1+16;
8131       }
8132     }
8133     if (isLittleEndian)
8134       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8135     else
8136       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8137   } else {
8138     llvm_unreachable("Unknown mul to lower!");
8139   }
8140 }
8141 
8142 /// LowerOperation - Provide custom lowering hooks for some operations.
8143 ///
8144 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8145   switch (Op.getOpcode()) {
8146   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8147   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8148   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8149   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8150   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8151   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8152   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8153   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8154   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8155   case ISD::VASTART:
8156     return LowerVASTART(Op, DAG, Subtarget);
8157 
8158   case ISD::VAARG:
8159     return LowerVAARG(Op, DAG, Subtarget);
8160 
8161   case ISD::VACOPY:
8162     return LowerVACOPY(Op, DAG, Subtarget);
8163 
8164   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
8165   case ISD::DYNAMIC_STACKALLOC:
8166     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
8167   case ISD::GET_DYNAMIC_AREA_OFFSET: return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG, Subtarget);
8168 
8169   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8170   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8171 
8172   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8173   case ISD::STORE:              return LowerSTORE(Op, DAG);
8174   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8175   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8176   case ISD::FP_TO_UINT:
8177   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8178                                                       SDLoc(Op));
8179   case ISD::UINT_TO_FP:
8180   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8181   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8182 
8183   // Lower 64-bit shifts.
8184   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8185   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8186   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8187 
8188   // Vector-related lowering.
8189   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8190   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8191   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8192   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8193   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8194   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8195   case ISD::MUL:                return LowerMUL(Op, DAG);
8196 
8197   // For counter-based loop handling.
8198   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8199 
8200   // Frame & Return address.
8201   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8202   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8203   }
8204 }
8205 
8206 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8207                                            SmallVectorImpl<SDValue>&Results,
8208                                            SelectionDAG &DAG) const {
8209   SDLoc dl(N);
8210   switch (N->getOpcode()) {
8211   default:
8212     llvm_unreachable("Do not know how to custom type legalize this operation!");
8213   case ISD::READCYCLECOUNTER: {
8214     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8215     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8216 
8217     Results.push_back(RTB);
8218     Results.push_back(RTB.getValue(1));
8219     Results.push_back(RTB.getValue(2));
8220     break;
8221   }
8222   case ISD::INTRINSIC_W_CHAIN: {
8223     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8224         Intrinsic::ppc_is_decremented_ctr_nonzero)
8225       break;
8226 
8227     assert(N->getValueType(0) == MVT::i1 &&
8228            "Unexpected result type for CTR decrement intrinsic");
8229     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8230                                  N->getValueType(0));
8231     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8232     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8233                                  N->getOperand(1));
8234 
8235     Results.push_back(NewInt);
8236     Results.push_back(NewInt.getValue(1));
8237     break;
8238   }
8239   case ISD::VAARG: {
8240     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8241       return;
8242 
8243     EVT VT = N->getValueType(0);
8244 
8245     if (VT == MVT::i64) {
8246       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
8247 
8248       Results.push_back(NewNode);
8249       Results.push_back(NewNode.getValue(1));
8250     }
8251     return;
8252   }
8253   case ISD::FP_ROUND_INREG: {
8254     assert(N->getValueType(0) == MVT::ppcf128);
8255     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8256     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8257                              MVT::f64, N->getOperand(0),
8258                              DAG.getIntPtrConstant(0, dl));
8259     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8260                              MVT::f64, N->getOperand(0),
8261                              DAG.getIntPtrConstant(1, dl));
8262 
8263     // Add the two halves of the long double in round-to-zero mode.
8264     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8265 
8266     // We know the low half is about to be thrown away, so just use something
8267     // convenient.
8268     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8269                                 FPreg, FPreg));
8270     return;
8271   }
8272   case ISD::FP_TO_SINT:
8273   case ISD::FP_TO_UINT:
8274     // LowerFP_TO_INT() can only handle f32 and f64.
8275     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8276       return;
8277     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8278     return;
8279   }
8280 }
8281 
8282 //===----------------------------------------------------------------------===//
8283 //  Other Lowering Code
8284 //===----------------------------------------------------------------------===//
8285 
8286 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8287   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8288   Function *Func = Intrinsic::getDeclaration(M, Id);
8289   return Builder.CreateCall(Func, {});
8290 }
8291 
8292 // The mappings for emitLeading/TrailingFence is taken from
8293 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8294 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8295                                          AtomicOrdering Ord, bool IsStore,
8296                                          bool IsLoad) const {
8297   if (Ord == AtomicOrdering::SequentiallyConsistent)
8298     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8299   if (isReleaseOrStronger(Ord))
8300     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8301   return nullptr;
8302 }
8303 
8304 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8305                                           AtomicOrdering Ord, bool IsStore,
8306                                           bool IsLoad) const {
8307   if (IsLoad && isAcquireOrStronger(Ord))
8308     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8309   // FIXME: this is too conservative, a dependent branch + isync is enough.
8310   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8311   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8312   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8313   return nullptr;
8314 }
8315 
8316 MachineBasicBlock *
8317 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
8318                                     unsigned AtomicSize,
8319                                     unsigned BinOpcode) const {
8320   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8321   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8322 
8323   auto LoadMnemonic = PPC::LDARX;
8324   auto StoreMnemonic = PPC::STDCX;
8325   switch (AtomicSize) {
8326   default:
8327     llvm_unreachable("Unexpected size of atomic entity");
8328   case 1:
8329     LoadMnemonic = PPC::LBARX;
8330     StoreMnemonic = PPC::STBCX;
8331     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8332     break;
8333   case 2:
8334     LoadMnemonic = PPC::LHARX;
8335     StoreMnemonic = PPC::STHCX;
8336     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8337     break;
8338   case 4:
8339     LoadMnemonic = PPC::LWARX;
8340     StoreMnemonic = PPC::STWCX;
8341     break;
8342   case 8:
8343     LoadMnemonic = PPC::LDARX;
8344     StoreMnemonic = PPC::STDCX;
8345     break;
8346   }
8347 
8348   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8349   MachineFunction *F = BB->getParent();
8350   MachineFunction::iterator It = ++BB->getIterator();
8351 
8352   unsigned dest = MI->getOperand(0).getReg();
8353   unsigned ptrA = MI->getOperand(1).getReg();
8354   unsigned ptrB = MI->getOperand(2).getReg();
8355   unsigned incr = MI->getOperand(3).getReg();
8356   DebugLoc dl = MI->getDebugLoc();
8357 
8358   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8359   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8360   F->insert(It, loopMBB);
8361   F->insert(It, exitMBB);
8362   exitMBB->splice(exitMBB->begin(), BB,
8363                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8364   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8365 
8366   MachineRegisterInfo &RegInfo = F->getRegInfo();
8367   unsigned TmpReg = (!BinOpcode) ? incr :
8368     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8369                                            : &PPC::GPRCRegClass);
8370 
8371   //  thisMBB:
8372   //   ...
8373   //   fallthrough --> loopMBB
8374   BB->addSuccessor(loopMBB);
8375 
8376   //  loopMBB:
8377   //   l[wd]arx dest, ptr
8378   //   add r0, dest, incr
8379   //   st[wd]cx. r0, ptr
8380   //   bne- loopMBB
8381   //   fallthrough --> exitMBB
8382   BB = loopMBB;
8383   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8384     .addReg(ptrA).addReg(ptrB);
8385   if (BinOpcode)
8386     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8387   BuildMI(BB, dl, TII->get(StoreMnemonic))
8388     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8389   BuildMI(BB, dl, TII->get(PPC::BCC))
8390     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8391   BB->addSuccessor(loopMBB);
8392   BB->addSuccessor(exitMBB);
8393 
8394   //  exitMBB:
8395   //   ...
8396   BB = exitMBB;
8397   return BB;
8398 }
8399 
8400 MachineBasicBlock *
8401 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8402                                             MachineBasicBlock *BB,
8403                                             bool is8bit,    // operation
8404                                             unsigned BinOpcode) const {
8405   // If we support part-word atomic mnemonics, just use them
8406   if (Subtarget.hasPartwordAtomics())
8407     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8408 
8409   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8410   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8411   // In 64 bit mode we have to use 64 bits for addresses, even though the
8412   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8413   // registers without caring whether they're 32 or 64, but here we're
8414   // doing actual arithmetic on the addresses.
8415   bool is64bit = Subtarget.isPPC64();
8416   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
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   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8438                                           : &PPC::GPRCRegClass;
8439   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8440   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8441   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8442   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8443   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8444   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8445   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8446   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8447   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8448   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8449   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8450   unsigned Ptr1Reg;
8451   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8452 
8453   //  thisMBB:
8454   //   ...
8455   //   fallthrough --> loopMBB
8456   BB->addSuccessor(loopMBB);
8457 
8458   // The 4-byte load must be aligned, while a char or short may be
8459   // anywhere in the word.  Hence all this nasty bookkeeping code.
8460   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8461   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8462   //   xori shift, shift1, 24 [16]
8463   //   rlwinm ptr, ptr1, 0, 0, 29
8464   //   slw incr2, incr, shift
8465   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8466   //   slw mask, mask2, shift
8467   //  loopMBB:
8468   //   lwarx tmpDest, ptr
8469   //   add tmp, tmpDest, incr2
8470   //   andc tmp2, tmpDest, mask
8471   //   and tmp3, tmp, mask
8472   //   or tmp4, tmp3, tmp2
8473   //   stwcx. tmp4, ptr
8474   //   bne- loopMBB
8475   //   fallthrough --> exitMBB
8476   //   srw dest, tmpDest, shift
8477   if (ptrA != ZeroReg) {
8478     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8479     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8480       .addReg(ptrA).addReg(ptrB);
8481   } else {
8482     Ptr1Reg = ptrB;
8483   }
8484   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8485       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8486   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8487       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8488   if (is64bit)
8489     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8490       .addReg(Ptr1Reg).addImm(0).addImm(61);
8491   else
8492     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8493       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8494   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8495       .addReg(incr).addReg(ShiftReg);
8496   if (is8bit)
8497     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8498   else {
8499     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8500     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8501   }
8502   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8503       .addReg(Mask2Reg).addReg(ShiftReg);
8504 
8505   BB = loopMBB;
8506   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8507     .addReg(ZeroReg).addReg(PtrReg);
8508   if (BinOpcode)
8509     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8510       .addReg(Incr2Reg).addReg(TmpDestReg);
8511   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8512     .addReg(TmpDestReg).addReg(MaskReg);
8513   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8514     .addReg(TmpReg).addReg(MaskReg);
8515   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8516     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8517   BuildMI(BB, dl, TII->get(PPC::STWCX))
8518     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8519   BuildMI(BB, dl, TII->get(PPC::BCC))
8520     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8521   BB->addSuccessor(loopMBB);
8522   BB->addSuccessor(exitMBB);
8523 
8524   //  exitMBB:
8525   //   ...
8526   BB = exitMBB;
8527   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8528     .addReg(ShiftReg);
8529   return BB;
8530 }
8531 
8532 llvm::MachineBasicBlock*
8533 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8534                                     MachineBasicBlock *MBB) const {
8535   DebugLoc DL = MI->getDebugLoc();
8536   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8537 
8538   MachineFunction *MF = MBB->getParent();
8539   MachineRegisterInfo &MRI = MF->getRegInfo();
8540 
8541   const BasicBlock *BB = MBB->getBasicBlock();
8542   MachineFunction::iterator I = ++MBB->getIterator();
8543 
8544   // Memory Reference
8545   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8546   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8547 
8548   unsigned DstReg = MI->getOperand(0).getReg();
8549   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8550   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8551   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8552   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8553 
8554   MVT PVT = getPointerTy(MF->getDataLayout());
8555   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8556          "Invalid Pointer Size!");
8557   // For v = setjmp(buf), we generate
8558   //
8559   // thisMBB:
8560   //  SjLjSetup mainMBB
8561   //  bl mainMBB
8562   //  v_restore = 1
8563   //  b sinkMBB
8564   //
8565   // mainMBB:
8566   //  buf[LabelOffset] = LR
8567   //  v_main = 0
8568   //
8569   // sinkMBB:
8570   //  v = phi(main, restore)
8571   //
8572 
8573   MachineBasicBlock *thisMBB = MBB;
8574   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8575   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8576   MF->insert(I, mainMBB);
8577   MF->insert(I, sinkMBB);
8578 
8579   MachineInstrBuilder MIB;
8580 
8581   // Transfer the remainder of BB and its successor edges to sinkMBB.
8582   sinkMBB->splice(sinkMBB->begin(), MBB,
8583                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8584   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8585 
8586   // Note that the structure of the jmp_buf used here is not compatible
8587   // with that used by libc, and is not designed to be. Specifically, it
8588   // stores only those 'reserved' registers that LLVM does not otherwise
8589   // understand how to spill. Also, by convention, by the time this
8590   // intrinsic is called, Clang has already stored the frame address in the
8591   // first slot of the buffer and stack address in the third. Following the
8592   // X86 target code, we'll store the jump address in the second slot. We also
8593   // need to save the TOC pointer (R2) to handle jumps between shared
8594   // libraries, and that will be stored in the fourth slot. The thread
8595   // identifier (R13) is not affected.
8596 
8597   // thisMBB:
8598   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8599   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8600   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8601 
8602   // Prepare IP either in reg.
8603   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8604   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8605   unsigned BufReg = MI->getOperand(1).getReg();
8606 
8607   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8608     setUsesTOCBasePtr(*MBB->getParent());
8609     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8610             .addReg(PPC::X2)
8611             .addImm(TOCOffset)
8612             .addReg(BufReg);
8613     MIB.setMemRefs(MMOBegin, MMOEnd);
8614   }
8615 
8616   // Naked functions never have a base pointer, and so we use r1. For all
8617   // other functions, this decision must be delayed until during PEI.
8618   unsigned BaseReg;
8619   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8620     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8621   else
8622     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8623 
8624   MIB = BuildMI(*thisMBB, MI, DL,
8625                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8626             .addReg(BaseReg)
8627             .addImm(BPOffset)
8628             .addReg(BufReg);
8629   MIB.setMemRefs(MMOBegin, MMOEnd);
8630 
8631   // Setup
8632   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8633   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8634   MIB.addRegMask(TRI->getNoPreservedMask());
8635 
8636   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8637 
8638   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8639           .addMBB(mainMBB);
8640   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8641 
8642   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8643   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8644 
8645   // mainMBB:
8646   //  mainDstReg = 0
8647   MIB =
8648       BuildMI(mainMBB, DL,
8649               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8650 
8651   // Store IP
8652   if (Subtarget.isPPC64()) {
8653     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8654             .addReg(LabelReg)
8655             .addImm(LabelOffset)
8656             .addReg(BufReg);
8657   } else {
8658     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8659             .addReg(LabelReg)
8660             .addImm(LabelOffset)
8661             .addReg(BufReg);
8662   }
8663 
8664   MIB.setMemRefs(MMOBegin, MMOEnd);
8665 
8666   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8667   mainMBB->addSuccessor(sinkMBB);
8668 
8669   // sinkMBB:
8670   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8671           TII->get(PPC::PHI), DstReg)
8672     .addReg(mainDstReg).addMBB(mainMBB)
8673     .addReg(restoreDstReg).addMBB(thisMBB);
8674 
8675   MI->eraseFromParent();
8676   return sinkMBB;
8677 }
8678 
8679 MachineBasicBlock *
8680 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8681                                      MachineBasicBlock *MBB) const {
8682   DebugLoc DL = MI->getDebugLoc();
8683   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8684 
8685   MachineFunction *MF = MBB->getParent();
8686   MachineRegisterInfo &MRI = MF->getRegInfo();
8687 
8688   // Memory Reference
8689   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8690   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8691 
8692   MVT PVT = getPointerTy(MF->getDataLayout());
8693   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8694          "Invalid Pointer Size!");
8695 
8696   const TargetRegisterClass *RC =
8697     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8698   unsigned Tmp = MRI.createVirtualRegister(RC);
8699   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8700   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8701   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8702   unsigned BP =
8703       (PVT == MVT::i64)
8704           ? PPC::X30
8705           : (Subtarget.isSVR4ABI() &&
8706                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8707                  ? PPC::R29
8708                  : PPC::R30);
8709 
8710   MachineInstrBuilder MIB;
8711 
8712   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8713   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8714   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8715   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8716 
8717   unsigned BufReg = MI->getOperand(0).getReg();
8718 
8719   // Reload FP (the jumped-to function may not have had a
8720   // frame pointer, and if so, then its r31 will be restored
8721   // as necessary).
8722   if (PVT == MVT::i64) {
8723     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8724             .addImm(0)
8725             .addReg(BufReg);
8726   } else {
8727     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8728             .addImm(0)
8729             .addReg(BufReg);
8730   }
8731   MIB.setMemRefs(MMOBegin, MMOEnd);
8732 
8733   // Reload IP
8734   if (PVT == MVT::i64) {
8735     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8736             .addImm(LabelOffset)
8737             .addReg(BufReg);
8738   } else {
8739     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8740             .addImm(LabelOffset)
8741             .addReg(BufReg);
8742   }
8743   MIB.setMemRefs(MMOBegin, MMOEnd);
8744 
8745   // Reload SP
8746   if (PVT == MVT::i64) {
8747     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8748             .addImm(SPOffset)
8749             .addReg(BufReg);
8750   } else {
8751     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8752             .addImm(SPOffset)
8753             .addReg(BufReg);
8754   }
8755   MIB.setMemRefs(MMOBegin, MMOEnd);
8756 
8757   // Reload BP
8758   if (PVT == MVT::i64) {
8759     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8760             .addImm(BPOffset)
8761             .addReg(BufReg);
8762   } else {
8763     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8764             .addImm(BPOffset)
8765             .addReg(BufReg);
8766   }
8767   MIB.setMemRefs(MMOBegin, MMOEnd);
8768 
8769   // Reload TOC
8770   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8771     setUsesTOCBasePtr(*MBB->getParent());
8772     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8773             .addImm(TOCOffset)
8774             .addReg(BufReg);
8775 
8776     MIB.setMemRefs(MMOBegin, MMOEnd);
8777   }
8778 
8779   // Jump
8780   BuildMI(*MBB, MI, DL,
8781           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8782   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8783 
8784   MI->eraseFromParent();
8785   return MBB;
8786 }
8787 
8788 MachineBasicBlock *
8789 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8790                                                MachineBasicBlock *BB) const {
8791   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8792       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8793     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8794         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8795       // Call lowering should have added an r2 operand to indicate a dependence
8796       // on the TOC base pointer value. It can't however, because there is no
8797       // way to mark the dependence as implicit there, and so the stackmap code
8798       // will confuse it with a regular operand. Instead, add the dependence
8799       // here.
8800       setUsesTOCBasePtr(*BB->getParent());
8801       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8802     }
8803 
8804     return emitPatchPoint(MI, BB);
8805   }
8806 
8807   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8808       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8809     return emitEHSjLjSetJmp(MI, BB);
8810   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8811              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8812     return emitEHSjLjLongJmp(MI, BB);
8813   }
8814 
8815   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8816 
8817   // To "insert" these instructions we actually have to insert their
8818   // control-flow patterns.
8819   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8820   MachineFunction::iterator It = ++BB->getIterator();
8821 
8822   MachineFunction *F = BB->getParent();
8823 
8824   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8825                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8826                               MI->getOpcode() == PPC::SELECT_I4 ||
8827                               MI->getOpcode() == PPC::SELECT_I8)) {
8828     SmallVector<MachineOperand, 2> Cond;
8829     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8830         MI->getOpcode() == PPC::SELECT_CC_I8)
8831       Cond.push_back(MI->getOperand(4));
8832     else
8833       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8834     Cond.push_back(MI->getOperand(1));
8835 
8836     DebugLoc dl = MI->getDebugLoc();
8837     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8838                       Cond, MI->getOperand(2).getReg(),
8839                       MI->getOperand(3).getReg());
8840   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8841              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8842              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8843              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8844              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8845              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8846              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8847              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8848              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8849              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8850              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8851              MI->getOpcode() == PPC::SELECT_I4 ||
8852              MI->getOpcode() == PPC::SELECT_I8 ||
8853              MI->getOpcode() == PPC::SELECT_F4 ||
8854              MI->getOpcode() == PPC::SELECT_F8 ||
8855              MI->getOpcode() == PPC::SELECT_QFRC ||
8856              MI->getOpcode() == PPC::SELECT_QSRC ||
8857              MI->getOpcode() == PPC::SELECT_QBRC ||
8858              MI->getOpcode() == PPC::SELECT_VRRC ||
8859              MI->getOpcode() == PPC::SELECT_VSFRC ||
8860              MI->getOpcode() == PPC::SELECT_VSSRC ||
8861              MI->getOpcode() == PPC::SELECT_VSRC) {
8862     // The incoming instruction knows the destination vreg to set, the
8863     // condition code register to branch on, the true/false values to
8864     // select between, and a branch opcode to use.
8865 
8866     //  thisMBB:
8867     //  ...
8868     //   TrueVal = ...
8869     //   cmpTY ccX, r1, r2
8870     //   bCC copy1MBB
8871     //   fallthrough --> copy0MBB
8872     MachineBasicBlock *thisMBB = BB;
8873     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8874     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8875     DebugLoc dl = MI->getDebugLoc();
8876     F->insert(It, copy0MBB);
8877     F->insert(It, sinkMBB);
8878 
8879     // Transfer the remainder of BB and its successor edges to sinkMBB.
8880     sinkMBB->splice(sinkMBB->begin(), BB,
8881                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8882     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8883 
8884     // Next, add the true and fallthrough blocks as its successors.
8885     BB->addSuccessor(copy0MBB);
8886     BB->addSuccessor(sinkMBB);
8887 
8888     if (MI->getOpcode() == PPC::SELECT_I4 ||
8889         MI->getOpcode() == PPC::SELECT_I8 ||
8890         MI->getOpcode() == PPC::SELECT_F4 ||
8891         MI->getOpcode() == PPC::SELECT_F8 ||
8892         MI->getOpcode() == PPC::SELECT_QFRC ||
8893         MI->getOpcode() == PPC::SELECT_QSRC ||
8894         MI->getOpcode() == PPC::SELECT_QBRC ||
8895         MI->getOpcode() == PPC::SELECT_VRRC ||
8896         MI->getOpcode() == PPC::SELECT_VSFRC ||
8897         MI->getOpcode() == PPC::SELECT_VSSRC ||
8898         MI->getOpcode() == PPC::SELECT_VSRC) {
8899       BuildMI(BB, dl, TII->get(PPC::BC))
8900         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8901     } else {
8902       unsigned SelectPred = MI->getOperand(4).getImm();
8903       BuildMI(BB, dl, TII->get(PPC::BCC))
8904         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8905     }
8906 
8907     //  copy0MBB:
8908     //   %FalseValue = ...
8909     //   # fallthrough to sinkMBB
8910     BB = copy0MBB;
8911 
8912     // Update machine-CFG edges
8913     BB->addSuccessor(sinkMBB);
8914 
8915     //  sinkMBB:
8916     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8917     //  ...
8918     BB = sinkMBB;
8919     BuildMI(*BB, BB->begin(), dl,
8920             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8921       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8922       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8923   } else if (MI->getOpcode() == PPC::ReadTB) {
8924     // To read the 64-bit time-base register on a 32-bit target, we read the
8925     // two halves. Should the counter have wrapped while it was being read, we
8926     // need to try again.
8927     // ...
8928     // readLoop:
8929     // mfspr Rx,TBU # load from TBU
8930     // mfspr Ry,TB  # load from TB
8931     // mfspr Rz,TBU # load from TBU
8932     // cmpw crX,Rx,Rz # check if 'old'='new'
8933     // bne readLoop   # branch if they're not equal
8934     // ...
8935 
8936     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8937     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8938     DebugLoc dl = MI->getDebugLoc();
8939     F->insert(It, readMBB);
8940     F->insert(It, sinkMBB);
8941 
8942     // Transfer the remainder of BB and its successor edges to sinkMBB.
8943     sinkMBB->splice(sinkMBB->begin(), BB,
8944                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8945     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8946 
8947     BB->addSuccessor(readMBB);
8948     BB = readMBB;
8949 
8950     MachineRegisterInfo &RegInfo = F->getRegInfo();
8951     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8952     unsigned LoReg = MI->getOperand(0).getReg();
8953     unsigned HiReg = MI->getOperand(1).getReg();
8954 
8955     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8956     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8957     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8958 
8959     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8960 
8961     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8962       .addReg(HiReg).addReg(ReadAgainReg);
8963     BuildMI(BB, dl, TII->get(PPC::BCC))
8964       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8965 
8966     BB->addSuccessor(readMBB);
8967     BB->addSuccessor(sinkMBB);
8968   }
8969   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8970     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8971   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8972     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8973   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8974     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8975   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8976     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8977 
8978   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8979     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8980   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8981     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8982   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8983     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8984   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8985     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8986 
8987   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8988     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8989   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8990     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8991   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8992     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8993   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8994     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8995 
8996   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8997     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8998   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8999     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9000   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9001     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9002   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9003     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9004 
9005   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9006     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9007   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9008     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9009   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9010     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9011   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9012     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9013 
9014   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9015     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9016   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9017     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9018   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9019     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9020   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9021     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9022 
9023   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
9024     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9025   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
9026     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9027   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
9028     BB = EmitAtomicBinary(MI, BB, 4, 0);
9029   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
9030     BB = EmitAtomicBinary(MI, BB, 8, 0);
9031 
9032   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9033            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9034            (Subtarget.hasPartwordAtomics() &&
9035             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9036            (Subtarget.hasPartwordAtomics() &&
9037             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9038     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9039 
9040     auto LoadMnemonic = PPC::LDARX;
9041     auto StoreMnemonic = PPC::STDCX;
9042     switch(MI->getOpcode()) {
9043     default:
9044       llvm_unreachable("Compare and swap of unknown size");
9045     case PPC::ATOMIC_CMP_SWAP_I8:
9046       LoadMnemonic = PPC::LBARX;
9047       StoreMnemonic = PPC::STBCX;
9048       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9049       break;
9050     case PPC::ATOMIC_CMP_SWAP_I16:
9051       LoadMnemonic = PPC::LHARX;
9052       StoreMnemonic = PPC::STHCX;
9053       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9054       break;
9055     case PPC::ATOMIC_CMP_SWAP_I32:
9056       LoadMnemonic = PPC::LWARX;
9057       StoreMnemonic = PPC::STWCX;
9058       break;
9059     case PPC::ATOMIC_CMP_SWAP_I64:
9060       LoadMnemonic = PPC::LDARX;
9061       StoreMnemonic = PPC::STDCX;
9062       break;
9063     }
9064     unsigned dest   = MI->getOperand(0).getReg();
9065     unsigned ptrA   = MI->getOperand(1).getReg();
9066     unsigned ptrB   = MI->getOperand(2).getReg();
9067     unsigned oldval = MI->getOperand(3).getReg();
9068     unsigned newval = MI->getOperand(4).getReg();
9069     DebugLoc dl     = MI->getDebugLoc();
9070 
9071     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9072     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9073     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9074     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9075     F->insert(It, loop1MBB);
9076     F->insert(It, loop2MBB);
9077     F->insert(It, midMBB);
9078     F->insert(It, exitMBB);
9079     exitMBB->splice(exitMBB->begin(), BB,
9080                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9081     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9082 
9083     //  thisMBB:
9084     //   ...
9085     //   fallthrough --> loopMBB
9086     BB->addSuccessor(loop1MBB);
9087 
9088     // loop1MBB:
9089     //   l[bhwd]arx dest, ptr
9090     //   cmp[wd] dest, oldval
9091     //   bne- midMBB
9092     // loop2MBB:
9093     //   st[bhwd]cx. newval, ptr
9094     //   bne- loopMBB
9095     //   b exitBB
9096     // midMBB:
9097     //   st[bhwd]cx. dest, ptr
9098     // exitBB:
9099     BB = loop1MBB;
9100     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9101       .addReg(ptrA).addReg(ptrB);
9102     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9103       .addReg(oldval).addReg(dest);
9104     BuildMI(BB, dl, TII->get(PPC::BCC))
9105       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9106     BB->addSuccessor(loop2MBB);
9107     BB->addSuccessor(midMBB);
9108 
9109     BB = loop2MBB;
9110     BuildMI(BB, dl, TII->get(StoreMnemonic))
9111       .addReg(newval).addReg(ptrA).addReg(ptrB);
9112     BuildMI(BB, dl, TII->get(PPC::BCC))
9113       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9114     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9115     BB->addSuccessor(loop1MBB);
9116     BB->addSuccessor(exitMBB);
9117 
9118     BB = midMBB;
9119     BuildMI(BB, dl, TII->get(StoreMnemonic))
9120       .addReg(dest).addReg(ptrA).addReg(ptrB);
9121     BB->addSuccessor(exitMBB);
9122 
9123     //  exitMBB:
9124     //   ...
9125     BB = exitMBB;
9126   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9127              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9128     // We must use 64-bit registers for addresses when targeting 64-bit,
9129     // since we're actually doing arithmetic on them.  Other registers
9130     // can be 32-bit.
9131     bool is64bit = Subtarget.isPPC64();
9132     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
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     MachineRegisterInfo &RegInfo = F->getRegInfo();
9154     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9155                                             : &PPC::GPRCRegClass;
9156     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9157     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9158     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
9159     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9160     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9161     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9162     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9163     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9164     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9165     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9166     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9167     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9168     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9169     unsigned Ptr1Reg;
9170     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9171     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9172     //  thisMBB:
9173     //   ...
9174     //   fallthrough --> loopMBB
9175     BB->addSuccessor(loop1MBB);
9176 
9177     // The 4-byte load must be aligned, while a char or short may be
9178     // anywhere in the word.  Hence all this nasty bookkeeping code.
9179     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9180     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9181     //   xori shift, shift1, 24 [16]
9182     //   rlwinm ptr, ptr1, 0, 0, 29
9183     //   slw newval2, newval, shift
9184     //   slw oldval2, oldval,shift
9185     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9186     //   slw mask, mask2, shift
9187     //   and newval3, newval2, mask
9188     //   and oldval3, oldval2, mask
9189     // loop1MBB:
9190     //   lwarx tmpDest, ptr
9191     //   and tmp, tmpDest, mask
9192     //   cmpw tmp, oldval3
9193     //   bne- midMBB
9194     // loop2MBB:
9195     //   andc tmp2, tmpDest, mask
9196     //   or tmp4, tmp2, newval3
9197     //   stwcx. tmp4, ptr
9198     //   bne- loop1MBB
9199     //   b exitBB
9200     // midMBB:
9201     //   stwcx. tmpDest, ptr
9202     // exitBB:
9203     //   srw dest, tmpDest, shift
9204     if (ptrA != ZeroReg) {
9205       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9206       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9207         .addReg(ptrA).addReg(ptrB);
9208     } else {
9209       Ptr1Reg = ptrB;
9210     }
9211     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9212         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9213     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9214         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9215     if (is64bit)
9216       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9217         .addReg(Ptr1Reg).addImm(0).addImm(61);
9218     else
9219       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9220         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9221     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9222         .addReg(newval).addReg(ShiftReg);
9223     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9224         .addReg(oldval).addReg(ShiftReg);
9225     if (is8bit)
9226       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9227     else {
9228       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9229       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9230         .addReg(Mask3Reg).addImm(65535);
9231     }
9232     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9233         .addReg(Mask2Reg).addReg(ShiftReg);
9234     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9235         .addReg(NewVal2Reg).addReg(MaskReg);
9236     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9237         .addReg(OldVal2Reg).addReg(MaskReg);
9238 
9239     BB = loop1MBB;
9240     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9241         .addReg(ZeroReg).addReg(PtrReg);
9242     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9243         .addReg(TmpDestReg).addReg(MaskReg);
9244     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9245         .addReg(TmpReg).addReg(OldVal3Reg);
9246     BuildMI(BB, dl, TII->get(PPC::BCC))
9247         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9248     BB->addSuccessor(loop2MBB);
9249     BB->addSuccessor(midMBB);
9250 
9251     BB = loop2MBB;
9252     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9253         .addReg(TmpDestReg).addReg(MaskReg);
9254     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9255         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9256     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9257         .addReg(ZeroReg).addReg(PtrReg);
9258     BuildMI(BB, dl, TII->get(PPC::BCC))
9259       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9260     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9261     BB->addSuccessor(loop1MBB);
9262     BB->addSuccessor(exitMBB);
9263 
9264     BB = midMBB;
9265     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9266       .addReg(ZeroReg).addReg(PtrReg);
9267     BB->addSuccessor(exitMBB);
9268 
9269     //  exitMBB:
9270     //   ...
9271     BB = exitMBB;
9272     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9273       .addReg(ShiftReg);
9274   } else if (MI->getOpcode() == PPC::FADDrtz) {
9275     // This pseudo performs an FADD with rounding mode temporarily forced
9276     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9277     // is not modeled at the SelectionDAG level.
9278     unsigned Dest = MI->getOperand(0).getReg();
9279     unsigned Src1 = MI->getOperand(1).getReg();
9280     unsigned Src2 = MI->getOperand(2).getReg();
9281     DebugLoc dl   = MI->getDebugLoc();
9282 
9283     MachineRegisterInfo &RegInfo = F->getRegInfo();
9284     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9285 
9286     // Save FPSCR value.
9287     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9288 
9289     // Set rounding mode to round-to-zero.
9290     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9291     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9292 
9293     // Perform addition.
9294     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9295 
9296     // Restore FPSCR value.
9297     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9298   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9299              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
9300              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9301              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9302     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9303                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
9304                       PPC::ANDIo8 : PPC::ANDIo;
9305     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9306                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9307 
9308     MachineRegisterInfo &RegInfo = F->getRegInfo();
9309     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9310                                                   &PPC::GPRCRegClass :
9311                                                   &PPC::G8RCRegClass);
9312 
9313     DebugLoc dl   = MI->getDebugLoc();
9314     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9315       .addReg(MI->getOperand(1).getReg()).addImm(1);
9316     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9317             MI->getOperand(0).getReg())
9318       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9319   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
9320     DebugLoc Dl = MI->getDebugLoc();
9321     MachineRegisterInfo &RegInfo = F->getRegInfo();
9322     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9323     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9324     return BB;
9325   } else {
9326     llvm_unreachable("Unexpected instr type to insert");
9327   }
9328 
9329   MI->eraseFromParent();   // The pseudo instruction is gone now.
9330   return BB;
9331 }
9332 
9333 //===----------------------------------------------------------------------===//
9334 // Target Optimization Hooks
9335 //===----------------------------------------------------------------------===//
9336 
9337 static std::string getRecipOp(const char *Base, EVT VT) {
9338   std::string RecipOp(Base);
9339   if (VT.getScalarType() == MVT::f64)
9340     RecipOp += "d";
9341   else
9342     RecipOp += "f";
9343 
9344   if (VT.isVector())
9345     RecipOp = "vec-" + RecipOp;
9346 
9347   return RecipOp;
9348 }
9349 
9350 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9351                                             DAGCombinerInfo &DCI,
9352                                             unsigned &RefinementSteps,
9353                                             bool &UseOneConstNR) const {
9354   EVT VT = Operand.getValueType();
9355   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9356       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9357       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9358       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9359       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9360       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9361     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9362     std::string RecipOp = getRecipOp("sqrt", VT);
9363     if (!Recips.isEnabled(RecipOp))
9364       return SDValue();
9365 
9366     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9367     UseOneConstNR = true;
9368     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9369   }
9370   return SDValue();
9371 }
9372 
9373 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9374                                             DAGCombinerInfo &DCI,
9375                                             unsigned &RefinementSteps) const {
9376   EVT VT = Operand.getValueType();
9377   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9378       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9379       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9380       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9381       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9382       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9383     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9384     std::string RecipOp = getRecipOp("div", VT);
9385     if (!Recips.isEnabled(RecipOp))
9386       return SDValue();
9387 
9388     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9389     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9390   }
9391   return SDValue();
9392 }
9393 
9394 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9395   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9396   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9397   // enabled for division), this functionality is redundant with the default
9398   // combiner logic (once the division -> reciprocal/multiply transformation
9399   // has taken place). As a result, this matters more for older cores than for
9400   // newer ones.
9401 
9402   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9403   // reciprocal if there are two or more FDIVs (for embedded cores with only
9404   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9405   switch (Subtarget.getDarwinDirective()) {
9406   default:
9407     return 3;
9408   case PPC::DIR_440:
9409   case PPC::DIR_A2:
9410   case PPC::DIR_E500mc:
9411   case PPC::DIR_E5500:
9412     return 2;
9413   }
9414 }
9415 
9416 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9417 // collapsed, and so we need to look through chains of them.
9418 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9419                                      int64_t& Offset, SelectionDAG &DAG) {
9420   if (DAG.isBaseWithConstantOffset(Loc)) {
9421     Base = Loc.getOperand(0);
9422     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9423 
9424     // The base might itself be a base plus an offset, and if so, accumulate
9425     // that as well.
9426     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9427   }
9428 }
9429 
9430 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9431                             unsigned Bytes, int Dist,
9432                             SelectionDAG &DAG) {
9433   if (VT.getSizeInBits() / 8 != Bytes)
9434     return false;
9435 
9436   SDValue BaseLoc = Base->getBasePtr();
9437   if (Loc.getOpcode() == ISD::FrameIndex) {
9438     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9439       return false;
9440     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9441     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9442     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9443     int FS  = MFI->getObjectSize(FI);
9444     int BFS = MFI->getObjectSize(BFI);
9445     if (FS != BFS || FS != (int)Bytes) return false;
9446     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9447   }
9448 
9449   SDValue Base1 = Loc, Base2 = BaseLoc;
9450   int64_t Offset1 = 0, Offset2 = 0;
9451   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9452   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9453   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9454     return true;
9455 
9456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9457   const GlobalValue *GV1 = nullptr;
9458   const GlobalValue *GV2 = nullptr;
9459   Offset1 = 0;
9460   Offset2 = 0;
9461   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9462   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9463   if (isGA1 && isGA2 && GV1 == GV2)
9464     return Offset1 == (Offset2 + Dist*Bytes);
9465   return false;
9466 }
9467 
9468 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9469 // not enforce equality of the chain operands.
9470 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9471                             unsigned Bytes, int Dist,
9472                             SelectionDAG &DAG) {
9473   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9474     EVT VT = LS->getMemoryVT();
9475     SDValue Loc = LS->getBasePtr();
9476     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9477   }
9478 
9479   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9480     EVT VT;
9481     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9482     default: return false;
9483     case Intrinsic::ppc_qpx_qvlfd:
9484     case Intrinsic::ppc_qpx_qvlfda:
9485       VT = MVT::v4f64;
9486       break;
9487     case Intrinsic::ppc_qpx_qvlfs:
9488     case Intrinsic::ppc_qpx_qvlfsa:
9489       VT = MVT::v4f32;
9490       break;
9491     case Intrinsic::ppc_qpx_qvlfcd:
9492     case Intrinsic::ppc_qpx_qvlfcda:
9493       VT = MVT::v2f64;
9494       break;
9495     case Intrinsic::ppc_qpx_qvlfcs:
9496     case Intrinsic::ppc_qpx_qvlfcsa:
9497       VT = MVT::v2f32;
9498       break;
9499     case Intrinsic::ppc_qpx_qvlfiwa:
9500     case Intrinsic::ppc_qpx_qvlfiwz:
9501     case Intrinsic::ppc_altivec_lvx:
9502     case Intrinsic::ppc_altivec_lvxl:
9503     case Intrinsic::ppc_vsx_lxvw4x:
9504       VT = MVT::v4i32;
9505       break;
9506     case Intrinsic::ppc_vsx_lxvd2x:
9507       VT = MVT::v2f64;
9508       break;
9509     case Intrinsic::ppc_altivec_lvebx:
9510       VT = MVT::i8;
9511       break;
9512     case Intrinsic::ppc_altivec_lvehx:
9513       VT = MVT::i16;
9514       break;
9515     case Intrinsic::ppc_altivec_lvewx:
9516       VT = MVT::i32;
9517       break;
9518     }
9519 
9520     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9521   }
9522 
9523   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9524     EVT VT;
9525     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9526     default: return false;
9527     case Intrinsic::ppc_qpx_qvstfd:
9528     case Intrinsic::ppc_qpx_qvstfda:
9529       VT = MVT::v4f64;
9530       break;
9531     case Intrinsic::ppc_qpx_qvstfs:
9532     case Intrinsic::ppc_qpx_qvstfsa:
9533       VT = MVT::v4f32;
9534       break;
9535     case Intrinsic::ppc_qpx_qvstfcd:
9536     case Intrinsic::ppc_qpx_qvstfcda:
9537       VT = MVT::v2f64;
9538       break;
9539     case Intrinsic::ppc_qpx_qvstfcs:
9540     case Intrinsic::ppc_qpx_qvstfcsa:
9541       VT = MVT::v2f32;
9542       break;
9543     case Intrinsic::ppc_qpx_qvstfiw:
9544     case Intrinsic::ppc_qpx_qvstfiwa:
9545     case Intrinsic::ppc_altivec_stvx:
9546     case Intrinsic::ppc_altivec_stvxl:
9547     case Intrinsic::ppc_vsx_stxvw4x:
9548       VT = MVT::v4i32;
9549       break;
9550     case Intrinsic::ppc_vsx_stxvd2x:
9551       VT = MVT::v2f64;
9552       break;
9553     case Intrinsic::ppc_altivec_stvebx:
9554       VT = MVT::i8;
9555       break;
9556     case Intrinsic::ppc_altivec_stvehx:
9557       VT = MVT::i16;
9558       break;
9559     case Intrinsic::ppc_altivec_stvewx:
9560       VT = MVT::i32;
9561       break;
9562     }
9563 
9564     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9565   }
9566 
9567   return false;
9568 }
9569 
9570 // Return true is there is a nearyby consecutive load to the one provided
9571 // (regardless of alignment). We search up and down the chain, looking though
9572 // token factors and other loads (but nothing else). As a result, a true result
9573 // indicates that it is safe to create a new consecutive load adjacent to the
9574 // load provided.
9575 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9576   SDValue Chain = LD->getChain();
9577   EVT VT = LD->getMemoryVT();
9578 
9579   SmallSet<SDNode *, 16> LoadRoots;
9580   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9581   SmallSet<SDNode *, 16> Visited;
9582 
9583   // First, search up the chain, branching to follow all token-factor operands.
9584   // If we find a consecutive load, then we're done, otherwise, record all
9585   // nodes just above the top-level loads and token factors.
9586   while (!Queue.empty()) {
9587     SDNode *ChainNext = Queue.pop_back_val();
9588     if (!Visited.insert(ChainNext).second)
9589       continue;
9590 
9591     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9592       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9593         return true;
9594 
9595       if (!Visited.count(ChainLD->getChain().getNode()))
9596         Queue.push_back(ChainLD->getChain().getNode());
9597     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9598       for (const SDUse &O : ChainNext->ops())
9599         if (!Visited.count(O.getNode()))
9600           Queue.push_back(O.getNode());
9601     } else
9602       LoadRoots.insert(ChainNext);
9603   }
9604 
9605   // Second, search down the chain, starting from the top-level nodes recorded
9606   // in the first phase. These top-level nodes are the nodes just above all
9607   // loads and token factors. Starting with their uses, recursively look though
9608   // all loads (just the chain uses) and token factors to find a consecutive
9609   // load.
9610   Visited.clear();
9611   Queue.clear();
9612 
9613   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9614        IE = LoadRoots.end(); I != IE; ++I) {
9615     Queue.push_back(*I);
9616 
9617     while (!Queue.empty()) {
9618       SDNode *LoadRoot = Queue.pop_back_val();
9619       if (!Visited.insert(LoadRoot).second)
9620         continue;
9621 
9622       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9623         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9624           return true;
9625 
9626       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9627            UE = LoadRoot->use_end(); UI != UE; ++UI)
9628         if (((isa<MemSDNode>(*UI) &&
9629             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9630             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9631           Queue.push_back(*UI);
9632     }
9633   }
9634 
9635   return false;
9636 }
9637 
9638 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9639                                                   DAGCombinerInfo &DCI) const {
9640   SelectionDAG &DAG = DCI.DAG;
9641   SDLoc dl(N);
9642 
9643   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9644   // If we're tracking CR bits, we need to be careful that we don't have:
9645   //   trunc(binary-ops(zext(x), zext(y)))
9646   // or
9647   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9648   // such that we're unnecessarily moving things into GPRs when it would be
9649   // better to keep them in CR bits.
9650 
9651   // Note that trunc here can be an actual i1 trunc, or can be the effective
9652   // truncation that comes from a setcc or select_cc.
9653   if (N->getOpcode() == ISD::TRUNCATE &&
9654       N->getValueType(0) != MVT::i1)
9655     return SDValue();
9656 
9657   if (N->getOperand(0).getValueType() != MVT::i32 &&
9658       N->getOperand(0).getValueType() != MVT::i64)
9659     return SDValue();
9660 
9661   if (N->getOpcode() == ISD::SETCC ||
9662       N->getOpcode() == ISD::SELECT_CC) {
9663     // If we're looking at a comparison, then we need to make sure that the
9664     // high bits (all except for the first) don't matter the result.
9665     ISD::CondCode CC =
9666       cast<CondCodeSDNode>(N->getOperand(
9667         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9668     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9669 
9670     if (ISD::isSignedIntSetCC(CC)) {
9671       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9672           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9673         return SDValue();
9674     } else if (ISD::isUnsignedIntSetCC(CC)) {
9675       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9676                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9677           !DAG.MaskedValueIsZero(N->getOperand(1),
9678                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9679         return SDValue();
9680     } else {
9681       // This is neither a signed nor an unsigned comparison, just make sure
9682       // that the high bits are equal.
9683       APInt Op1Zero, Op1One;
9684       APInt Op2Zero, Op2One;
9685       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9686       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9687 
9688       // We don't really care about what is known about the first bit (if
9689       // anything), so clear it in all masks prior to comparing them.
9690       Op1Zero.clearBit(0); Op1One.clearBit(0);
9691       Op2Zero.clearBit(0); Op2One.clearBit(0);
9692 
9693       if (Op1Zero != Op2Zero || Op1One != Op2One)
9694         return SDValue();
9695     }
9696   }
9697 
9698   // We now know that the higher-order bits are irrelevant, we just need to
9699   // make sure that all of the intermediate operations are bit operations, and
9700   // all inputs are extensions.
9701   if (N->getOperand(0).getOpcode() != ISD::AND &&
9702       N->getOperand(0).getOpcode() != ISD::OR  &&
9703       N->getOperand(0).getOpcode() != ISD::XOR &&
9704       N->getOperand(0).getOpcode() != ISD::SELECT &&
9705       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9706       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9707       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9708       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9709       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9710     return SDValue();
9711 
9712   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9713       N->getOperand(1).getOpcode() != ISD::AND &&
9714       N->getOperand(1).getOpcode() != ISD::OR  &&
9715       N->getOperand(1).getOpcode() != ISD::XOR &&
9716       N->getOperand(1).getOpcode() != ISD::SELECT &&
9717       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9718       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9719       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9720       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9721       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9722     return SDValue();
9723 
9724   SmallVector<SDValue, 4> Inputs;
9725   SmallVector<SDValue, 8> BinOps, PromOps;
9726   SmallPtrSet<SDNode *, 16> Visited;
9727 
9728   for (unsigned i = 0; i < 2; ++i) {
9729     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9730           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9731           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9732           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9733         isa<ConstantSDNode>(N->getOperand(i)))
9734       Inputs.push_back(N->getOperand(i));
9735     else
9736       BinOps.push_back(N->getOperand(i));
9737 
9738     if (N->getOpcode() == ISD::TRUNCATE)
9739       break;
9740   }
9741 
9742   // Visit all inputs, collect all binary operations (and, or, xor and
9743   // select) that are all fed by extensions.
9744   while (!BinOps.empty()) {
9745     SDValue BinOp = BinOps.back();
9746     BinOps.pop_back();
9747 
9748     if (!Visited.insert(BinOp.getNode()).second)
9749       continue;
9750 
9751     PromOps.push_back(BinOp);
9752 
9753     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9754       // The condition of the select is not promoted.
9755       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9756         continue;
9757       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9758         continue;
9759 
9760       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9761             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9762             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9763            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9764           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9765         Inputs.push_back(BinOp.getOperand(i));
9766       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9767                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9768                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9769                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9770                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9771                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9772                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9773                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9774                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9775         BinOps.push_back(BinOp.getOperand(i));
9776       } else {
9777         // We have an input that is not an extension or another binary
9778         // operation; we'll abort this transformation.
9779         return SDValue();
9780       }
9781     }
9782   }
9783 
9784   // Make sure that this is a self-contained cluster of operations (which
9785   // is not quite the same thing as saying that everything has only one
9786   // use).
9787   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9788     if (isa<ConstantSDNode>(Inputs[i]))
9789       continue;
9790 
9791     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9792                               UE = Inputs[i].getNode()->use_end();
9793          UI != UE; ++UI) {
9794       SDNode *User = *UI;
9795       if (User != N && !Visited.count(User))
9796         return SDValue();
9797 
9798       // Make sure that we're not going to promote the non-output-value
9799       // operand(s) or SELECT or SELECT_CC.
9800       // FIXME: Although we could sometimes handle this, and it does occur in
9801       // practice that one of the condition inputs to the select is also one of
9802       // the outputs, we currently can't deal with this.
9803       if (User->getOpcode() == ISD::SELECT) {
9804         if (User->getOperand(0) == Inputs[i])
9805           return SDValue();
9806       } else if (User->getOpcode() == ISD::SELECT_CC) {
9807         if (User->getOperand(0) == Inputs[i] ||
9808             User->getOperand(1) == Inputs[i])
9809           return SDValue();
9810       }
9811     }
9812   }
9813 
9814   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9815     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9816                               UE = PromOps[i].getNode()->use_end();
9817          UI != UE; ++UI) {
9818       SDNode *User = *UI;
9819       if (User != N && !Visited.count(User))
9820         return SDValue();
9821 
9822       // Make sure that we're not going to promote the non-output-value
9823       // operand(s) or SELECT or SELECT_CC.
9824       // FIXME: Although we could sometimes handle this, and it does occur in
9825       // practice that one of the condition inputs to the select is also one of
9826       // the outputs, we currently can't deal with this.
9827       if (User->getOpcode() == ISD::SELECT) {
9828         if (User->getOperand(0) == PromOps[i])
9829           return SDValue();
9830       } else if (User->getOpcode() == ISD::SELECT_CC) {
9831         if (User->getOperand(0) == PromOps[i] ||
9832             User->getOperand(1) == PromOps[i])
9833           return SDValue();
9834       }
9835     }
9836   }
9837 
9838   // Replace all inputs with the extension operand.
9839   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9840     // Constants may have users outside the cluster of to-be-promoted nodes,
9841     // and so we need to replace those as we do the promotions.
9842     if (isa<ConstantSDNode>(Inputs[i]))
9843       continue;
9844     else
9845       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9846   }
9847 
9848   std::list<HandleSDNode> PromOpHandles;
9849   for (auto &PromOp : PromOps)
9850     PromOpHandles.emplace_back(PromOp);
9851 
9852   // Replace all operations (these are all the same, but have a different
9853   // (i1) return type). DAG.getNode will validate that the types of
9854   // a binary operator match, so go through the list in reverse so that
9855   // we've likely promoted both operands first. Any intermediate truncations or
9856   // extensions disappear.
9857   while (!PromOpHandles.empty()) {
9858     SDValue PromOp = PromOpHandles.back().getValue();
9859     PromOpHandles.pop_back();
9860 
9861     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9862         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9863         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9864         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9865       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9866           PromOp.getOperand(0).getValueType() != MVT::i1) {
9867         // The operand is not yet ready (see comment below).
9868         PromOpHandles.emplace_front(PromOp);
9869         continue;
9870       }
9871 
9872       SDValue RepValue = PromOp.getOperand(0);
9873       if (isa<ConstantSDNode>(RepValue))
9874         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9875 
9876       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9877       continue;
9878     }
9879 
9880     unsigned C;
9881     switch (PromOp.getOpcode()) {
9882     default:             C = 0; break;
9883     case ISD::SELECT:    C = 1; break;
9884     case ISD::SELECT_CC: C = 2; break;
9885     }
9886 
9887     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9888          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9889         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9890          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9891       // The to-be-promoted operands of this node have not yet been
9892       // promoted (this should be rare because we're going through the
9893       // list backward, but if one of the operands has several users in
9894       // this cluster of to-be-promoted nodes, it is possible).
9895       PromOpHandles.emplace_front(PromOp);
9896       continue;
9897     }
9898 
9899     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9900                                 PromOp.getNode()->op_end());
9901 
9902     // If there are any constant inputs, make sure they're replaced now.
9903     for (unsigned i = 0; i < 2; ++i)
9904       if (isa<ConstantSDNode>(Ops[C+i]))
9905         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9906 
9907     DAG.ReplaceAllUsesOfValueWith(PromOp,
9908       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9909   }
9910 
9911   // Now we're left with the initial truncation itself.
9912   if (N->getOpcode() == ISD::TRUNCATE)
9913     return N->getOperand(0);
9914 
9915   // Otherwise, this is a comparison. The operands to be compared have just
9916   // changed type (to i1), but everything else is the same.
9917   return SDValue(N, 0);
9918 }
9919 
9920 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9921                                                   DAGCombinerInfo &DCI) const {
9922   SelectionDAG &DAG = DCI.DAG;
9923   SDLoc dl(N);
9924 
9925   // If we're tracking CR bits, we need to be careful that we don't have:
9926   //   zext(binary-ops(trunc(x), trunc(y)))
9927   // or
9928   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9929   // such that we're unnecessarily moving things into CR bits that can more
9930   // efficiently stay in GPRs. Note that if we're not certain that the high
9931   // bits are set as required by the final extension, we still may need to do
9932   // some masking to get the proper behavior.
9933 
9934   // This same functionality is important on PPC64 when dealing with
9935   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9936   // the return values of functions. Because it is so similar, it is handled
9937   // here as well.
9938 
9939   if (N->getValueType(0) != MVT::i32 &&
9940       N->getValueType(0) != MVT::i64)
9941     return SDValue();
9942 
9943   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9944         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9945     return SDValue();
9946 
9947   if (N->getOperand(0).getOpcode() != ISD::AND &&
9948       N->getOperand(0).getOpcode() != ISD::OR  &&
9949       N->getOperand(0).getOpcode() != ISD::XOR &&
9950       N->getOperand(0).getOpcode() != ISD::SELECT &&
9951       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9952     return SDValue();
9953 
9954   SmallVector<SDValue, 4> Inputs;
9955   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9956   SmallPtrSet<SDNode *, 16> Visited;
9957 
9958   // Visit all inputs, collect all binary operations (and, or, xor and
9959   // select) that are all fed by truncations.
9960   while (!BinOps.empty()) {
9961     SDValue BinOp = BinOps.back();
9962     BinOps.pop_back();
9963 
9964     if (!Visited.insert(BinOp.getNode()).second)
9965       continue;
9966 
9967     PromOps.push_back(BinOp);
9968 
9969     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9970       // The condition of the select is not promoted.
9971       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9972         continue;
9973       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9974         continue;
9975 
9976       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9977           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9978         Inputs.push_back(BinOp.getOperand(i));
9979       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9980                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9981                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9982                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9983                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9984         BinOps.push_back(BinOp.getOperand(i));
9985       } else {
9986         // We have an input that is not a truncation or another binary
9987         // operation; we'll abort this transformation.
9988         return SDValue();
9989       }
9990     }
9991   }
9992 
9993   // The operands of a select that must be truncated when the select is
9994   // promoted because the operand is actually part of the to-be-promoted set.
9995   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9996 
9997   // Make sure that this is a self-contained cluster of operations (which
9998   // is not quite the same thing as saying that everything has only one
9999   // use).
10000   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10001     if (isa<ConstantSDNode>(Inputs[i]))
10002       continue;
10003 
10004     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10005                               UE = Inputs[i].getNode()->use_end();
10006          UI != UE; ++UI) {
10007       SDNode *User = *UI;
10008       if (User != N && !Visited.count(User))
10009         return SDValue();
10010 
10011       // If we're going to promote the non-output-value operand(s) or SELECT or
10012       // SELECT_CC, record them for truncation.
10013       if (User->getOpcode() == ISD::SELECT) {
10014         if (User->getOperand(0) == Inputs[i])
10015           SelectTruncOp[0].insert(std::make_pair(User,
10016                                     User->getOperand(0).getValueType()));
10017       } else if (User->getOpcode() == ISD::SELECT_CC) {
10018         if (User->getOperand(0) == Inputs[i])
10019           SelectTruncOp[0].insert(std::make_pair(User,
10020                                     User->getOperand(0).getValueType()));
10021         if (User->getOperand(1) == Inputs[i])
10022           SelectTruncOp[1].insert(std::make_pair(User,
10023                                     User->getOperand(1).getValueType()));
10024       }
10025     }
10026   }
10027 
10028   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10029     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10030                               UE = PromOps[i].getNode()->use_end();
10031          UI != UE; ++UI) {
10032       SDNode *User = *UI;
10033       if (User != N && !Visited.count(User))
10034         return SDValue();
10035 
10036       // If we're going to promote the non-output-value operand(s) or SELECT or
10037       // SELECT_CC, record them for truncation.
10038       if (User->getOpcode() == ISD::SELECT) {
10039         if (User->getOperand(0) == PromOps[i])
10040           SelectTruncOp[0].insert(std::make_pair(User,
10041                                     User->getOperand(0).getValueType()));
10042       } else if (User->getOpcode() == ISD::SELECT_CC) {
10043         if (User->getOperand(0) == PromOps[i])
10044           SelectTruncOp[0].insert(std::make_pair(User,
10045                                     User->getOperand(0).getValueType()));
10046         if (User->getOperand(1) == PromOps[i])
10047           SelectTruncOp[1].insert(std::make_pair(User,
10048                                     User->getOperand(1).getValueType()));
10049       }
10050     }
10051   }
10052 
10053   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10054   bool ReallyNeedsExt = false;
10055   if (N->getOpcode() != ISD::ANY_EXTEND) {
10056     // If all of the inputs are not already sign/zero extended, then
10057     // we'll still need to do that at the end.
10058     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10059       if (isa<ConstantSDNode>(Inputs[i]))
10060         continue;
10061 
10062       unsigned OpBits =
10063         Inputs[i].getOperand(0).getValueSizeInBits();
10064       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10065 
10066       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10067            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10068                                   APInt::getHighBitsSet(OpBits,
10069                                                         OpBits-PromBits))) ||
10070           (N->getOpcode() == ISD::SIGN_EXTEND &&
10071            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10072              (OpBits-(PromBits-1)))) {
10073         ReallyNeedsExt = true;
10074         break;
10075       }
10076     }
10077   }
10078 
10079   // Replace all inputs, either with the truncation operand, or a
10080   // truncation or extension to the final output type.
10081   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10082     // Constant inputs need to be replaced with the to-be-promoted nodes that
10083     // use them because they might have users outside of the cluster of
10084     // promoted nodes.
10085     if (isa<ConstantSDNode>(Inputs[i]))
10086       continue;
10087 
10088     SDValue InSrc = Inputs[i].getOperand(0);
10089     if (Inputs[i].getValueType() == N->getValueType(0))
10090       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10091     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10092       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10093         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10094     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10095       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10096         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10097     else
10098       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10099         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10100   }
10101 
10102   std::list<HandleSDNode> PromOpHandles;
10103   for (auto &PromOp : PromOps)
10104     PromOpHandles.emplace_back(PromOp);
10105 
10106   // Replace all operations (these are all the same, but have a different
10107   // (promoted) return type). DAG.getNode will validate that the types of
10108   // a binary operator match, so go through the list in reverse so that
10109   // we've likely promoted both operands first.
10110   while (!PromOpHandles.empty()) {
10111     SDValue PromOp = PromOpHandles.back().getValue();
10112     PromOpHandles.pop_back();
10113 
10114     unsigned C;
10115     switch (PromOp.getOpcode()) {
10116     default:             C = 0; break;
10117     case ISD::SELECT:    C = 1; break;
10118     case ISD::SELECT_CC: C = 2; break;
10119     }
10120 
10121     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10122          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10123         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10124          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10125       // The to-be-promoted operands of this node have not yet been
10126       // promoted (this should be rare because we're going through the
10127       // list backward, but if one of the operands has several users in
10128       // this cluster of to-be-promoted nodes, it is possible).
10129       PromOpHandles.emplace_front(PromOp);
10130       continue;
10131     }
10132 
10133     // For SELECT and SELECT_CC nodes, we do a similar check for any
10134     // to-be-promoted comparison inputs.
10135     if (PromOp.getOpcode() == ISD::SELECT ||
10136         PromOp.getOpcode() == ISD::SELECT_CC) {
10137       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10138            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10139           (SelectTruncOp[1].count(PromOp.getNode()) &&
10140            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10141         PromOpHandles.emplace_front(PromOp);
10142         continue;
10143       }
10144     }
10145 
10146     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10147                                 PromOp.getNode()->op_end());
10148 
10149     // If this node has constant inputs, then they'll need to be promoted here.
10150     for (unsigned i = 0; i < 2; ++i) {
10151       if (!isa<ConstantSDNode>(Ops[C+i]))
10152         continue;
10153       if (Ops[C+i].getValueType() == N->getValueType(0))
10154         continue;
10155 
10156       if (N->getOpcode() == ISD::SIGN_EXTEND)
10157         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10158       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10159         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10160       else
10161         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10162     }
10163 
10164     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10165     // truncate them again to the original value type.
10166     if (PromOp.getOpcode() == ISD::SELECT ||
10167         PromOp.getOpcode() == ISD::SELECT_CC) {
10168       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10169       if (SI0 != SelectTruncOp[0].end())
10170         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10171       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10172       if (SI1 != SelectTruncOp[1].end())
10173         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10174     }
10175 
10176     DAG.ReplaceAllUsesOfValueWith(PromOp,
10177       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10178   }
10179 
10180   // Now we're left with the initial extension itself.
10181   if (!ReallyNeedsExt)
10182     return N->getOperand(0);
10183 
10184   // To zero extend, just mask off everything except for the first bit (in the
10185   // i1 case).
10186   if (N->getOpcode() == ISD::ZERO_EXTEND)
10187     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10188                        DAG.getConstant(APInt::getLowBitsSet(
10189                                          N->getValueSizeInBits(0), PromBits),
10190                                        dl, N->getValueType(0)));
10191 
10192   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10193          "Invalid extension type");
10194   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10195   SDValue ShiftCst =
10196       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10197   return DAG.getNode(
10198       ISD::SRA, dl, N->getValueType(0),
10199       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10200       ShiftCst);
10201 }
10202 
10203 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10204                                               DAGCombinerInfo &DCI) const {
10205   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10206           N->getOpcode() == ISD::UINT_TO_FP) &&
10207          "Need an int -> FP conversion node here");
10208 
10209   if (!Subtarget.has64BitSupport())
10210     return SDValue();
10211 
10212   SelectionDAG &DAG = DCI.DAG;
10213   SDLoc dl(N);
10214   SDValue Op(N, 0);
10215 
10216   // Don't handle ppc_fp128 here or i1 conversions.
10217   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10218     return SDValue();
10219   if (Op.getOperand(0).getValueType() == MVT::i1)
10220     return SDValue();
10221 
10222   // For i32 intermediate values, unfortunately, the conversion functions
10223   // leave the upper 32 bits of the value are undefined. Within the set of
10224   // scalar instructions, we have no method for zero- or sign-extending the
10225   // value. Thus, we cannot handle i32 intermediate values here.
10226   if (Op.getOperand(0).getValueType() == MVT::i32)
10227     return SDValue();
10228 
10229   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10230          "UINT_TO_FP is supported only with FPCVT");
10231 
10232   // If we have FCFIDS, then use it when converting to single-precision.
10233   // Otherwise, convert to double-precision and then round.
10234   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10235                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10236                                                             : PPCISD::FCFIDS)
10237                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10238                                                             : PPCISD::FCFID);
10239   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10240                   ? MVT::f32
10241                   : MVT::f64;
10242 
10243   // If we're converting from a float, to an int, and back to a float again,
10244   // then we don't need the store/load pair at all.
10245   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10246        Subtarget.hasFPCVT()) ||
10247       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10248     SDValue Src = Op.getOperand(0).getOperand(0);
10249     if (Src.getValueType() == MVT::f32) {
10250       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10251       DCI.AddToWorklist(Src.getNode());
10252     } else if (Src.getValueType() != MVT::f64) {
10253       // Make sure that we don't pick up a ppc_fp128 source value.
10254       return SDValue();
10255     }
10256 
10257     unsigned FCTOp =
10258       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10259                                                         PPCISD::FCTIDUZ;
10260 
10261     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10262     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10263 
10264     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10265       FP = DAG.getNode(ISD::FP_ROUND, dl,
10266                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10267       DCI.AddToWorklist(FP.getNode());
10268     }
10269 
10270     return FP;
10271   }
10272 
10273   return SDValue();
10274 }
10275 
10276 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10277 // builtins) into loads with swaps.
10278 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10279                                               DAGCombinerInfo &DCI) const {
10280   SelectionDAG &DAG = DCI.DAG;
10281   SDLoc dl(N);
10282   SDValue Chain;
10283   SDValue Base;
10284   MachineMemOperand *MMO;
10285 
10286   switch (N->getOpcode()) {
10287   default:
10288     llvm_unreachable("Unexpected opcode for little endian VSX load");
10289   case ISD::LOAD: {
10290     LoadSDNode *LD = cast<LoadSDNode>(N);
10291     Chain = LD->getChain();
10292     Base = LD->getBasePtr();
10293     MMO = LD->getMemOperand();
10294     // If the MMO suggests this isn't a load of a full vector, leave
10295     // things alone.  For a built-in, we have to make the change for
10296     // correctness, so if there is a size problem that will be a bug.
10297     if (MMO->getSize() < 16)
10298       return SDValue();
10299     break;
10300   }
10301   case ISD::INTRINSIC_W_CHAIN: {
10302     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10303     Chain = Intrin->getChain();
10304     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10305     // us what we want. Get operand 2 instead.
10306     Base = Intrin->getOperand(2);
10307     MMO = Intrin->getMemOperand();
10308     break;
10309   }
10310   }
10311 
10312   MVT VecTy = N->getValueType(0).getSimpleVT();
10313   SDValue LoadOps[] = { Chain, Base };
10314   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10315                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10316                                          LoadOps, MVT::v2f64, MMO);
10317 
10318   DCI.AddToWorklist(Load.getNode());
10319   Chain = Load.getValue(1);
10320   SDValue Swap = DAG.getNode(
10321       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10322   DCI.AddToWorklist(Swap.getNode());
10323 
10324   // Add a bitcast if the resulting load type doesn't match v2f64.
10325   if (VecTy != MVT::v2f64) {
10326     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10327     DCI.AddToWorklist(N.getNode());
10328     // Package {bitcast value, swap's chain} to match Load's shape.
10329     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10330                        N, Swap.getValue(1));
10331   }
10332 
10333   return Swap;
10334 }
10335 
10336 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10337 // builtins) into stores with swaps.
10338 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10339                                                DAGCombinerInfo &DCI) const {
10340   SelectionDAG &DAG = DCI.DAG;
10341   SDLoc dl(N);
10342   SDValue Chain;
10343   SDValue Base;
10344   unsigned SrcOpnd;
10345   MachineMemOperand *MMO;
10346 
10347   switch (N->getOpcode()) {
10348   default:
10349     llvm_unreachable("Unexpected opcode for little endian VSX store");
10350   case ISD::STORE: {
10351     StoreSDNode *ST = cast<StoreSDNode>(N);
10352     Chain = ST->getChain();
10353     Base = ST->getBasePtr();
10354     MMO = ST->getMemOperand();
10355     SrcOpnd = 1;
10356     // If the MMO suggests this isn't a store of a full vector, leave
10357     // things alone.  For a built-in, we have to make the change for
10358     // correctness, so if there is a size problem that will be a bug.
10359     if (MMO->getSize() < 16)
10360       return SDValue();
10361     break;
10362   }
10363   case ISD::INTRINSIC_VOID: {
10364     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10365     Chain = Intrin->getChain();
10366     // Intrin->getBasePtr() oddly does not get what we want.
10367     Base = Intrin->getOperand(3);
10368     MMO = Intrin->getMemOperand();
10369     SrcOpnd = 2;
10370     break;
10371   }
10372   }
10373 
10374   SDValue Src = N->getOperand(SrcOpnd);
10375   MVT VecTy = Src.getValueType().getSimpleVT();
10376 
10377   // All stores are done as v2f64 and possible bit cast.
10378   if (VecTy != MVT::v2f64) {
10379     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10380     DCI.AddToWorklist(Src.getNode());
10381   }
10382 
10383   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10384                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10385   DCI.AddToWorklist(Swap.getNode());
10386   Chain = Swap.getValue(1);
10387   SDValue StoreOps[] = { Chain, Swap, Base };
10388   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10389                                           DAG.getVTList(MVT::Other),
10390                                           StoreOps, VecTy, MMO);
10391   DCI.AddToWorklist(Store.getNode());
10392   return Store;
10393 }
10394 
10395 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10396                                              DAGCombinerInfo &DCI) const {
10397   SelectionDAG &DAG = DCI.DAG;
10398   SDLoc dl(N);
10399   switch (N->getOpcode()) {
10400   default: break;
10401   case PPCISD::SHL:
10402     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10403         return N->getOperand(0);
10404     break;
10405   case PPCISD::SRL:
10406     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10407         return N->getOperand(0);
10408     break;
10409   case PPCISD::SRA:
10410     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10411       if (C->isNullValue() ||   //  0 >>s V -> 0.
10412           C->isAllOnesValue())    // -1 >>s V -> -1.
10413         return N->getOperand(0);
10414     }
10415     break;
10416   case ISD::SIGN_EXTEND:
10417   case ISD::ZERO_EXTEND:
10418   case ISD::ANY_EXTEND:
10419     return DAGCombineExtBoolTrunc(N, DCI);
10420   case ISD::TRUNCATE:
10421   case ISD::SETCC:
10422   case ISD::SELECT_CC:
10423     return DAGCombineTruncBoolExt(N, DCI);
10424   case ISD::SINT_TO_FP:
10425   case ISD::UINT_TO_FP:
10426     return combineFPToIntToFP(N, DCI);
10427   case ISD::STORE: {
10428     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10429     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10430         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10431         N->getOperand(1).getValueType() == MVT::i32 &&
10432         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10433       SDValue Val = N->getOperand(1).getOperand(0);
10434       if (Val.getValueType() == MVT::f32) {
10435         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10436         DCI.AddToWorklist(Val.getNode());
10437       }
10438       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10439       DCI.AddToWorklist(Val.getNode());
10440 
10441       SDValue Ops[] = {
10442         N->getOperand(0), Val, N->getOperand(2),
10443         DAG.getValueType(N->getOperand(1).getValueType())
10444       };
10445 
10446       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10447               DAG.getVTList(MVT::Other), Ops,
10448               cast<StoreSDNode>(N)->getMemoryVT(),
10449               cast<StoreSDNode>(N)->getMemOperand());
10450       DCI.AddToWorklist(Val.getNode());
10451       return Val;
10452     }
10453 
10454     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10455     if (cast<StoreSDNode>(N)->isUnindexed() &&
10456         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10457         N->getOperand(1).getNode()->hasOneUse() &&
10458         (N->getOperand(1).getValueType() == MVT::i32 ||
10459          N->getOperand(1).getValueType() == MVT::i16 ||
10460          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10461           N->getOperand(1).getValueType() == MVT::i64))) {
10462       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10463       // Do an any-extend to 32-bits if this is a half-word input.
10464       if (BSwapOp.getValueType() == MVT::i16)
10465         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10466 
10467       SDValue Ops[] = {
10468         N->getOperand(0), BSwapOp, N->getOperand(2),
10469         DAG.getValueType(N->getOperand(1).getValueType())
10470       };
10471       return
10472         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10473                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10474                                 cast<StoreSDNode>(N)->getMemOperand());
10475     }
10476 
10477     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10478     EVT VT = N->getOperand(1).getValueType();
10479     if (VT.isSimple()) {
10480       MVT StoreVT = VT.getSimpleVT();
10481       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10482           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10483            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10484         return expandVSXStoreForLE(N, DCI);
10485     }
10486     break;
10487   }
10488   case ISD::LOAD: {
10489     LoadSDNode *LD = cast<LoadSDNode>(N);
10490     EVT VT = LD->getValueType(0);
10491 
10492     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10493     if (VT.isSimple()) {
10494       MVT LoadVT = VT.getSimpleVT();
10495       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10496           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10497            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10498         return expandVSXLoadForLE(N, DCI);
10499     }
10500 
10501     // We sometimes end up with a 64-bit integer load, from which we extract
10502     // two single-precision floating-point numbers. This happens with
10503     // std::complex<float>, and other similar structures, because of the way we
10504     // canonicalize structure copies. However, if we lack direct moves,
10505     // then the final bitcasts from the extracted integer values to the
10506     // floating-point numbers turn into store/load pairs. Even with direct moves,
10507     // just loading the two floating-point numbers is likely better.
10508     auto ReplaceTwoFloatLoad = [&]() {
10509       if (VT != MVT::i64)
10510         return false;
10511 
10512       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10513           LD->isVolatile())
10514         return false;
10515 
10516       //  We're looking for a sequence like this:
10517       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10518       //      t16: i64 = srl t13, Constant:i32<32>
10519       //    t17: i32 = truncate t16
10520       //  t18: f32 = bitcast t17
10521       //    t19: i32 = truncate t13
10522       //  t20: f32 = bitcast t19
10523 
10524       if (!LD->hasNUsesOfValue(2, 0))
10525         return false;
10526 
10527       auto UI = LD->use_begin();
10528       while (UI.getUse().getResNo() != 0) ++UI;
10529       SDNode *Trunc = *UI++;
10530       while (UI.getUse().getResNo() != 0) ++UI;
10531       SDNode *RightShift = *UI;
10532       if (Trunc->getOpcode() != ISD::TRUNCATE)
10533         std::swap(Trunc, RightShift);
10534 
10535       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10536           Trunc->getValueType(0) != MVT::i32 ||
10537           !Trunc->hasOneUse())
10538         return false;
10539       if (RightShift->getOpcode() != ISD::SRL ||
10540           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10541           RightShift->getConstantOperandVal(1) != 32 ||
10542           !RightShift->hasOneUse())
10543         return false;
10544 
10545       SDNode *Trunc2 = *RightShift->use_begin();
10546       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10547           Trunc2->getValueType(0) != MVT::i32 ||
10548           !Trunc2->hasOneUse())
10549         return false;
10550 
10551       SDNode *Bitcast = *Trunc->use_begin();
10552       SDNode *Bitcast2 = *Trunc2->use_begin();
10553 
10554       if (Bitcast->getOpcode() != ISD::BITCAST ||
10555           Bitcast->getValueType(0) != MVT::f32)
10556         return false;
10557       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10558           Bitcast2->getValueType(0) != MVT::f32)
10559         return false;
10560 
10561       if (Subtarget.isLittleEndian())
10562         std::swap(Bitcast, Bitcast2);
10563 
10564       // Bitcast has the second float (in memory-layout order) and Bitcast2
10565       // has the first one.
10566 
10567       SDValue BasePtr = LD->getBasePtr();
10568       if (LD->isIndexed()) {
10569         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10570                "Non-pre-inc AM on PPC?");
10571         BasePtr =
10572           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10573                       LD->getOffset());
10574       }
10575 
10576       SDValue FloatLoad =
10577         DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10578                     LD->getPointerInfo(), false, LD->isNonTemporal(),
10579                     LD->isInvariant(), LD->getAlignment(), LD->getAAInfo());
10580       SDValue AddPtr =
10581         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10582                     BasePtr, DAG.getIntPtrConstant(4, dl));
10583       SDValue FloatLoad2 =
10584         DAG.getLoad(MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10585                     LD->getPointerInfo().getWithOffset(4), false,
10586                     LD->isNonTemporal(), LD->isInvariant(),
10587                     MinAlign(LD->getAlignment(), 4), LD->getAAInfo());
10588 
10589       if (LD->isIndexed()) {
10590         // Note that DAGCombine should re-form any pre-increment load(s) from
10591         // what is produced here if that makes sense.
10592         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10593       }
10594 
10595       DCI.CombineTo(Bitcast2, FloatLoad);
10596       DCI.CombineTo(Bitcast, FloatLoad2);
10597 
10598       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10599                                     SDValue(FloatLoad2.getNode(), 1));
10600       return true;
10601     };
10602 
10603     if (ReplaceTwoFloatLoad())
10604       return SDValue(N, 0);
10605 
10606     EVT MemVT = LD->getMemoryVT();
10607     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10608     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10609     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10610     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10611     if (LD->isUnindexed() && VT.isVector() &&
10612         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10613           // P8 and later hardware should just use LOAD.
10614           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10615                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10616          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10617           LD->getAlignment() >= ScalarABIAlignment)) &&
10618         LD->getAlignment() < ABIAlignment) {
10619       // This is a type-legal unaligned Altivec or QPX load.
10620       SDValue Chain = LD->getChain();
10621       SDValue Ptr = LD->getBasePtr();
10622       bool isLittleEndian = Subtarget.isLittleEndian();
10623 
10624       // This implements the loading of unaligned vectors as described in
10625       // the venerable Apple Velocity Engine overview. Specifically:
10626       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10627       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10628       //
10629       // The general idea is to expand a sequence of one or more unaligned
10630       // loads into an alignment-based permutation-control instruction (lvsl
10631       // or lvsr), a series of regular vector loads (which always truncate
10632       // their input address to an aligned address), and a series of
10633       // permutations.  The results of these permutations are the requested
10634       // loaded values.  The trick is that the last "extra" load is not taken
10635       // from the address you might suspect (sizeof(vector) bytes after the
10636       // last requested load), but rather sizeof(vector) - 1 bytes after the
10637       // last requested vector. The point of this is to avoid a page fault if
10638       // the base address happened to be aligned. This works because if the
10639       // base address is aligned, then adding less than a full vector length
10640       // will cause the last vector in the sequence to be (re)loaded.
10641       // Otherwise, the next vector will be fetched as you might suspect was
10642       // necessary.
10643 
10644       // We might be able to reuse the permutation generation from
10645       // a different base address offset from this one by an aligned amount.
10646       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10647       // optimization later.
10648       Intrinsic::ID Intr, IntrLD, IntrPerm;
10649       MVT PermCntlTy, PermTy, LDTy;
10650       if (Subtarget.hasAltivec()) {
10651         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10652                                  Intrinsic::ppc_altivec_lvsl;
10653         IntrLD = Intrinsic::ppc_altivec_lvx;
10654         IntrPerm = Intrinsic::ppc_altivec_vperm;
10655         PermCntlTy = MVT::v16i8;
10656         PermTy = MVT::v4i32;
10657         LDTy = MVT::v4i32;
10658       } else {
10659         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10660                                        Intrinsic::ppc_qpx_qvlpcls;
10661         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10662                                        Intrinsic::ppc_qpx_qvlfs;
10663         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10664         PermCntlTy = MVT::v4f64;
10665         PermTy = MVT::v4f64;
10666         LDTy = MemVT.getSimpleVT();
10667       }
10668 
10669       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10670 
10671       // Create the new MMO for the new base load. It is like the original MMO,
10672       // but represents an area in memory almost twice the vector size centered
10673       // on the original address. If the address is unaligned, we might start
10674       // reading up to (sizeof(vector)-1) bytes below the address of the
10675       // original unaligned load.
10676       MachineFunction &MF = DAG.getMachineFunction();
10677       MachineMemOperand *BaseMMO =
10678         MF.getMachineMemOperand(LD->getMemOperand(),
10679                                 -(long)MemVT.getStoreSize()+1,
10680                                 2*MemVT.getStoreSize()-1);
10681 
10682       // Create the new base load.
10683       SDValue LDXIntID =
10684           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10685       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10686       SDValue BaseLoad =
10687         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10688                                 DAG.getVTList(PermTy, MVT::Other),
10689                                 BaseLoadOps, LDTy, BaseMMO);
10690 
10691       // Note that the value of IncOffset (which is provided to the next
10692       // load's pointer info offset value, and thus used to calculate the
10693       // alignment), and the value of IncValue (which is actually used to
10694       // increment the pointer value) are different! This is because we
10695       // require the next load to appear to be aligned, even though it
10696       // is actually offset from the base pointer by a lesser amount.
10697       int IncOffset = VT.getSizeInBits() / 8;
10698       int IncValue = IncOffset;
10699 
10700       // Walk (both up and down) the chain looking for another load at the real
10701       // (aligned) offset (the alignment of the other load does not matter in
10702       // this case). If found, then do not use the offset reduction trick, as
10703       // that will prevent the loads from being later combined (as they would
10704       // otherwise be duplicates).
10705       if (!findConsecutiveLoad(LD, DAG))
10706         --IncValue;
10707 
10708       SDValue Increment =
10709           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10710       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10711 
10712       MachineMemOperand *ExtraMMO =
10713         MF.getMachineMemOperand(LD->getMemOperand(),
10714                                 1, 2*MemVT.getStoreSize()-1);
10715       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10716       SDValue ExtraLoad =
10717         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10718                                 DAG.getVTList(PermTy, MVT::Other),
10719                                 ExtraLoadOps, LDTy, ExtraMMO);
10720 
10721       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10722         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10723 
10724       // Because vperm has a big-endian bias, we must reverse the order
10725       // of the input vectors and complement the permute control vector
10726       // when generating little endian code.  We have already handled the
10727       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10728       // and ExtraLoad here.
10729       SDValue Perm;
10730       if (isLittleEndian)
10731         Perm = BuildIntrinsicOp(IntrPerm,
10732                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10733       else
10734         Perm = BuildIntrinsicOp(IntrPerm,
10735                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10736 
10737       if (VT != PermTy)
10738         Perm = Subtarget.hasAltivec() ?
10739                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10740                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10741                                DAG.getTargetConstant(1, dl, MVT::i64));
10742                                // second argument is 1 because this rounding
10743                                // is always exact.
10744 
10745       // The output of the permutation is our loaded result, the TokenFactor is
10746       // our new chain.
10747       DCI.CombineTo(N, Perm, TF);
10748       return SDValue(N, 0);
10749     }
10750     }
10751     break;
10752     case ISD::INTRINSIC_WO_CHAIN: {
10753       bool isLittleEndian = Subtarget.isLittleEndian();
10754       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10755       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10756                                            : Intrinsic::ppc_altivec_lvsl);
10757       if ((IID == Intr ||
10758            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10759            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10760         N->getOperand(1)->getOpcode() == ISD::ADD) {
10761         SDValue Add = N->getOperand(1);
10762 
10763         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10764                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10765 
10766         if (DAG.MaskedValueIsZero(
10767                 Add->getOperand(1),
10768                 APInt::getAllOnesValue(Bits /* alignment */)
10769                     .zext(
10770                         Add.getValueType().getScalarType().getSizeInBits()))) {
10771           SDNode *BasePtr = Add->getOperand(0).getNode();
10772           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10773                                     UE = BasePtr->use_end();
10774                UI != UE; ++UI) {
10775             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10776                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10777               // We've found another LVSL/LVSR, and this address is an aligned
10778               // multiple of that one. The results will be the same, so use the
10779               // one we've just found instead.
10780 
10781               return SDValue(*UI, 0);
10782             }
10783           }
10784         }
10785 
10786         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10787           SDNode *BasePtr = Add->getOperand(0).getNode();
10788           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10789                UE = BasePtr->use_end(); UI != UE; ++UI) {
10790             if (UI->getOpcode() == ISD::ADD &&
10791                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10792                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10793                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10794                 (1ULL << Bits) == 0) {
10795               SDNode *OtherAdd = *UI;
10796               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10797                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10798                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10799                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10800                   return SDValue(*VI, 0);
10801                 }
10802               }
10803             }
10804           }
10805         }
10806       }
10807     }
10808 
10809     break;
10810   case ISD::INTRINSIC_W_CHAIN: {
10811     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10812     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10813       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10814       default:
10815         break;
10816       case Intrinsic::ppc_vsx_lxvw4x:
10817       case Intrinsic::ppc_vsx_lxvd2x:
10818         return expandVSXLoadForLE(N, DCI);
10819       }
10820     }
10821     break;
10822   }
10823   case ISD::INTRINSIC_VOID: {
10824     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10825     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10826       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10827       default:
10828         break;
10829       case Intrinsic::ppc_vsx_stxvw4x:
10830       case Intrinsic::ppc_vsx_stxvd2x:
10831         return expandVSXStoreForLE(N, DCI);
10832       }
10833     }
10834     break;
10835   }
10836   case ISD::BSWAP:
10837     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10838     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10839         N->getOperand(0).hasOneUse() &&
10840         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10841          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10842           N->getValueType(0) == MVT::i64))) {
10843       SDValue Load = N->getOperand(0);
10844       LoadSDNode *LD = cast<LoadSDNode>(Load);
10845       // Create the byte-swapping load.
10846       SDValue Ops[] = {
10847         LD->getChain(),    // Chain
10848         LD->getBasePtr(),  // Ptr
10849         DAG.getValueType(N->getValueType(0)) // VT
10850       };
10851       SDValue BSLoad =
10852         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10853                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10854                                               MVT::i64 : MVT::i32, MVT::Other),
10855                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10856 
10857       // If this is an i16 load, insert the truncate.
10858       SDValue ResVal = BSLoad;
10859       if (N->getValueType(0) == MVT::i16)
10860         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10861 
10862       // First, combine the bswap away.  This makes the value produced by the
10863       // load dead.
10864       DCI.CombineTo(N, ResVal);
10865 
10866       // Next, combine the load away, we give it a bogus result value but a real
10867       // chain result.  The result value is dead because the bswap is dead.
10868       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10869 
10870       // Return N so it doesn't get rechecked!
10871       return SDValue(N, 0);
10872     }
10873 
10874     break;
10875   case PPCISD::VCMP: {
10876     // If a VCMPo node already exists with exactly the same operands as this
10877     // node, use its result instead of this node (VCMPo computes both a CR6 and
10878     // a normal output).
10879     //
10880     if (!N->getOperand(0).hasOneUse() &&
10881         !N->getOperand(1).hasOneUse() &&
10882         !N->getOperand(2).hasOneUse()) {
10883 
10884       // Scan all of the users of the LHS, looking for VCMPo's that match.
10885       SDNode *VCMPoNode = nullptr;
10886 
10887       SDNode *LHSN = N->getOperand(0).getNode();
10888       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10889            UI != E; ++UI)
10890         if (UI->getOpcode() == PPCISD::VCMPo &&
10891             UI->getOperand(1) == N->getOperand(1) &&
10892             UI->getOperand(2) == N->getOperand(2) &&
10893             UI->getOperand(0) == N->getOperand(0)) {
10894           VCMPoNode = *UI;
10895           break;
10896         }
10897 
10898       // If there is no VCMPo node, or if the flag value has a single use, don't
10899       // transform this.
10900       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10901         break;
10902 
10903       // Look at the (necessarily single) use of the flag value.  If it has a
10904       // chain, this transformation is more complex.  Note that multiple things
10905       // could use the value result, which we should ignore.
10906       SDNode *FlagUser = nullptr;
10907       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10908            FlagUser == nullptr; ++UI) {
10909         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10910         SDNode *User = *UI;
10911         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10912           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10913             FlagUser = User;
10914             break;
10915           }
10916         }
10917       }
10918 
10919       // If the user is a MFOCRF instruction, we know this is safe.
10920       // Otherwise we give up for right now.
10921       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10922         return SDValue(VCMPoNode, 0);
10923     }
10924     break;
10925   }
10926   case ISD::BRCOND: {
10927     SDValue Cond = N->getOperand(1);
10928     SDValue Target = N->getOperand(2);
10929 
10930     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10931         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10932           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10933 
10934       // We now need to make the intrinsic dead (it cannot be instruction
10935       // selected).
10936       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10937       assert(Cond.getNode()->hasOneUse() &&
10938              "Counter decrement has more than one use");
10939 
10940       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10941                          N->getOperand(0), Target);
10942     }
10943   }
10944   break;
10945   case ISD::BR_CC: {
10946     // If this is a branch on an altivec predicate comparison, lower this so
10947     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10948     // lowering is done pre-legalize, because the legalizer lowers the predicate
10949     // compare down to code that is difficult to reassemble.
10950     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10951     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10952 
10953     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10954     // value. If so, pass-through the AND to get to the intrinsic.
10955     if (LHS.getOpcode() == ISD::AND &&
10956         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10957         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10958           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10959         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10960         !isNullConstant(LHS.getOperand(1)))
10961       LHS = LHS.getOperand(0);
10962 
10963     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10964         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10965           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10966         isa<ConstantSDNode>(RHS)) {
10967       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10968              "Counter decrement comparison is not EQ or NE");
10969 
10970       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10971       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10972                     (CC == ISD::SETNE && !Val);
10973 
10974       // We now need to make the intrinsic dead (it cannot be instruction
10975       // selected).
10976       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10977       assert(LHS.getNode()->hasOneUse() &&
10978              "Counter decrement has more than one use");
10979 
10980       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10981                          N->getOperand(0), N->getOperand(4));
10982     }
10983 
10984     int CompareOpc;
10985     bool isDot;
10986 
10987     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10988         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10989         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10990       assert(isDot && "Can't compare against a vector result!");
10991 
10992       // If this is a comparison against something other than 0/1, then we know
10993       // that the condition is never/always true.
10994       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10995       if (Val != 0 && Val != 1) {
10996         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10997           return N->getOperand(0);
10998         // Always !=, turn it into an unconditional branch.
10999         return DAG.getNode(ISD::BR, dl, MVT::Other,
11000                            N->getOperand(0), N->getOperand(4));
11001       }
11002 
11003       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11004 
11005       // Create the PPCISD altivec 'dot' comparison node.
11006       SDValue Ops[] = {
11007         LHS.getOperand(2),  // LHS of compare
11008         LHS.getOperand(3),  // RHS of compare
11009         DAG.getConstant(CompareOpc, dl, MVT::i32)
11010       };
11011       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11012       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11013 
11014       // Unpack the result based on how the target uses it.
11015       PPC::Predicate CompOpc;
11016       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11017       default:  // Can't happen, don't crash on invalid number though.
11018       case 0:   // Branch on the value of the EQ bit of CR6.
11019         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11020         break;
11021       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11022         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11023         break;
11024       case 2:   // Branch on the value of the LT bit of CR6.
11025         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11026         break;
11027       case 3:   // Branch on the inverted value of the LT bit of CR6.
11028         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11029         break;
11030       }
11031 
11032       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11033                          DAG.getConstant(CompOpc, dl, MVT::i32),
11034                          DAG.getRegister(PPC::CR6, MVT::i32),
11035                          N->getOperand(4), CompNode.getValue(1));
11036     }
11037     break;
11038   }
11039   }
11040 
11041   return SDValue();
11042 }
11043 
11044 SDValue
11045 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11046                                   SelectionDAG &DAG,
11047                                   std::vector<SDNode *> *Created) const {
11048   // fold (sdiv X, pow2)
11049   EVT VT = N->getValueType(0);
11050   if (VT == MVT::i64 && !Subtarget.isPPC64())
11051     return SDValue();
11052   if ((VT != MVT::i32 && VT != MVT::i64) ||
11053       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11054     return SDValue();
11055 
11056   SDLoc DL(N);
11057   SDValue N0 = N->getOperand(0);
11058 
11059   bool IsNegPow2 = (-Divisor).isPowerOf2();
11060   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11061   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11062 
11063   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11064   if (Created)
11065     Created->push_back(Op.getNode());
11066 
11067   if (IsNegPow2) {
11068     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11069     if (Created)
11070       Created->push_back(Op.getNode());
11071   }
11072 
11073   return Op;
11074 }
11075 
11076 //===----------------------------------------------------------------------===//
11077 // Inline Assembly Support
11078 //===----------------------------------------------------------------------===//
11079 
11080 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11081                                                       APInt &KnownZero,
11082                                                       APInt &KnownOne,
11083                                                       const SelectionDAG &DAG,
11084                                                       unsigned Depth) const {
11085   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11086   switch (Op.getOpcode()) {
11087   default: break;
11088   case PPCISD::LBRX: {
11089     // lhbrx is known to have the top bits cleared out.
11090     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11091       KnownZero = 0xFFFF0000;
11092     break;
11093   }
11094   case ISD::INTRINSIC_WO_CHAIN: {
11095     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11096     default: break;
11097     case Intrinsic::ppc_altivec_vcmpbfp_p:
11098     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11099     case Intrinsic::ppc_altivec_vcmpequb_p:
11100     case Intrinsic::ppc_altivec_vcmpequh_p:
11101     case Intrinsic::ppc_altivec_vcmpequw_p:
11102     case Intrinsic::ppc_altivec_vcmpequd_p:
11103     case Intrinsic::ppc_altivec_vcmpgefp_p:
11104     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11105     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11106     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11107     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11108     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11109     case Intrinsic::ppc_altivec_vcmpgtub_p:
11110     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11111     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11112     case Intrinsic::ppc_altivec_vcmpgtud_p:
11113       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11114       break;
11115     }
11116   }
11117   }
11118 }
11119 
11120 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11121   switch (Subtarget.getDarwinDirective()) {
11122   default: break;
11123   case PPC::DIR_970:
11124   case PPC::DIR_PWR4:
11125   case PPC::DIR_PWR5:
11126   case PPC::DIR_PWR5X:
11127   case PPC::DIR_PWR6:
11128   case PPC::DIR_PWR6X:
11129   case PPC::DIR_PWR7:
11130   case PPC::DIR_PWR8:
11131   case PPC::DIR_PWR9: {
11132     if (!ML)
11133       break;
11134 
11135     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11136 
11137     // For small loops (between 5 and 8 instructions), align to a 32-byte
11138     // boundary so that the entire loop fits in one instruction-cache line.
11139     uint64_t LoopSize = 0;
11140     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11141       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11142         LoopSize += TII->GetInstSizeInBytes(J);
11143         if (LoopSize > 32)
11144           break;
11145       }
11146 
11147     if (LoopSize > 16 && LoopSize <= 32)
11148       return 5;
11149 
11150     break;
11151   }
11152   }
11153 
11154   return TargetLowering::getPrefLoopAlignment(ML);
11155 }
11156 
11157 /// getConstraintType - Given a constraint, return the type of
11158 /// constraint it is for this target.
11159 PPCTargetLowering::ConstraintType
11160 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11161   if (Constraint.size() == 1) {
11162     switch (Constraint[0]) {
11163     default: break;
11164     case 'b':
11165     case 'r':
11166     case 'f':
11167     case 'd':
11168     case 'v':
11169     case 'y':
11170       return C_RegisterClass;
11171     case 'Z':
11172       // FIXME: While Z does indicate a memory constraint, it specifically
11173       // indicates an r+r address (used in conjunction with the 'y' modifier
11174       // in the replacement string). Currently, we're forcing the base
11175       // register to be r0 in the asm printer (which is interpreted as zero)
11176       // and forming the complete address in the second register. This is
11177       // suboptimal.
11178       return C_Memory;
11179     }
11180   } else if (Constraint == "wc") { // individual CR bits.
11181     return C_RegisterClass;
11182   } else if (Constraint == "wa" || Constraint == "wd" ||
11183              Constraint == "wf" || Constraint == "ws") {
11184     return C_RegisterClass; // VSX registers.
11185   }
11186   return TargetLowering::getConstraintType(Constraint);
11187 }
11188 
11189 /// Examine constraint type and operand type and determine a weight value.
11190 /// This object must already have been set up with the operand type
11191 /// and the current alternative constraint selected.
11192 TargetLowering::ConstraintWeight
11193 PPCTargetLowering::getSingleConstraintMatchWeight(
11194     AsmOperandInfo &info, const char *constraint) const {
11195   ConstraintWeight weight = CW_Invalid;
11196   Value *CallOperandVal = info.CallOperandVal;
11197     // If we don't have a value, we can't do a match,
11198     // but allow it at the lowest weight.
11199   if (!CallOperandVal)
11200     return CW_Default;
11201   Type *type = CallOperandVal->getType();
11202 
11203   // Look at the constraint type.
11204   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11205     return CW_Register; // an individual CR bit.
11206   else if ((StringRef(constraint) == "wa" ||
11207             StringRef(constraint) == "wd" ||
11208             StringRef(constraint) == "wf") &&
11209            type->isVectorTy())
11210     return CW_Register;
11211   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11212     return CW_Register;
11213 
11214   switch (*constraint) {
11215   default:
11216     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11217     break;
11218   case 'b':
11219     if (type->isIntegerTy())
11220       weight = CW_Register;
11221     break;
11222   case 'f':
11223     if (type->isFloatTy())
11224       weight = CW_Register;
11225     break;
11226   case 'd':
11227     if (type->isDoubleTy())
11228       weight = CW_Register;
11229     break;
11230   case 'v':
11231     if (type->isVectorTy())
11232       weight = CW_Register;
11233     break;
11234   case 'y':
11235     weight = CW_Register;
11236     break;
11237   case 'Z':
11238     weight = CW_Memory;
11239     break;
11240   }
11241   return weight;
11242 }
11243 
11244 std::pair<unsigned, const TargetRegisterClass *>
11245 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11246                                                 StringRef Constraint,
11247                                                 MVT VT) const {
11248   if (Constraint.size() == 1) {
11249     // GCC RS6000 Constraint Letters
11250     switch (Constraint[0]) {
11251     case 'b':   // R1-R31
11252       if (VT == MVT::i64 && Subtarget.isPPC64())
11253         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11254       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11255     case 'r':   // R0-R31
11256       if (VT == MVT::i64 && Subtarget.isPPC64())
11257         return std::make_pair(0U, &PPC::G8RCRegClass);
11258       return std::make_pair(0U, &PPC::GPRCRegClass);
11259     // 'd' and 'f' constraints are both defined to be "the floating point
11260     // registers", where one is for 32-bit and the other for 64-bit. We don't
11261     // really care overly much here so just give them all the same reg classes.
11262     case 'd':
11263     case 'f':
11264       if (VT == MVT::f32 || VT == MVT::i32)
11265         return std::make_pair(0U, &PPC::F4RCRegClass);
11266       if (VT == MVT::f64 || VT == MVT::i64)
11267         return std::make_pair(0U, &PPC::F8RCRegClass);
11268       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11269         return std::make_pair(0U, &PPC::QFRCRegClass);
11270       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11271         return std::make_pair(0U, &PPC::QSRCRegClass);
11272       break;
11273     case 'v':
11274       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11275         return std::make_pair(0U, &PPC::QFRCRegClass);
11276       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11277         return std::make_pair(0U, &PPC::QSRCRegClass);
11278       if (Subtarget.hasAltivec())
11279         return std::make_pair(0U, &PPC::VRRCRegClass);
11280     case 'y':   // crrc
11281       return std::make_pair(0U, &PPC::CRRCRegClass);
11282     }
11283   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11284     // An individual CR bit.
11285     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11286   } else if ((Constraint == "wa" || Constraint == "wd" ||
11287              Constraint == "wf") && Subtarget.hasVSX()) {
11288     return std::make_pair(0U, &PPC::VSRCRegClass);
11289   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11290     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11291       return std::make_pair(0U, &PPC::VSSRCRegClass);
11292     else
11293       return std::make_pair(0U, &PPC::VSFRCRegClass);
11294   }
11295 
11296   std::pair<unsigned, const TargetRegisterClass *> R =
11297       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11298 
11299   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11300   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11301   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11302   // register.
11303   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11304   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11305   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11306       PPC::GPRCRegClass.contains(R.first))
11307     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11308                             PPC::sub_32, &PPC::G8RCRegClass),
11309                           &PPC::G8RCRegClass);
11310 
11311   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11312   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11313     R.first = PPC::CR0;
11314     R.second = &PPC::CRRCRegClass;
11315   }
11316 
11317   return R;
11318 }
11319 
11320 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11321 /// vector.  If it is invalid, don't add anything to Ops.
11322 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11323                                                      std::string &Constraint,
11324                                                      std::vector<SDValue>&Ops,
11325                                                      SelectionDAG &DAG) const {
11326   SDValue Result;
11327 
11328   // Only support length 1 constraints.
11329   if (Constraint.length() > 1) return;
11330 
11331   char Letter = Constraint[0];
11332   switch (Letter) {
11333   default: break;
11334   case 'I':
11335   case 'J':
11336   case 'K':
11337   case 'L':
11338   case 'M':
11339   case 'N':
11340   case 'O':
11341   case 'P': {
11342     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11343     if (!CST) return; // Must be an immediate to match.
11344     SDLoc dl(Op);
11345     int64_t Value = CST->getSExtValue();
11346     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11347                          // numbers are printed as such.
11348     switch (Letter) {
11349     default: llvm_unreachable("Unknown constraint letter!");
11350     case 'I':  // "I" is a signed 16-bit constant.
11351       if (isInt<16>(Value))
11352         Result = DAG.getTargetConstant(Value, dl, TCVT);
11353       break;
11354     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11355       if (isShiftedUInt<16, 16>(Value))
11356         Result = DAG.getTargetConstant(Value, dl, TCVT);
11357       break;
11358     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11359       if (isShiftedInt<16, 16>(Value))
11360         Result = DAG.getTargetConstant(Value, dl, TCVT);
11361       break;
11362     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11363       if (isUInt<16>(Value))
11364         Result = DAG.getTargetConstant(Value, dl, TCVT);
11365       break;
11366     case 'M':  // "M" is a constant that is greater than 31.
11367       if (Value > 31)
11368         Result = DAG.getTargetConstant(Value, dl, TCVT);
11369       break;
11370     case 'N':  // "N" is a positive constant that is an exact power of two.
11371       if (Value > 0 && isPowerOf2_64(Value))
11372         Result = DAG.getTargetConstant(Value, dl, TCVT);
11373       break;
11374     case 'O':  // "O" is the constant zero.
11375       if (Value == 0)
11376         Result = DAG.getTargetConstant(Value, dl, TCVT);
11377       break;
11378     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11379       if (isInt<16>(-Value))
11380         Result = DAG.getTargetConstant(Value, dl, TCVT);
11381       break;
11382     }
11383     break;
11384   }
11385   }
11386 
11387   if (Result.getNode()) {
11388     Ops.push_back(Result);
11389     return;
11390   }
11391 
11392   // Handle standard constraint letters.
11393   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11394 }
11395 
11396 // isLegalAddressingMode - Return true if the addressing mode represented
11397 // by AM is legal for this target, for a load/store of the specified type.
11398 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11399                                               const AddrMode &AM, Type *Ty,
11400                                               unsigned AS) const {
11401   // PPC does not allow r+i addressing modes for vectors!
11402   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11403     return false;
11404 
11405   // PPC allows a sign-extended 16-bit immediate field.
11406   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11407     return false;
11408 
11409   // No global is ever allowed as a base.
11410   if (AM.BaseGV)
11411     return false;
11412 
11413   // PPC only support r+r,
11414   switch (AM.Scale) {
11415   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11416     break;
11417   case 1:
11418     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11419       return false;
11420     // Otherwise we have r+r or r+i.
11421     break;
11422   case 2:
11423     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11424       return false;
11425     // Allow 2*r as r+r.
11426     break;
11427   default:
11428     // No other scales are supported.
11429     return false;
11430   }
11431 
11432   return true;
11433 }
11434 
11435 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11436                                            SelectionDAG &DAG) const {
11437   MachineFunction &MF = DAG.getMachineFunction();
11438   MachineFrameInfo *MFI = MF.getFrameInfo();
11439   MFI->setReturnAddressIsTaken(true);
11440 
11441   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11442     return SDValue();
11443 
11444   SDLoc dl(Op);
11445   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11446 
11447   // Make sure the function does not optimize away the store of the RA to
11448   // the stack.
11449   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11450   FuncInfo->setLRStoreRequired();
11451   bool isPPC64 = Subtarget.isPPC64();
11452   auto PtrVT = getPointerTy(MF.getDataLayout());
11453 
11454   if (Depth > 0) {
11455     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11456     SDValue Offset =
11457         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11458                         isPPC64 ? MVT::i64 : MVT::i32);
11459     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11460                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11461                        MachinePointerInfo(), false, false, false, 0);
11462   }
11463 
11464   // Just load the return address off the stack.
11465   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11466   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11467                      MachinePointerInfo(), false, false, false, 0);
11468 }
11469 
11470 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11471                                           SelectionDAG &DAG) const {
11472   SDLoc dl(Op);
11473   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11474 
11475   MachineFunction &MF = DAG.getMachineFunction();
11476   MachineFrameInfo *MFI = MF.getFrameInfo();
11477   MFI->setFrameAddressIsTaken(true);
11478 
11479   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11480   bool isPPC64 = PtrVT == MVT::i64;
11481 
11482   // Naked functions never have a frame pointer, and so we use r1. For all
11483   // other functions, this decision must be delayed until during PEI.
11484   unsigned FrameReg;
11485   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11486     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11487   else
11488     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11489 
11490   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11491                                          PtrVT);
11492   while (Depth--)
11493     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11494                             FrameAddr, MachinePointerInfo(), false, false,
11495                             false, 0);
11496   return FrameAddr;
11497 }
11498 
11499 // FIXME? Maybe this could be a TableGen attribute on some registers and
11500 // this table could be generated automatically from RegInfo.
11501 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11502                                               SelectionDAG &DAG) const {
11503   bool isPPC64 = Subtarget.isPPC64();
11504   bool isDarwinABI = Subtarget.isDarwinABI();
11505 
11506   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11507       (!isPPC64 && VT != MVT::i32))
11508     report_fatal_error("Invalid register global variable type");
11509 
11510   bool is64Bit = isPPC64 && VT == MVT::i64;
11511   unsigned Reg = StringSwitch<unsigned>(RegName)
11512                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11513                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11514                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11515                                   (is64Bit ? PPC::X13 : PPC::R13))
11516                    .Default(0);
11517 
11518   if (Reg)
11519     return Reg;
11520   report_fatal_error("Invalid register name global variable");
11521 }
11522 
11523 bool
11524 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11525   // The PowerPC target isn't yet aware of offsets.
11526   return false;
11527 }
11528 
11529 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11530                                            const CallInst &I,
11531                                            unsigned Intrinsic) const {
11532 
11533   switch (Intrinsic) {
11534   case Intrinsic::ppc_qpx_qvlfd:
11535   case Intrinsic::ppc_qpx_qvlfs:
11536   case Intrinsic::ppc_qpx_qvlfcd:
11537   case Intrinsic::ppc_qpx_qvlfcs:
11538   case Intrinsic::ppc_qpx_qvlfiwa:
11539   case Intrinsic::ppc_qpx_qvlfiwz:
11540   case Intrinsic::ppc_altivec_lvx:
11541   case Intrinsic::ppc_altivec_lvxl:
11542   case Intrinsic::ppc_altivec_lvebx:
11543   case Intrinsic::ppc_altivec_lvehx:
11544   case Intrinsic::ppc_altivec_lvewx:
11545   case Intrinsic::ppc_vsx_lxvd2x:
11546   case Intrinsic::ppc_vsx_lxvw4x: {
11547     EVT VT;
11548     switch (Intrinsic) {
11549     case Intrinsic::ppc_altivec_lvebx:
11550       VT = MVT::i8;
11551       break;
11552     case Intrinsic::ppc_altivec_lvehx:
11553       VT = MVT::i16;
11554       break;
11555     case Intrinsic::ppc_altivec_lvewx:
11556       VT = MVT::i32;
11557       break;
11558     case Intrinsic::ppc_vsx_lxvd2x:
11559       VT = MVT::v2f64;
11560       break;
11561     case Intrinsic::ppc_qpx_qvlfd:
11562       VT = MVT::v4f64;
11563       break;
11564     case Intrinsic::ppc_qpx_qvlfs:
11565       VT = MVT::v4f32;
11566       break;
11567     case Intrinsic::ppc_qpx_qvlfcd:
11568       VT = MVT::v2f64;
11569       break;
11570     case Intrinsic::ppc_qpx_qvlfcs:
11571       VT = MVT::v2f32;
11572       break;
11573     default:
11574       VT = MVT::v4i32;
11575       break;
11576     }
11577 
11578     Info.opc = ISD::INTRINSIC_W_CHAIN;
11579     Info.memVT = VT;
11580     Info.ptrVal = I.getArgOperand(0);
11581     Info.offset = -VT.getStoreSize()+1;
11582     Info.size = 2*VT.getStoreSize()-1;
11583     Info.align = 1;
11584     Info.vol = false;
11585     Info.readMem = true;
11586     Info.writeMem = false;
11587     return true;
11588   }
11589   case Intrinsic::ppc_qpx_qvlfda:
11590   case Intrinsic::ppc_qpx_qvlfsa:
11591   case Intrinsic::ppc_qpx_qvlfcda:
11592   case Intrinsic::ppc_qpx_qvlfcsa:
11593   case Intrinsic::ppc_qpx_qvlfiwaa:
11594   case Intrinsic::ppc_qpx_qvlfiwza: {
11595     EVT VT;
11596     switch (Intrinsic) {
11597     case Intrinsic::ppc_qpx_qvlfda:
11598       VT = MVT::v4f64;
11599       break;
11600     case Intrinsic::ppc_qpx_qvlfsa:
11601       VT = MVT::v4f32;
11602       break;
11603     case Intrinsic::ppc_qpx_qvlfcda:
11604       VT = MVT::v2f64;
11605       break;
11606     case Intrinsic::ppc_qpx_qvlfcsa:
11607       VT = MVT::v2f32;
11608       break;
11609     default:
11610       VT = MVT::v4i32;
11611       break;
11612     }
11613 
11614     Info.opc = ISD::INTRINSIC_W_CHAIN;
11615     Info.memVT = VT;
11616     Info.ptrVal = I.getArgOperand(0);
11617     Info.offset = 0;
11618     Info.size = VT.getStoreSize();
11619     Info.align = 1;
11620     Info.vol = false;
11621     Info.readMem = true;
11622     Info.writeMem = false;
11623     return true;
11624   }
11625   case Intrinsic::ppc_qpx_qvstfd:
11626   case Intrinsic::ppc_qpx_qvstfs:
11627   case Intrinsic::ppc_qpx_qvstfcd:
11628   case Intrinsic::ppc_qpx_qvstfcs:
11629   case Intrinsic::ppc_qpx_qvstfiw:
11630   case Intrinsic::ppc_altivec_stvx:
11631   case Intrinsic::ppc_altivec_stvxl:
11632   case Intrinsic::ppc_altivec_stvebx:
11633   case Intrinsic::ppc_altivec_stvehx:
11634   case Intrinsic::ppc_altivec_stvewx:
11635   case Intrinsic::ppc_vsx_stxvd2x:
11636   case Intrinsic::ppc_vsx_stxvw4x: {
11637     EVT VT;
11638     switch (Intrinsic) {
11639     case Intrinsic::ppc_altivec_stvebx:
11640       VT = MVT::i8;
11641       break;
11642     case Intrinsic::ppc_altivec_stvehx:
11643       VT = MVT::i16;
11644       break;
11645     case Intrinsic::ppc_altivec_stvewx:
11646       VT = MVT::i32;
11647       break;
11648     case Intrinsic::ppc_vsx_stxvd2x:
11649       VT = MVT::v2f64;
11650       break;
11651     case Intrinsic::ppc_qpx_qvstfd:
11652       VT = MVT::v4f64;
11653       break;
11654     case Intrinsic::ppc_qpx_qvstfs:
11655       VT = MVT::v4f32;
11656       break;
11657     case Intrinsic::ppc_qpx_qvstfcd:
11658       VT = MVT::v2f64;
11659       break;
11660     case Intrinsic::ppc_qpx_qvstfcs:
11661       VT = MVT::v2f32;
11662       break;
11663     default:
11664       VT = MVT::v4i32;
11665       break;
11666     }
11667 
11668     Info.opc = ISD::INTRINSIC_VOID;
11669     Info.memVT = VT;
11670     Info.ptrVal = I.getArgOperand(1);
11671     Info.offset = -VT.getStoreSize()+1;
11672     Info.size = 2*VT.getStoreSize()-1;
11673     Info.align = 1;
11674     Info.vol = false;
11675     Info.readMem = false;
11676     Info.writeMem = true;
11677     return true;
11678   }
11679   case Intrinsic::ppc_qpx_qvstfda:
11680   case Intrinsic::ppc_qpx_qvstfsa:
11681   case Intrinsic::ppc_qpx_qvstfcda:
11682   case Intrinsic::ppc_qpx_qvstfcsa:
11683   case Intrinsic::ppc_qpx_qvstfiwa: {
11684     EVT VT;
11685     switch (Intrinsic) {
11686     case Intrinsic::ppc_qpx_qvstfda:
11687       VT = MVT::v4f64;
11688       break;
11689     case Intrinsic::ppc_qpx_qvstfsa:
11690       VT = MVT::v4f32;
11691       break;
11692     case Intrinsic::ppc_qpx_qvstfcda:
11693       VT = MVT::v2f64;
11694       break;
11695     case Intrinsic::ppc_qpx_qvstfcsa:
11696       VT = MVT::v2f32;
11697       break;
11698     default:
11699       VT = MVT::v4i32;
11700       break;
11701     }
11702 
11703     Info.opc = ISD::INTRINSIC_VOID;
11704     Info.memVT = VT;
11705     Info.ptrVal = I.getArgOperand(1);
11706     Info.offset = 0;
11707     Info.size = VT.getStoreSize();
11708     Info.align = 1;
11709     Info.vol = false;
11710     Info.readMem = false;
11711     Info.writeMem = true;
11712     return true;
11713   }
11714   default:
11715     break;
11716   }
11717 
11718   return false;
11719 }
11720 
11721 /// getOptimalMemOpType - Returns the target specific optimal type for load
11722 /// and store operations as a result of memset, memcpy, and memmove
11723 /// lowering. If DstAlign is zero that means it's safe to destination
11724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11725 /// means there isn't a need to check it against alignment requirement,
11726 /// probably because the source does not need to be loaded. If 'IsMemset' is
11727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11729 /// source is constant so it does not need to be loaded.
11730 /// It returns EVT::Other if the type should be determined using generic
11731 /// target-independent logic.
11732 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11733                                            unsigned DstAlign, unsigned SrcAlign,
11734                                            bool IsMemset, bool ZeroMemset,
11735                                            bool MemcpyStrSrc,
11736                                            MachineFunction &MF) const {
11737   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11738     const Function *F = MF.getFunction();
11739     // When expanding a memset, require at least two QPX instructions to cover
11740     // the cost of loading the value to be stored from the constant pool.
11741     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11742        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11743         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11744       return MVT::v4f64;
11745     }
11746 
11747     // We should use Altivec/VSX loads and stores when available. For unaligned
11748     // addresses, unaligned VSX loads are only fast starting with the P8.
11749     if (Subtarget.hasAltivec() && Size >= 16 &&
11750         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11751          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11752       return MVT::v4i32;
11753   }
11754 
11755   if (Subtarget.isPPC64()) {
11756     return MVT::i64;
11757   }
11758 
11759   return MVT::i32;
11760 }
11761 
11762 /// \brief Returns true if it is beneficial to convert a load of a constant
11763 /// to just the constant itself.
11764 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11765                                                           Type *Ty) const {
11766   assert(Ty->isIntegerTy());
11767 
11768   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11769   return !(BitSize == 0 || BitSize > 64);
11770 }
11771 
11772 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11773   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11774     return false;
11775   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11776   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11777   return NumBits1 == 64 && NumBits2 == 32;
11778 }
11779 
11780 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11781   if (!VT1.isInteger() || !VT2.isInteger())
11782     return false;
11783   unsigned NumBits1 = VT1.getSizeInBits();
11784   unsigned NumBits2 = VT2.getSizeInBits();
11785   return NumBits1 == 64 && NumBits2 == 32;
11786 }
11787 
11788 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11789   // Generally speaking, zexts are not free, but they are free when they can be
11790   // folded with other operations.
11791   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11792     EVT MemVT = LD->getMemoryVT();
11793     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11794          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11795         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11796          LD->getExtensionType() == ISD::ZEXTLOAD))
11797       return true;
11798   }
11799 
11800   // FIXME: Add other cases...
11801   //  - 32-bit shifts with a zext to i64
11802   //  - zext after ctlz, bswap, etc.
11803   //  - zext after and by a constant mask
11804 
11805   return TargetLowering::isZExtFree(Val, VT2);
11806 }
11807 
11808 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11809   assert(VT.isFloatingPoint());
11810   return true;
11811 }
11812 
11813 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11814   return isInt<16>(Imm) || isUInt<16>(Imm);
11815 }
11816 
11817 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11818   return isInt<16>(Imm) || isUInt<16>(Imm);
11819 }
11820 
11821 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11822                                                        unsigned,
11823                                                        unsigned,
11824                                                        bool *Fast) const {
11825   if (DisablePPCUnaligned)
11826     return false;
11827 
11828   // PowerPC supports unaligned memory access for simple non-vector types.
11829   // Although accessing unaligned addresses is not as efficient as accessing
11830   // aligned addresses, it is generally more efficient than manual expansion,
11831   // and generally only traps for software emulation when crossing page
11832   // boundaries.
11833 
11834   if (!VT.isSimple())
11835     return false;
11836 
11837   if (VT.getSimpleVT().isVector()) {
11838     if (Subtarget.hasVSX()) {
11839       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11840           VT != MVT::v4f32 && VT != MVT::v4i32)
11841         return false;
11842     } else {
11843       return false;
11844     }
11845   }
11846 
11847   if (VT == MVT::ppcf128)
11848     return false;
11849 
11850   if (Fast)
11851     *Fast = true;
11852 
11853   return true;
11854 }
11855 
11856 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11857   VT = VT.getScalarType();
11858 
11859   if (!VT.isSimple())
11860     return false;
11861 
11862   switch (VT.getSimpleVT().SimpleTy) {
11863   case MVT::f32:
11864   case MVT::f64:
11865     return true;
11866   default:
11867     break;
11868   }
11869 
11870   return false;
11871 }
11872 
11873 const MCPhysReg *
11874 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11875   // LR is a callee-save register, but we must treat it as clobbered by any call
11876   // site. Hence we include LR in the scratch registers, which are in turn added
11877   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11878   // to CTR, which is used by any indirect call.
11879   static const MCPhysReg ScratchRegs[] = {
11880     PPC::X12, PPC::LR8, PPC::CTR8, 0
11881   };
11882 
11883   return ScratchRegs;
11884 }
11885 
11886 unsigned PPCTargetLowering::getExceptionPointerRegister(
11887     const Constant *PersonalityFn) const {
11888   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
11889 }
11890 
11891 unsigned PPCTargetLowering::getExceptionSelectorRegister(
11892     const Constant *PersonalityFn) const {
11893   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
11894 }
11895 
11896 bool
11897 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11898                      EVT VT , unsigned DefinedValues) const {
11899   if (VT == MVT::v2i64)
11900     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
11901 
11902   if (Subtarget.hasVSX() || Subtarget.hasQPX())
11903     return true;
11904 
11905   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11906 }
11907 
11908 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11909   if (DisableILPPref || Subtarget.enableMachineScheduler())
11910     return TargetLowering::getSchedulingPreference(N);
11911 
11912   return Sched::ILP;
11913 }
11914 
11915 // Create a fast isel object.
11916 FastISel *
11917 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11918                                   const TargetLibraryInfo *LibInfo) const {
11919   return PPC::createFastISel(FuncInfo, LibInfo);
11920 }
11921 
11922 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
11923   if (Subtarget.isDarwinABI()) return;
11924   if (!Subtarget.isPPC64()) return;
11925 
11926   // Update IsSplitCSR in PPCFunctionInfo
11927   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
11928   PFI->setIsSplitCSR(true);
11929 }
11930 
11931 void PPCTargetLowering::insertCopiesSplitCSR(
11932   MachineBasicBlock *Entry,
11933   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
11934   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11935   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
11936   if (!IStart)
11937     return;
11938 
11939   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11940   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
11941   MachineBasicBlock::iterator MBBI = Entry->begin();
11942   for (const MCPhysReg *I = IStart; *I; ++I) {
11943     const TargetRegisterClass *RC = nullptr;
11944     if (PPC::G8RCRegClass.contains(*I))
11945       RC = &PPC::G8RCRegClass;
11946     else if (PPC::F8RCRegClass.contains(*I))
11947       RC = &PPC::F8RCRegClass;
11948     else if (PPC::CRRCRegClass.contains(*I))
11949       RC = &PPC::CRRCRegClass;
11950     else if (PPC::VRRCRegClass.contains(*I))
11951       RC = &PPC::VRRCRegClass;
11952     else
11953       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
11954 
11955     unsigned NewVR = MRI->createVirtualRegister(RC);
11956     // Create copy from CSR to a virtual register.
11957     // FIXME: this currently does not emit CFI pseudo-instructions, it works
11958     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
11959     // nounwind. If we want to generalize this later, we may need to emit
11960     // CFI pseudo-instructions.
11961     assert(Entry->getParent()->getFunction()->hasFnAttribute(
11962              Attribute::NoUnwind) &&
11963            "Function should be nounwind in insertCopiesSplitCSR!");
11964     Entry->addLiveIn(*I);
11965     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
11966       .addReg(*I);
11967 
11968     // Insert the copy-back instructions right before the terminator
11969     for (auto *Exit : Exits)
11970       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
11971               TII->get(TargetOpcode::COPY), *I)
11972         .addReg(NewVR);
11973   }
11974 }
11975 
11976 // Override to enable LOAD_STACK_GUARD lowering on Linux.
11977 bool PPCTargetLowering::useLoadStackGuardNode() const {
11978   if (!Subtarget.isTargetLinux())
11979     return TargetLowering::useLoadStackGuardNode();
11980   return true;
11981 }
11982 
11983 // Override to disable global variable loading on Linux.
11984 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
11985   if (!Subtarget.isTargetLinux())
11986     return TargetLowering::insertSSPDeclarations(M);
11987 }
11988