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 (!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   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
348   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
349 
350   // We want to custom lower some of our intrinsics.
351   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
352 
353   // To handle counter-based loop conditions.
354   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
355 
356   // Comparisons that require checking two conditions.
357   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
358   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
359   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
360   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
361   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
362   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
363   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
364   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
365   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
366   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
367   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
368   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
369 
370   if (Subtarget.has64BitSupport()) {
371     // They also have instructions for converting between i64 and fp.
372     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
374     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
376     // This is just the low 32 bits of a (signed) fp->i64 conversion.
377     // We cannot do this with Promote because i64 is not a legal type.
378     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
379 
380     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
381       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382   } else {
383     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
384     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
385   }
386 
387   // With the instructions enabled under FPCVT, we can do everything.
388   if (Subtarget.hasFPCVT()) {
389     if (Subtarget.has64BitSupport()) {
390       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
391       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
392       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
393       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
394     }
395 
396     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
397     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
398     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
399     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
400   }
401 
402   if (Subtarget.use64BitRegs()) {
403     // 64-bit PowerPC implementations can support i64 types directly
404     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
405     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
406     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
407     // 64-bit PowerPC wants to expand i128 shifts itself.
408     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
409     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
410     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
411   } else {
412     // 32-bit PowerPC wants to expand i64 shifts itself.
413     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
414     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
415     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
416   }
417 
418   if (Subtarget.hasAltivec()) {
419     // First set operation action for all vector types to expand. Then we
420     // will selectively turn on ones that can be effectively codegen'd.
421     for (MVT VT : MVT::vector_valuetypes()) {
422       // add/sub are legal for all supported vector VT's.
423       setOperationAction(ISD::ADD, VT, Legal);
424       setOperationAction(ISD::SUB, VT, Legal);
425 
426       // Vector instructions introduced in P8
427       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
428         setOperationAction(ISD::CTPOP, VT, Legal);
429         setOperationAction(ISD::CTLZ, VT, Legal);
430       }
431       else {
432         setOperationAction(ISD::CTPOP, VT, Expand);
433         setOperationAction(ISD::CTLZ, VT, Expand);
434       }
435 
436       // We promote all shuffles to v16i8.
437       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
438       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
439 
440       // We promote all non-typed operations to v4i32.
441       setOperationAction(ISD::AND   , VT, Promote);
442       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
443       setOperationAction(ISD::OR    , VT, Promote);
444       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
445       setOperationAction(ISD::XOR   , VT, Promote);
446       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
447       setOperationAction(ISD::LOAD  , VT, Promote);
448       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
449       setOperationAction(ISD::SELECT, VT, Promote);
450       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
451       setOperationAction(ISD::SELECT_CC, VT, Promote);
452       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
453       setOperationAction(ISD::STORE, VT, Promote);
454       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
455 
456       // No other operations are legal.
457       setOperationAction(ISD::MUL , VT, Expand);
458       setOperationAction(ISD::SDIV, VT, Expand);
459       setOperationAction(ISD::SREM, VT, Expand);
460       setOperationAction(ISD::UDIV, VT, Expand);
461       setOperationAction(ISD::UREM, VT, Expand);
462       setOperationAction(ISD::FDIV, VT, Expand);
463       setOperationAction(ISD::FREM, VT, Expand);
464       setOperationAction(ISD::FNEG, VT, Expand);
465       setOperationAction(ISD::FSQRT, VT, Expand);
466       setOperationAction(ISD::FLOG, VT, Expand);
467       setOperationAction(ISD::FLOG10, VT, Expand);
468       setOperationAction(ISD::FLOG2, VT, Expand);
469       setOperationAction(ISD::FEXP, VT, Expand);
470       setOperationAction(ISD::FEXP2, VT, Expand);
471       setOperationAction(ISD::FSIN, VT, Expand);
472       setOperationAction(ISD::FCOS, VT, Expand);
473       setOperationAction(ISD::FABS, VT, Expand);
474       setOperationAction(ISD::FPOWI, VT, Expand);
475       setOperationAction(ISD::FFLOOR, VT, Expand);
476       setOperationAction(ISD::FCEIL,  VT, Expand);
477       setOperationAction(ISD::FTRUNC, VT, Expand);
478       setOperationAction(ISD::FRINT,  VT, Expand);
479       setOperationAction(ISD::FNEARBYINT, VT, Expand);
480       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
481       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
482       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
483       setOperationAction(ISD::MULHU, VT, Expand);
484       setOperationAction(ISD::MULHS, VT, Expand);
485       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
486       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
487       setOperationAction(ISD::UDIVREM, VT, Expand);
488       setOperationAction(ISD::SDIVREM, VT, Expand);
489       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
490       setOperationAction(ISD::FPOW, VT, Expand);
491       setOperationAction(ISD::BSWAP, VT, Expand);
492       setOperationAction(ISD::CTTZ, VT, Expand);
493       setOperationAction(ISD::VSELECT, VT, Expand);
494       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
495       setOperationAction(ISD::ROTL, VT, Expand);
496       setOperationAction(ISD::ROTR, VT, Expand);
497 
498       for (MVT InnerVT : MVT::vector_valuetypes()) {
499         setTruncStoreAction(VT, InnerVT, Expand);
500         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
501         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
502         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
503       }
504     }
505 
506     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
507     // with merges, splats, etc.
508     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
509 
510     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
511     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
512     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
513     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
514     setOperationAction(ISD::SELECT, MVT::v4i32,
515                        Subtarget.useCRBits() ? Legal : Expand);
516     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
517     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
518     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
519     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
520     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
521     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
524     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
525 
526     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
527     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
528     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
529     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
530 
531     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
532     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
533 
534     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
535       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
536       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
537     }
538 
539     if (Subtarget.hasP8Altivec())
540       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
541     else
542       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
543 
544     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
545     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
546 
547     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
548     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
549 
550     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
551     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
552     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
553     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
554 
555     // Altivec does not contain unordered floating-point compare instructions
556     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
557     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
558     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
559     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
560 
561     if (Subtarget.hasVSX()) {
562       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
563       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
564       if (Subtarget.hasP8Vector()) {
565         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
566         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
567       }
568       if (Subtarget.hasDirectMove() && isPPC64) {
569         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
570         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
571         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
572         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
573         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
574         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
575         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
576         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
577       }
578       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
579 
580       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
581       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
582       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
583       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
584       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
585 
586       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
587 
588       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
589       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
590 
591       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
592       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
593 
594       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
595       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
596       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
597       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
598       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
599 
600       // Share the Altivec comparison restrictions.
601       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
602       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
603       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
604       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
605 
606       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
607       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
608 
609       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
610 
611       if (Subtarget.hasP8Vector())
612         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
613 
614       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
615 
616       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
617       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
618       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
619 
620       if (Subtarget.hasP8Altivec()) {
621         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
622         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
623         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
624 
625         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
626       }
627       else {
628         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
629         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
630         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
631 
632         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
633 
634         // VSX v2i64 only supports non-arithmetic operations.
635         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
636         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
637       }
638 
639       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
640       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
641       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
642       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
643 
644       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
645 
646       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
647       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
648       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
649       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
650 
651       // Vector operation legalization checks the result type of
652       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
653       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
654       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
655       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
656       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
657 
658       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
659       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
660       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
661       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
662 
663       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
664     }
665 
666     if (Subtarget.hasP8Altivec()) {
667       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
668       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
669     }
670 
671     if (Subtarget.hasP9Vector()) {
672       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
673       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
674     }
675 
676     if (Subtarget.isISA3_0() && Subtarget.hasDirectMove())
677       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Legal);
678   }
679 
680   if (Subtarget.hasQPX()) {
681     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
682     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
683     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
684     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
685 
686     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
687     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
688 
689     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
690     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
691 
692     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
693     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
694 
695     if (!Subtarget.useCRBits())
696       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
697     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
698 
699     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
700     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
701     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
703     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
704     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
705     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
706 
707     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
708     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
709 
710     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
711     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
712     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
713 
714     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
715     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
716     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
717     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
718     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
719     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
720     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
721     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
722     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
723     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
724     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
725 
726     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
727     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
728 
729     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
730     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
731 
732     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
733 
734     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
735     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
736     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
737     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
738 
739     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
740     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
741 
742     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
743     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
744 
745     if (!Subtarget.useCRBits())
746       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
747     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
748 
749     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
750     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
751     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
752     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
753     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
754     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
755     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
756 
757     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
758     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
759 
760     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
761     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
762     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
763     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
764     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
765     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
766     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
767     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
768     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
769     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
770     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
771 
772     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
773     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
774 
775     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
776     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
777 
778     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
779 
780     setOperationAction(ISD::AND , MVT::v4i1, Legal);
781     setOperationAction(ISD::OR , MVT::v4i1, Legal);
782     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
783 
784     if (!Subtarget.useCRBits())
785       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
786     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
787 
788     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
789     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
790 
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
792     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
793     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
794     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
795     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
796     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
797     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
798 
799     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
800     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
801 
802     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
803 
804     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
805     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
806     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
807     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
808 
809     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
810     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
811     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
812     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
813 
814     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
815     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
816 
817     // These need to set FE_INEXACT, and so cannot be vectorized here.
818     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
819     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
820 
821     if (TM.Options.UnsafeFPMath) {
822       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
823       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
824 
825       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
826       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
827     } else {
828       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
829       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
830 
831       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
832       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
833     }
834   }
835 
836   if (Subtarget.has64BitSupport())
837     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
838 
839   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
840 
841   if (!isPPC64) {
842     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
843     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
844   }
845 
846   setBooleanContents(ZeroOrOneBooleanContent);
847 
848   if (Subtarget.hasAltivec()) {
849     // Altivec instructions set fields to all zeros or all ones.
850     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
851   }
852 
853   if (!isPPC64) {
854     // These libcalls are not available in 32-bit.
855     setLibcallName(RTLIB::SHL_I128, nullptr);
856     setLibcallName(RTLIB::SRL_I128, nullptr);
857     setLibcallName(RTLIB::SRA_I128, nullptr);
858   }
859 
860   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
861 
862   // We have target-specific dag combine patterns for the following nodes:
863   setTargetDAGCombine(ISD::SINT_TO_FP);
864   setTargetDAGCombine(ISD::BUILD_VECTOR);
865   if (Subtarget.hasFPCVT())
866     setTargetDAGCombine(ISD::UINT_TO_FP);
867   setTargetDAGCombine(ISD::LOAD);
868   setTargetDAGCombine(ISD::STORE);
869   setTargetDAGCombine(ISD::BR_CC);
870   if (Subtarget.useCRBits())
871     setTargetDAGCombine(ISD::BRCOND);
872   setTargetDAGCombine(ISD::BSWAP);
873   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
874   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
875   setTargetDAGCombine(ISD::INTRINSIC_VOID);
876 
877   setTargetDAGCombine(ISD::SIGN_EXTEND);
878   setTargetDAGCombine(ISD::ZERO_EXTEND);
879   setTargetDAGCombine(ISD::ANY_EXTEND);
880 
881   if (Subtarget.useCRBits()) {
882     setTargetDAGCombine(ISD::TRUNCATE);
883     setTargetDAGCombine(ISD::SETCC);
884     setTargetDAGCombine(ISD::SELECT_CC);
885   }
886 
887   // Use reciprocal estimates.
888   if (TM.Options.UnsafeFPMath) {
889     setTargetDAGCombine(ISD::FDIV);
890     setTargetDAGCombine(ISD::FSQRT);
891   }
892 
893   // Darwin long double math library functions have $LDBL128 appended.
894   if (Subtarget.isDarwin()) {
895     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
896     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
897     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
898     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
899     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
900     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
901     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
902     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
903     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
904     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
905   }
906 
907   // With 32 condition bits, we don't need to sink (and duplicate) compares
908   // aggressively in CodeGenPrep.
909   if (Subtarget.useCRBits()) {
910     setHasMultipleConditionRegisters();
911     setJumpIsExpensive();
912   }
913 
914   setMinFunctionAlignment(2);
915   if (Subtarget.isDarwin())
916     setPrefFunctionAlignment(4);
917 
918   switch (Subtarget.getDarwinDirective()) {
919   default: break;
920   case PPC::DIR_970:
921   case PPC::DIR_A2:
922   case PPC::DIR_E500mc:
923   case PPC::DIR_E5500:
924   case PPC::DIR_PWR4:
925   case PPC::DIR_PWR5:
926   case PPC::DIR_PWR5X:
927   case PPC::DIR_PWR6:
928   case PPC::DIR_PWR6X:
929   case PPC::DIR_PWR7:
930   case PPC::DIR_PWR8:
931   case PPC::DIR_PWR9:
932     setPrefFunctionAlignment(4);
933     setPrefLoopAlignment(4);
934     break;
935   }
936 
937   if (Subtarget.enableMachineScheduler())
938     setSchedulingPreference(Sched::Source);
939   else
940     setSchedulingPreference(Sched::Hybrid);
941 
942   computeRegisterProperties(STI.getRegisterInfo());
943 
944   // The Freescale cores do better with aggressive inlining of memcpy and
945   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
946   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
947       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
948     MaxStoresPerMemset = 32;
949     MaxStoresPerMemsetOptSize = 16;
950     MaxStoresPerMemcpy = 32;
951     MaxStoresPerMemcpyOptSize = 8;
952     MaxStoresPerMemmove = 32;
953     MaxStoresPerMemmoveOptSize = 8;
954   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
955     // The A2 also benefits from (very) aggressive inlining of memcpy and
956     // friends. The overhead of a the function call, even when warm, can be
957     // over one hundred cycles.
958     MaxStoresPerMemset = 128;
959     MaxStoresPerMemcpy = 128;
960     MaxStoresPerMemmove = 128;
961   }
962 }
963 
964 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
965 /// the desired ByVal argument alignment.
966 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
967                              unsigned MaxMaxAlign) {
968   if (MaxAlign == MaxMaxAlign)
969     return;
970   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
971     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
972       MaxAlign = 32;
973     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
974       MaxAlign = 16;
975   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
976     unsigned EltAlign = 0;
977     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
978     if (EltAlign > MaxAlign)
979       MaxAlign = EltAlign;
980   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
981     for (auto *EltTy : STy->elements()) {
982       unsigned EltAlign = 0;
983       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
984       if (EltAlign > MaxAlign)
985         MaxAlign = EltAlign;
986       if (MaxAlign == MaxMaxAlign)
987         break;
988     }
989   }
990 }
991 
992 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
993 /// function arguments in the caller parameter area.
994 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
995                                                   const DataLayout &DL) const {
996   // Darwin passes everything on 4 byte boundary.
997   if (Subtarget.isDarwin())
998     return 4;
999 
1000   // 16byte and wider vectors are passed on 16byte boundary.
1001   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1002   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1003   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1004     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1005   return Align;
1006 }
1007 
1008 bool PPCTargetLowering::useSoftFloat() const {
1009   return Subtarget.useSoftFloat();
1010 }
1011 
1012 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1013   switch ((PPCISD::NodeType)Opcode) {
1014   case PPCISD::FIRST_NUMBER:    break;
1015   case PPCISD::FSEL:            return "PPCISD::FSEL";
1016   case PPCISD::FCFID:           return "PPCISD::FCFID";
1017   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1018   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1019   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1020   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1021   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1022   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1023   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1024   case PPCISD::FRE:             return "PPCISD::FRE";
1025   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1026   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1027   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1028   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1029   case PPCISD::VPERM:           return "PPCISD::VPERM";
1030   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1031   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1032   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1033   case PPCISD::CMPB:            return "PPCISD::CMPB";
1034   case PPCISD::Hi:              return "PPCISD::Hi";
1035   case PPCISD::Lo:              return "PPCISD::Lo";
1036   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1037   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1038   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1039   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1040   case PPCISD::SRL:             return "PPCISD::SRL";
1041   case PPCISD::SRA:             return "PPCISD::SRA";
1042   case PPCISD::SHL:             return "PPCISD::SHL";
1043   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1044   case PPCISD::CALL:            return "PPCISD::CALL";
1045   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1046   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1047   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1048   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1049   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1050   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1051   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1052   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1053   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1054   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1055   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1056   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1057   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1058   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1059   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1060   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1061   case PPCISD::VCMP:            return "PPCISD::VCMP";
1062   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1063   case PPCISD::LBRX:            return "PPCISD::LBRX";
1064   case PPCISD::STBRX:           return "PPCISD::STBRX";
1065   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1066   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1067   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1068   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1069   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1070   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1071   case PPCISD::BDZ:             return "PPCISD::BDZ";
1072   case PPCISD::MFFS:            return "PPCISD::MFFS";
1073   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1074   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1075   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1076   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1077   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1078   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1079   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1080   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1081   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1082   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1083   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1084   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1085   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1086   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1087   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1088   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1089   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1090   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1091   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1092   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1093   case PPCISD::SC:              return "PPCISD::SC";
1094   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1095   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1096   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1097   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1098   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1099   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1100   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1101   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1102   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1103   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1104   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1105   }
1106   return nullptr;
1107 }
1108 
1109 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1110                                           EVT VT) const {
1111   if (!VT.isVector())
1112     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1113 
1114   if (Subtarget.hasQPX())
1115     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1116 
1117   return VT.changeVectorElementTypeToInteger();
1118 }
1119 
1120 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1121   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1122   return true;
1123 }
1124 
1125 //===----------------------------------------------------------------------===//
1126 // Node matching predicates, for use by the tblgen matching code.
1127 //===----------------------------------------------------------------------===//
1128 
1129 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1130 static bool isFloatingPointZero(SDValue Op) {
1131   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1132     return CFP->getValueAPF().isZero();
1133   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1134     // Maybe this has already been legalized into the constant pool?
1135     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1136       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1137         return CFP->getValueAPF().isZero();
1138   }
1139   return false;
1140 }
1141 
1142 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1143 /// true if Op is undef or if it matches the specified value.
1144 static bool isConstantOrUndef(int Op, int Val) {
1145   return Op < 0 || Op == Val;
1146 }
1147 
1148 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1149 /// VPKUHUM instruction.
1150 /// The ShuffleKind distinguishes between big-endian operations with
1151 /// two different inputs (0), either-endian operations with two identical
1152 /// inputs (1), and little-endian operations with two different inputs (2).
1153 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1154 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1155                                SelectionDAG &DAG) {
1156   bool IsLE = DAG.getDataLayout().isLittleEndian();
1157   if (ShuffleKind == 0) {
1158     if (IsLE)
1159       return false;
1160     for (unsigned i = 0; i != 16; ++i)
1161       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1162         return false;
1163   } else if (ShuffleKind == 2) {
1164     if (!IsLE)
1165       return false;
1166     for (unsigned i = 0; i != 16; ++i)
1167       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1168         return false;
1169   } else if (ShuffleKind == 1) {
1170     unsigned j = IsLE ? 0 : 1;
1171     for (unsigned i = 0; i != 8; ++i)
1172       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1173           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1174         return false;
1175   }
1176   return true;
1177 }
1178 
1179 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1180 /// VPKUWUM instruction.
1181 /// The ShuffleKind distinguishes between big-endian operations with
1182 /// two different inputs (0), either-endian operations with two identical
1183 /// inputs (1), and little-endian operations with two different inputs (2).
1184 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1185 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1186                                SelectionDAG &DAG) {
1187   bool IsLE = DAG.getDataLayout().isLittleEndian();
1188   if (ShuffleKind == 0) {
1189     if (IsLE)
1190       return false;
1191     for (unsigned i = 0; i != 16; i += 2)
1192       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1193           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1194         return false;
1195   } else if (ShuffleKind == 2) {
1196     if (!IsLE)
1197       return false;
1198     for (unsigned i = 0; i != 16; i += 2)
1199       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1200           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1201         return false;
1202   } else if (ShuffleKind == 1) {
1203     unsigned j = IsLE ? 0 : 2;
1204     for (unsigned i = 0; i != 8; i += 2)
1205       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1206           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1207           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1208           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1209         return false;
1210   }
1211   return true;
1212 }
1213 
1214 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1215 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1216 /// current subtarget.
1217 ///
1218 /// The ShuffleKind distinguishes between big-endian operations with
1219 /// two different inputs (0), either-endian operations with two identical
1220 /// inputs (1), and little-endian operations with two different inputs (2).
1221 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1222 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1223                                SelectionDAG &DAG) {
1224   const PPCSubtarget& Subtarget =
1225     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1226   if (!Subtarget.hasP8Vector())
1227     return false;
1228 
1229   bool IsLE = DAG.getDataLayout().isLittleEndian();
1230   if (ShuffleKind == 0) {
1231     if (IsLE)
1232       return false;
1233     for (unsigned i = 0; i != 16; i += 4)
1234       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1235           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1236           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1237           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1238         return false;
1239   } else if (ShuffleKind == 2) {
1240     if (!IsLE)
1241       return false;
1242     for (unsigned i = 0; i != 16; i += 4)
1243       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1244           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1245           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1246           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1247         return false;
1248   } else if (ShuffleKind == 1) {
1249     unsigned j = IsLE ? 0 : 4;
1250     for (unsigned i = 0; i != 8; i += 4)
1251       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1252           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1253           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1254           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1255           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1256           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1257           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1258           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1259         return false;
1260   }
1261   return true;
1262 }
1263 
1264 /// isVMerge - Common function, used to match vmrg* shuffles.
1265 ///
1266 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1267                      unsigned LHSStart, unsigned RHSStart) {
1268   if (N->getValueType(0) != MVT::v16i8)
1269     return false;
1270   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1271          "Unsupported merge size!");
1272 
1273   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1274     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1275       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1276                              LHSStart+j+i*UnitSize) ||
1277           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1278                              RHSStart+j+i*UnitSize))
1279         return false;
1280     }
1281   return true;
1282 }
1283 
1284 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1285 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1286 /// The ShuffleKind distinguishes between big-endian merges with two
1287 /// different inputs (0), either-endian merges with two identical inputs (1),
1288 /// and little-endian merges with two different inputs (2).  For the latter,
1289 /// the input operands are swapped (see PPCInstrAltivec.td).
1290 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1291                              unsigned ShuffleKind, SelectionDAG &DAG) {
1292   if (DAG.getDataLayout().isLittleEndian()) {
1293     if (ShuffleKind == 1) // unary
1294       return isVMerge(N, UnitSize, 0, 0);
1295     else if (ShuffleKind == 2) // swapped
1296       return isVMerge(N, UnitSize, 0, 16);
1297     else
1298       return false;
1299   } else {
1300     if (ShuffleKind == 1) // unary
1301       return isVMerge(N, UnitSize, 8, 8);
1302     else if (ShuffleKind == 0) // normal
1303       return isVMerge(N, UnitSize, 8, 24);
1304     else
1305       return false;
1306   }
1307 }
1308 
1309 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1310 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1311 /// The ShuffleKind distinguishes between big-endian merges with two
1312 /// different inputs (0), either-endian merges with two identical inputs (1),
1313 /// and little-endian merges with two different inputs (2).  For the latter,
1314 /// the input operands are swapped (see PPCInstrAltivec.td).
1315 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1316                              unsigned ShuffleKind, SelectionDAG &DAG) {
1317   if (DAG.getDataLayout().isLittleEndian()) {
1318     if (ShuffleKind == 1) // unary
1319       return isVMerge(N, UnitSize, 8, 8);
1320     else if (ShuffleKind == 2) // swapped
1321       return isVMerge(N, UnitSize, 8, 24);
1322     else
1323       return false;
1324   } else {
1325     if (ShuffleKind == 1) // unary
1326       return isVMerge(N, UnitSize, 0, 0);
1327     else if (ShuffleKind == 0) // normal
1328       return isVMerge(N, UnitSize, 0, 16);
1329     else
1330       return false;
1331   }
1332 }
1333 
1334 /**
1335  * \brief Common function used to match vmrgew and vmrgow shuffles
1336  *
1337  * The indexOffset determines whether to look for even or odd words in
1338  * the shuffle mask. This is based on the of the endianness of the target
1339  * machine.
1340  *   - Little Endian:
1341  *     - Use offset of 0 to check for odd elements
1342  *     - Use offset of 4 to check for even elements
1343  *   - Big Endian:
1344  *     - Use offset of 0 to check for even elements
1345  *     - Use offset of 4 to check for odd elements
1346  * A detailed description of the vector element ordering for little endian and
1347  * big endian can be found at
1348  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1349  * Targeting your applications - what little endian and big endian IBM XL C/C++
1350  * compiler differences mean to you
1351  *
1352  * The mask to the shuffle vector instruction specifies the indices of the
1353  * elements from the two input vectors to place in the result. The elements are
1354  * numbered in array-access order, starting with the first vector. These vectors
1355  * are always of type v16i8, thus each vector will contain 16 elements of size
1356  * 8. More info on the shuffle vector can be found in the
1357  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1358  * Language Reference.
1359  *
1360  * The RHSStartValue indicates whether the same input vectors are used (unary)
1361  * or two different input vectors are used, based on the following:
1362  *   - If the instruction uses the same vector for both inputs, the range of the
1363  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1364  *     be 0.
1365  *   - If the instruction has two different vectors then the range of the
1366  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1367  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1368  *     to 31 specify elements in the second vector).
1369  *
1370  * \param[in] N The shuffle vector SD Node to analyze
1371  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1372  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1373  * vector to the shuffle_vector instruction
1374  * \return true iff this shuffle vector represents an even or odd word merge
1375  */
1376 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1377                      unsigned RHSStartValue) {
1378   if (N->getValueType(0) != MVT::v16i8)
1379     return false;
1380 
1381   for (unsigned i = 0; i < 2; ++i)
1382     for (unsigned j = 0; j < 4; ++j)
1383       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1384                              i*RHSStartValue+j+IndexOffset) ||
1385           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1386                              i*RHSStartValue+j+IndexOffset+8))
1387         return false;
1388   return true;
1389 }
1390 
1391 /**
1392  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1393  * vmrgow instructions.
1394  *
1395  * \param[in] N The shuffle vector SD Node to analyze
1396  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1397  * \param[in] ShuffleKind Identify the type of merge:
1398  *   - 0 = big-endian merge with two different inputs;
1399  *   - 1 = either-endian merge with two identical inputs;
1400  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1401  *     little-endian merges).
1402  * \param[in] DAG The current SelectionDAG
1403  * \return true iff this shuffle mask
1404  */
1405 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1406                               unsigned ShuffleKind, SelectionDAG &DAG) {
1407   if (DAG.getDataLayout().isLittleEndian()) {
1408     unsigned indexOffset = CheckEven ? 4 : 0;
1409     if (ShuffleKind == 1) // Unary
1410       return isVMerge(N, indexOffset, 0);
1411     else if (ShuffleKind == 2) // swapped
1412       return isVMerge(N, indexOffset, 16);
1413     else
1414       return false;
1415   }
1416   else {
1417     unsigned indexOffset = CheckEven ? 0 : 4;
1418     if (ShuffleKind == 1) // Unary
1419       return isVMerge(N, indexOffset, 0);
1420     else if (ShuffleKind == 0) // Normal
1421       return isVMerge(N, indexOffset, 16);
1422     else
1423       return false;
1424   }
1425   return false;
1426 }
1427 
1428 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1429 /// amount, otherwise return -1.
1430 /// The ShuffleKind distinguishes between big-endian operations with two
1431 /// different inputs (0), either-endian operations with two identical inputs
1432 /// (1), and little-endian operations with two different inputs (2).  For the
1433 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1434 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1435                              SelectionDAG &DAG) {
1436   if (N->getValueType(0) != MVT::v16i8)
1437     return -1;
1438 
1439   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1440 
1441   // Find the first non-undef value in the shuffle mask.
1442   unsigned i;
1443   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1444     /*search*/;
1445 
1446   if (i == 16) return -1;  // all undef.
1447 
1448   // Otherwise, check to see if the rest of the elements are consecutively
1449   // numbered from this value.
1450   unsigned ShiftAmt = SVOp->getMaskElt(i);
1451   if (ShiftAmt < i) return -1;
1452 
1453   ShiftAmt -= i;
1454   bool isLE = DAG.getDataLayout().isLittleEndian();
1455 
1456   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1457     // Check the rest of the elements to see if they are consecutive.
1458     for (++i; i != 16; ++i)
1459       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1460         return -1;
1461   } else if (ShuffleKind == 1) {
1462     // Check the rest of the elements to see if they are consecutive.
1463     for (++i; i != 16; ++i)
1464       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1465         return -1;
1466   } else
1467     return -1;
1468 
1469   if (isLE)
1470     ShiftAmt = 16 - ShiftAmt;
1471 
1472   return ShiftAmt;
1473 }
1474 
1475 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1476 /// specifies a splat of a single element that is suitable for input to
1477 /// VSPLTB/VSPLTH/VSPLTW.
1478 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1479   assert(N->getValueType(0) == MVT::v16i8 &&
1480          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1481 
1482   // The consecutive indices need to specify an element, not part of two
1483   // different elements.  So abandon ship early if this isn't the case.
1484   if (N->getMaskElt(0) % EltSize != 0)
1485     return false;
1486 
1487   // This is a splat operation if each element of the permute is the same, and
1488   // if the value doesn't reference the second vector.
1489   unsigned ElementBase = N->getMaskElt(0);
1490 
1491   // FIXME: Handle UNDEF elements too!
1492   if (ElementBase >= 16)
1493     return false;
1494 
1495   // Check that the indices are consecutive, in the case of a multi-byte element
1496   // splatted with a v16i8 mask.
1497   for (unsigned i = 1; i != EltSize; ++i)
1498     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1499       return false;
1500 
1501   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1502     if (N->getMaskElt(i) < 0) continue;
1503     for (unsigned j = 0; j != EltSize; ++j)
1504       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1505         return false;
1506   }
1507   return true;
1508 }
1509 
1510 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1511                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1512 
1513   // Check that the mask is shuffling words
1514   for (unsigned i = 0; i < 4; ++i) {
1515     unsigned B0 = N->getMaskElt(i*4);
1516     unsigned B1 = N->getMaskElt(i*4+1);
1517     unsigned B2 = N->getMaskElt(i*4+2);
1518     unsigned B3 = N->getMaskElt(i*4+3);
1519     if (B0 % 4)
1520       return false;
1521     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1522       return false;
1523   }
1524 
1525   // Now we look at mask elements 0,4,8,12
1526   unsigned M0 = N->getMaskElt(0) / 4;
1527   unsigned M1 = N->getMaskElt(4) / 4;
1528   unsigned M2 = N->getMaskElt(8) / 4;
1529   unsigned M3 = N->getMaskElt(12) / 4;
1530   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1531   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1532 
1533   // Below, let H and L be arbitrary elements of the shuffle mask
1534   // where H is in the range [4,7] and L is in the range [0,3].
1535   // H, 1, 2, 3 or L, 5, 6, 7
1536   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1537       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1538     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1539     InsertAtByte = IsLE ? 12 : 0;
1540     Swap = M0 < 4;
1541     return true;
1542   }
1543   // 0, H, 2, 3 or 4, L, 6, 7
1544   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1545       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1546     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1547     InsertAtByte = IsLE ? 8 : 4;
1548     Swap = M1 < 4;
1549     return true;
1550   }
1551   // 0, 1, H, 3 or 4, 5, L, 7
1552   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1553       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1554     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1555     InsertAtByte = IsLE ? 4 : 8;
1556     Swap = M2 < 4;
1557     return true;
1558   }
1559   // 0, 1, 2, H or 4, 5, 6, L
1560   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1561       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1562     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1563     InsertAtByte = IsLE ? 0 : 12;
1564     Swap = M3 < 4;
1565     return true;
1566   }
1567 
1568   // If both vector operands for the shuffle are the same vector, the mask will
1569   // contain only elements from the first one and the second one will be undef.
1570   if (N->getOperand(1).isUndef()) {
1571     ShiftElts = 0;
1572     Swap = true;
1573     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1574     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1575       InsertAtByte = IsLE ? 12 : 0;
1576       return true;
1577     }
1578     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1579       InsertAtByte = IsLE ? 8 : 4;
1580       return true;
1581     }
1582     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1583       InsertAtByte = IsLE ? 4 : 8;
1584       return true;
1585     }
1586     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1587       InsertAtByte = IsLE ? 0 : 12;
1588       return true;
1589     }
1590   }
1591 
1592   return false;
1593 }
1594 
1595 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1596 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1597 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1598                                 SelectionDAG &DAG) {
1599   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1600   assert(isSplatShuffleMask(SVOp, EltSize));
1601   if (DAG.getDataLayout().isLittleEndian())
1602     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1603   else
1604     return SVOp->getMaskElt(0) / EltSize;
1605 }
1606 
1607 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1608 /// by using a vspltis[bhw] instruction of the specified element size, return
1609 /// the constant being splatted.  The ByteSize field indicates the number of
1610 /// bytes of each element [124] -> [bhw].
1611 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1612   SDValue OpVal(nullptr, 0);
1613 
1614   // If ByteSize of the splat is bigger than the element size of the
1615   // build_vector, then we have a case where we are checking for a splat where
1616   // multiple elements of the buildvector are folded together into a single
1617   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1618   unsigned EltSize = 16/N->getNumOperands();
1619   if (EltSize < ByteSize) {
1620     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1621     SDValue UniquedVals[4];
1622     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1623 
1624     // See if all of the elements in the buildvector agree across.
1625     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1626       if (N->getOperand(i).isUndef()) continue;
1627       // If the element isn't a constant, bail fully out.
1628       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1629 
1630 
1631       if (!UniquedVals[i&(Multiple-1)].getNode())
1632         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1633       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1634         return SDValue();  // no match.
1635     }
1636 
1637     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1638     // either constant or undef values that are identical for each chunk.  See
1639     // if these chunks can form into a larger vspltis*.
1640 
1641     // Check to see if all of the leading entries are either 0 or -1.  If
1642     // neither, then this won't fit into the immediate field.
1643     bool LeadingZero = true;
1644     bool LeadingOnes = true;
1645     for (unsigned i = 0; i != Multiple-1; ++i) {
1646       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1647 
1648       LeadingZero &= isNullConstant(UniquedVals[i]);
1649       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1650     }
1651     // Finally, check the least significant entry.
1652     if (LeadingZero) {
1653       if (!UniquedVals[Multiple-1].getNode())
1654         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1655       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1656       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1657         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1658     }
1659     if (LeadingOnes) {
1660       if (!UniquedVals[Multiple-1].getNode())
1661         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1662       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1663       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1664         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1665     }
1666 
1667     return SDValue();
1668   }
1669 
1670   // Check to see if this buildvec has a single non-undef value in its elements.
1671   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1672     if (N->getOperand(i).isUndef()) continue;
1673     if (!OpVal.getNode())
1674       OpVal = N->getOperand(i);
1675     else if (OpVal != N->getOperand(i))
1676       return SDValue();
1677   }
1678 
1679   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1680 
1681   unsigned ValSizeInBytes = EltSize;
1682   uint64_t Value = 0;
1683   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1684     Value = CN->getZExtValue();
1685   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1686     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1687     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1688   }
1689 
1690   // If the splat value is larger than the element value, then we can never do
1691   // this splat.  The only case that we could fit the replicated bits into our
1692   // immediate field for would be zero, and we prefer to use vxor for it.
1693   if (ValSizeInBytes < ByteSize) return SDValue();
1694 
1695   // If the element value is larger than the splat value, check if it consists
1696   // of a repeated bit pattern of size ByteSize.
1697   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1698     return SDValue();
1699 
1700   // Properly sign extend the value.
1701   int MaskVal = SignExtend32(Value, ByteSize * 8);
1702 
1703   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1704   if (MaskVal == 0) return SDValue();
1705 
1706   // Finally, if this value fits in a 5 bit sext field, return it
1707   if (SignExtend32<5>(MaskVal) == MaskVal)
1708     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1709   return SDValue();
1710 }
1711 
1712 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1713 /// amount, otherwise return -1.
1714 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1715   EVT VT = N->getValueType(0);
1716   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1717     return -1;
1718 
1719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1720 
1721   // Find the first non-undef value in the shuffle mask.
1722   unsigned i;
1723   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1724     /*search*/;
1725 
1726   if (i == 4) return -1;  // all undef.
1727 
1728   // Otherwise, check to see if the rest of the elements are consecutively
1729   // numbered from this value.
1730   unsigned ShiftAmt = SVOp->getMaskElt(i);
1731   if (ShiftAmt < i) return -1;
1732   ShiftAmt -= i;
1733 
1734   // Check the rest of the elements to see if they are consecutive.
1735   for (++i; i != 4; ++i)
1736     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1737       return -1;
1738 
1739   return ShiftAmt;
1740 }
1741 
1742 //===----------------------------------------------------------------------===//
1743 //  Addressing Mode Selection
1744 //===----------------------------------------------------------------------===//
1745 
1746 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1747 /// or 64-bit immediate, and if the value can be accurately represented as a
1748 /// sign extension from a 16-bit value.  If so, this returns true and the
1749 /// immediate.
1750 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1751   if (!isa<ConstantSDNode>(N))
1752     return false;
1753 
1754   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1755   if (N->getValueType(0) == MVT::i32)
1756     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1757   else
1758     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1759 }
1760 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1761   return isIntS16Immediate(Op.getNode(), Imm);
1762 }
1763 
1764 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1765 /// can be represented as an indexed [r+r] operation.  Returns false if it
1766 /// can be more efficiently represented with [r+imm].
1767 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1768                                             SDValue &Index,
1769                                             SelectionDAG &DAG) const {
1770   short imm = 0;
1771   if (N.getOpcode() == ISD::ADD) {
1772     if (isIntS16Immediate(N.getOperand(1), imm))
1773       return false;    // r+i
1774     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1775       return false;    // r+i
1776 
1777     Base = N.getOperand(0);
1778     Index = N.getOperand(1);
1779     return true;
1780   } else if (N.getOpcode() == ISD::OR) {
1781     if (isIntS16Immediate(N.getOperand(1), imm))
1782       return false;    // r+i can fold it if we can.
1783 
1784     // If this is an or of disjoint bitfields, we can codegen this as an add
1785     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1786     // disjoint.
1787     APInt LHSKnownZero, LHSKnownOne;
1788     APInt RHSKnownZero, RHSKnownOne;
1789     DAG.computeKnownBits(N.getOperand(0),
1790                          LHSKnownZero, LHSKnownOne);
1791 
1792     if (LHSKnownZero.getBoolValue()) {
1793       DAG.computeKnownBits(N.getOperand(1),
1794                            RHSKnownZero, RHSKnownOne);
1795       // If all of the bits are known zero on the LHS or RHS, the add won't
1796       // carry.
1797       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1798         Base = N.getOperand(0);
1799         Index = N.getOperand(1);
1800         return true;
1801       }
1802     }
1803   }
1804 
1805   return false;
1806 }
1807 
1808 // If we happen to be doing an i64 load or store into a stack slot that has
1809 // less than a 4-byte alignment, then the frame-index elimination may need to
1810 // use an indexed load or store instruction (because the offset may not be a
1811 // multiple of 4). The extra register needed to hold the offset comes from the
1812 // register scavenger, and it is possible that the scavenger will need to use
1813 // an emergency spill slot. As a result, we need to make sure that a spill slot
1814 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1815 // stack slot.
1816 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1817   // FIXME: This does not handle the LWA case.
1818   if (VT != MVT::i64)
1819     return;
1820 
1821   // NOTE: We'll exclude negative FIs here, which come from argument
1822   // lowering, because there are no known test cases triggering this problem
1823   // using packed structures (or similar). We can remove this exclusion if
1824   // we find such a test case. The reason why this is so test-case driven is
1825   // because this entire 'fixup' is only to prevent crashes (from the
1826   // register scavenger) on not-really-valid inputs. For example, if we have:
1827   //   %a = alloca i1
1828   //   %b = bitcast i1* %a to i64*
1829   //   store i64* a, i64 b
1830   // then the store should really be marked as 'align 1', but is not. If it
1831   // were marked as 'align 1' then the indexed form would have been
1832   // instruction-selected initially, and the problem this 'fixup' is preventing
1833   // won't happen regardless.
1834   if (FrameIdx < 0)
1835     return;
1836 
1837   MachineFunction &MF = DAG.getMachineFunction();
1838   MachineFrameInfo &MFI = MF.getFrameInfo();
1839 
1840   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1841   if (Align >= 4)
1842     return;
1843 
1844   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1845   FuncInfo->setHasNonRISpills();
1846 }
1847 
1848 /// Returns true if the address N can be represented by a base register plus
1849 /// a signed 16-bit displacement [r+imm], and if it is not better
1850 /// represented as reg+reg.  If Aligned is true, only accept displacements
1851 /// suitable for STD and friends, i.e. multiples of 4.
1852 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1853                                             SDValue &Base,
1854                                             SelectionDAG &DAG,
1855                                             bool Aligned) const {
1856   // FIXME dl should come from parent load or store, not from address
1857   SDLoc dl(N);
1858   // If this can be more profitably realized as r+r, fail.
1859   if (SelectAddressRegReg(N, Disp, Base, DAG))
1860     return false;
1861 
1862   if (N.getOpcode() == ISD::ADD) {
1863     short imm = 0;
1864     if (isIntS16Immediate(N.getOperand(1), imm) &&
1865         (!Aligned || (imm & 3) == 0)) {
1866       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1867       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1868         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1869         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1870       } else {
1871         Base = N.getOperand(0);
1872       }
1873       return true; // [r+i]
1874     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1875       // Match LOAD (ADD (X, Lo(G))).
1876       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1877              && "Cannot handle constant offsets yet!");
1878       Disp = N.getOperand(1).getOperand(0);  // The global address.
1879       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1880              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1881              Disp.getOpcode() == ISD::TargetConstantPool ||
1882              Disp.getOpcode() == ISD::TargetJumpTable);
1883       Base = N.getOperand(0);
1884       return true;  // [&g+r]
1885     }
1886   } else if (N.getOpcode() == ISD::OR) {
1887     short imm = 0;
1888     if (isIntS16Immediate(N.getOperand(1), imm) &&
1889         (!Aligned || (imm & 3) == 0)) {
1890       // If this is an or of disjoint bitfields, we can codegen this as an add
1891       // (for better address arithmetic) if the LHS and RHS of the OR are
1892       // provably disjoint.
1893       APInt LHSKnownZero, LHSKnownOne;
1894       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1895 
1896       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1897         // If all of the bits are known zero on the LHS or RHS, the add won't
1898         // carry.
1899         if (FrameIndexSDNode *FI =
1900               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1901           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1902           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1903         } else {
1904           Base = N.getOperand(0);
1905         }
1906         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1907         return true;
1908       }
1909     }
1910   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1911     // Loading from a constant address.
1912 
1913     // If this address fits entirely in a 16-bit sext immediate field, codegen
1914     // this as "d, 0"
1915     short Imm;
1916     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1917       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1918       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1919                              CN->getValueType(0));
1920       return true;
1921     }
1922 
1923     // Handle 32-bit sext immediates with LIS + addr mode.
1924     if ((CN->getValueType(0) == MVT::i32 ||
1925          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1926         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1927       int Addr = (int)CN->getZExtValue();
1928 
1929       // Otherwise, break this down into an LIS + disp.
1930       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1931 
1932       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1933                                    MVT::i32);
1934       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1935       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1936       return true;
1937     }
1938   }
1939 
1940   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1941   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1942     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1943     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1944   } else
1945     Base = N;
1946   return true;      // [r+0]
1947 }
1948 
1949 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1950 /// represented as an indexed [r+r] operation.
1951 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1952                                                 SDValue &Index,
1953                                                 SelectionDAG &DAG) const {
1954   // Check to see if we can easily represent this as an [r+r] address.  This
1955   // will fail if it thinks that the address is more profitably represented as
1956   // reg+imm, e.g. where imm = 0.
1957   if (SelectAddressRegReg(N, Base, Index, DAG))
1958     return true;
1959 
1960   // If the operand is an addition, always emit this as [r+r], since this is
1961   // better (for code size, and execution, as the memop does the add for free)
1962   // than emitting an explicit add.
1963   if (N.getOpcode() == ISD::ADD) {
1964     Base = N.getOperand(0);
1965     Index = N.getOperand(1);
1966     return true;
1967   }
1968 
1969   // Otherwise, do it the hard way, using R0 as the base register.
1970   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1971                          N.getValueType());
1972   Index = N;
1973   return true;
1974 }
1975 
1976 /// getPreIndexedAddressParts - returns true by value, base pointer and
1977 /// offset pointer and addressing mode by reference if the node's address
1978 /// can be legally represented as pre-indexed load / store address.
1979 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1980                                                   SDValue &Offset,
1981                                                   ISD::MemIndexedMode &AM,
1982                                                   SelectionDAG &DAG) const {
1983   if (DisablePPCPreinc) return false;
1984 
1985   bool isLoad = true;
1986   SDValue Ptr;
1987   EVT VT;
1988   unsigned Alignment;
1989   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1990     Ptr = LD->getBasePtr();
1991     VT = LD->getMemoryVT();
1992     Alignment = LD->getAlignment();
1993   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1994     Ptr = ST->getBasePtr();
1995     VT  = ST->getMemoryVT();
1996     Alignment = ST->getAlignment();
1997     isLoad = false;
1998   } else
1999     return false;
2000 
2001   // PowerPC doesn't have preinc load/store instructions for vectors (except
2002   // for QPX, which does have preinc r+r forms).
2003   if (VT.isVector()) {
2004     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2005       return false;
2006     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2007       AM = ISD::PRE_INC;
2008       return true;
2009     }
2010   }
2011 
2012   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2013 
2014     // Common code will reject creating a pre-inc form if the base pointer
2015     // is a frame index, or if N is a store and the base pointer is either
2016     // the same as or a predecessor of the value being stored.  Check for
2017     // those situations here, and try with swapped Base/Offset instead.
2018     bool Swap = false;
2019 
2020     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2021       Swap = true;
2022     else if (!isLoad) {
2023       SDValue Val = cast<StoreSDNode>(N)->getValue();
2024       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2025         Swap = true;
2026     }
2027 
2028     if (Swap)
2029       std::swap(Base, Offset);
2030 
2031     AM = ISD::PRE_INC;
2032     return true;
2033   }
2034 
2035   // LDU/STU can only handle immediates that are a multiple of 4.
2036   if (VT != MVT::i64) {
2037     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2038       return false;
2039   } else {
2040     // LDU/STU need an address with at least 4-byte alignment.
2041     if (Alignment < 4)
2042       return false;
2043 
2044     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2045       return false;
2046   }
2047 
2048   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2049     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2050     // sext i32 to i64 when addr mode is r+i.
2051     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2052         LD->getExtensionType() == ISD::SEXTLOAD &&
2053         isa<ConstantSDNode>(Offset))
2054       return false;
2055   }
2056 
2057   AM = ISD::PRE_INC;
2058   return true;
2059 }
2060 
2061 //===----------------------------------------------------------------------===//
2062 //  LowerOperation implementation
2063 //===----------------------------------------------------------------------===//
2064 
2065 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2066 /// and LoOpFlags to the target MO flags.
2067 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2068                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2069                                const GlobalValue *GV = nullptr) {
2070   HiOpFlags = PPCII::MO_HA;
2071   LoOpFlags = PPCII::MO_LO;
2072 
2073   // Don't use the pic base if not in PIC relocation model.
2074   if (IsPIC) {
2075     HiOpFlags |= PPCII::MO_PIC_FLAG;
2076     LoOpFlags |= PPCII::MO_PIC_FLAG;
2077   }
2078 
2079   // If this is a reference to a global value that requires a non-lazy-ptr, make
2080   // sure that instruction lowering adds it.
2081   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2082     HiOpFlags |= PPCII::MO_NLP_FLAG;
2083     LoOpFlags |= PPCII::MO_NLP_FLAG;
2084 
2085     if (GV->hasHiddenVisibility()) {
2086       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2087       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2088     }
2089   }
2090 }
2091 
2092 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2093                              SelectionDAG &DAG) {
2094   SDLoc DL(HiPart);
2095   EVT PtrVT = HiPart.getValueType();
2096   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2097 
2098   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2099   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2100 
2101   // With PIC, the first instruction is actually "GR+hi(&G)".
2102   if (isPIC)
2103     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2104                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2105 
2106   // Generate non-pic code that has direct accesses to the constant pool.
2107   // The address of the global is just (hi(&g)+lo(&g)).
2108   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2109 }
2110 
2111 static void setUsesTOCBasePtr(MachineFunction &MF) {
2112   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2113   FuncInfo->setUsesTOCBasePtr();
2114 }
2115 
2116 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2117   setUsesTOCBasePtr(DAG.getMachineFunction());
2118 }
2119 
2120 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2121                            SDValue GA) {
2122   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2123   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2124                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2125 
2126   SDValue Ops[] = { GA, Reg };
2127   return DAG.getMemIntrinsicNode(
2128       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2129       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2130       false, 0);
2131 }
2132 
2133 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2134                                              SelectionDAG &DAG) const {
2135   EVT PtrVT = Op.getValueType();
2136   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2137   const Constant *C = CP->getConstVal();
2138 
2139   // 64-bit SVR4 ABI code is always position-independent.
2140   // The actual address of the GlobalValue is stored in the TOC.
2141   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2142     setUsesTOCBasePtr(DAG);
2143     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2144     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2145   }
2146 
2147   unsigned MOHiFlag, MOLoFlag;
2148   bool IsPIC = isPositionIndependent();
2149   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2150 
2151   if (IsPIC && Subtarget.isSVR4ABI()) {
2152     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2153                                            PPCII::MO_PIC_FLAG);
2154     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2155   }
2156 
2157   SDValue CPIHi =
2158     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2159   SDValue CPILo =
2160     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2161   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2162 }
2163 
2164 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2165   EVT PtrVT = Op.getValueType();
2166   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2167 
2168   // 64-bit SVR4 ABI code is always position-independent.
2169   // The actual address of the GlobalValue is stored in the TOC.
2170   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2171     setUsesTOCBasePtr(DAG);
2172     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2173     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2174   }
2175 
2176   unsigned MOHiFlag, MOLoFlag;
2177   bool IsPIC = isPositionIndependent();
2178   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2179 
2180   if (IsPIC && Subtarget.isSVR4ABI()) {
2181     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2182                                         PPCII::MO_PIC_FLAG);
2183     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2184   }
2185 
2186   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2187   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2188   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2189 }
2190 
2191 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2192                                              SelectionDAG &DAG) const {
2193   EVT PtrVT = Op.getValueType();
2194   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2195   const BlockAddress *BA = BASDN->getBlockAddress();
2196 
2197   // 64-bit SVR4 ABI code is always position-independent.
2198   // The actual BlockAddress is stored in the TOC.
2199   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2200     setUsesTOCBasePtr(DAG);
2201     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2202     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2203   }
2204 
2205   unsigned MOHiFlag, MOLoFlag;
2206   bool IsPIC = isPositionIndependent();
2207   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2208   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2209   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2210   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2211 }
2212 
2213 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2214                                               SelectionDAG &DAG) const {
2215 
2216   // FIXME: TLS addresses currently use medium model code sequences,
2217   // which is the most useful form.  Eventually support for small and
2218   // large models could be added if users need it, at the cost of
2219   // additional complexity.
2220   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2221   if (DAG.getTarget().Options.EmulatedTLS)
2222     return LowerToTLSEmulatedModel(GA, DAG);
2223 
2224   SDLoc dl(GA);
2225   const GlobalValue *GV = GA->getGlobal();
2226   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2227   bool is64bit = Subtarget.isPPC64();
2228   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2229   PICLevel::Level picLevel = M->getPICLevel();
2230 
2231   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2232 
2233   if (Model == TLSModel::LocalExec) {
2234     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2235                                                PPCII::MO_TPREL_HA);
2236     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2237                                                PPCII::MO_TPREL_LO);
2238     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2239                                      is64bit ? MVT::i64 : MVT::i32);
2240     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2241     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2242   }
2243 
2244   if (Model == TLSModel::InitialExec) {
2245     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2246     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2247                                                 PPCII::MO_TLS);
2248     SDValue GOTPtr;
2249     if (is64bit) {
2250       setUsesTOCBasePtr(DAG);
2251       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2252       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2253                            PtrVT, GOTReg, TGA);
2254     } else
2255       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2256     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2257                                    PtrVT, TGA, GOTPtr);
2258     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2259   }
2260 
2261   if (Model == TLSModel::GeneralDynamic) {
2262     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2263     SDValue GOTPtr;
2264     if (is64bit) {
2265       setUsesTOCBasePtr(DAG);
2266       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2267       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2268                                    GOTReg, TGA);
2269     } else {
2270       if (picLevel == PICLevel::SmallPIC)
2271         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2272       else
2273         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2274     }
2275     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2276                        GOTPtr, TGA, TGA);
2277   }
2278 
2279   if (Model == TLSModel::LocalDynamic) {
2280     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2281     SDValue GOTPtr;
2282     if (is64bit) {
2283       setUsesTOCBasePtr(DAG);
2284       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2285       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2286                            GOTReg, TGA);
2287     } else {
2288       if (picLevel == PICLevel::SmallPIC)
2289         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2290       else
2291         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2292     }
2293     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2294                                   PtrVT, GOTPtr, TGA, TGA);
2295     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2296                                       PtrVT, TLSAddr, TGA);
2297     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2298   }
2299 
2300   llvm_unreachable("Unknown TLS model!");
2301 }
2302 
2303 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2304                                               SelectionDAG &DAG) const {
2305   EVT PtrVT = Op.getValueType();
2306   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2307   SDLoc DL(GSDN);
2308   const GlobalValue *GV = GSDN->getGlobal();
2309 
2310   // 64-bit SVR4 ABI code is always position-independent.
2311   // The actual address of the GlobalValue is stored in the TOC.
2312   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2313     setUsesTOCBasePtr(DAG);
2314     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2315     return getTOCEntry(DAG, DL, true, GA);
2316   }
2317 
2318   unsigned MOHiFlag, MOLoFlag;
2319   bool IsPIC = isPositionIndependent();
2320   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2321 
2322   if (IsPIC && Subtarget.isSVR4ABI()) {
2323     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2324                                             GSDN->getOffset(),
2325                                             PPCII::MO_PIC_FLAG);
2326     return getTOCEntry(DAG, DL, false, GA);
2327   }
2328 
2329   SDValue GAHi =
2330     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2331   SDValue GALo =
2332     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2333 
2334   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2335 
2336   // If the global reference is actually to a non-lazy-pointer, we have to do an
2337   // extra load to get the address of the global.
2338   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2339     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2340   return Ptr;
2341 }
2342 
2343 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2344   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2345   SDLoc dl(Op);
2346 
2347   if (Op.getValueType() == MVT::v2i64) {
2348     // When the operands themselves are v2i64 values, we need to do something
2349     // special because VSX has no underlying comparison operations for these.
2350     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2351       // Equality can be handled by casting to the legal type for Altivec
2352       // comparisons, everything else needs to be expanded.
2353       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2354         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2355                  DAG.getSetCC(dl, MVT::v4i32,
2356                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2357                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2358                    CC));
2359       }
2360 
2361       return SDValue();
2362     }
2363 
2364     // We handle most of these in the usual way.
2365     return Op;
2366   }
2367 
2368   // If we're comparing for equality to zero, expose the fact that this is
2369   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2370   // fold the new nodes.
2371   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2372     return V;
2373 
2374   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2375     // Leave comparisons against 0 and -1 alone for now, since they're usually
2376     // optimized.  FIXME: revisit this when we can custom lower all setcc
2377     // optimizations.
2378     if (C->isAllOnesValue() || C->isNullValue())
2379       return SDValue();
2380   }
2381 
2382   // If we have an integer seteq/setne, turn it into a compare against zero
2383   // by xor'ing the rhs with the lhs, which is faster than setting a
2384   // condition register, reading it back out, and masking the correct bit.  The
2385   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2386   // the result to other bit-twiddling opportunities.
2387   EVT LHSVT = Op.getOperand(0).getValueType();
2388   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2389     EVT VT = Op.getValueType();
2390     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2391                                 Op.getOperand(1));
2392     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2393   }
2394   return SDValue();
2395 }
2396 
2397 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2398   SDNode *Node = Op.getNode();
2399   EVT VT = Node->getValueType(0);
2400   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2401   SDValue InChain = Node->getOperand(0);
2402   SDValue VAListPtr = Node->getOperand(1);
2403   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2404   SDLoc dl(Node);
2405 
2406   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2407 
2408   // gpr_index
2409   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2410                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2411   InChain = GprIndex.getValue(1);
2412 
2413   if (VT == MVT::i64) {
2414     // Check if GprIndex is even
2415     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2416                                  DAG.getConstant(1, dl, MVT::i32));
2417     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2418                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2419     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2420                                           DAG.getConstant(1, dl, MVT::i32));
2421     // Align GprIndex to be even if it isn't
2422     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2423                            GprIndex);
2424   }
2425 
2426   // fpr index is 1 byte after gpr
2427   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2428                                DAG.getConstant(1, dl, MVT::i32));
2429 
2430   // fpr
2431   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2432                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2433   InChain = FprIndex.getValue(1);
2434 
2435   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2436                                        DAG.getConstant(8, dl, MVT::i32));
2437 
2438   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2439                                         DAG.getConstant(4, dl, MVT::i32));
2440 
2441   // areas
2442   SDValue OverflowArea =
2443       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2444   InChain = OverflowArea.getValue(1);
2445 
2446   SDValue RegSaveArea =
2447       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2448   InChain = RegSaveArea.getValue(1);
2449 
2450   // select overflow_area if index > 8
2451   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2452                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2453 
2454   // adjustment constant gpr_index * 4/8
2455   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2456                                     VT.isInteger() ? GprIndex : FprIndex,
2457                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2458                                                     MVT::i32));
2459 
2460   // OurReg = RegSaveArea + RegConstant
2461   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2462                                RegConstant);
2463 
2464   // Floating types are 32 bytes into RegSaveArea
2465   if (VT.isFloatingPoint())
2466     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2467                          DAG.getConstant(32, dl, MVT::i32));
2468 
2469   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2470   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2471                                    VT.isInteger() ? GprIndex : FprIndex,
2472                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2473                                                    MVT::i32));
2474 
2475   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2476                               VT.isInteger() ? VAListPtr : FprPtr,
2477                               MachinePointerInfo(SV), MVT::i8);
2478 
2479   // determine if we should load from reg_save_area or overflow_area
2480   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2481 
2482   // increase overflow_area by 4/8 if gpr/fpr > 8
2483   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2484                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2485                                           dl, MVT::i32));
2486 
2487   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2488                              OverflowAreaPlusN);
2489 
2490   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2491                               MachinePointerInfo(), MVT::i32);
2492 
2493   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2494 }
2495 
2496 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2497   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2498 
2499   // We have to copy the entire va_list struct:
2500   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2501   return DAG.getMemcpy(Op.getOperand(0), Op,
2502                        Op.getOperand(1), Op.getOperand(2),
2503                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2504                        false, MachinePointerInfo(), MachinePointerInfo());
2505 }
2506 
2507 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2508                                                   SelectionDAG &DAG) const {
2509   return Op.getOperand(0);
2510 }
2511 
2512 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2513                                                 SelectionDAG &DAG) const {
2514   SDValue Chain = Op.getOperand(0);
2515   SDValue Trmp = Op.getOperand(1); // trampoline
2516   SDValue FPtr = Op.getOperand(2); // nested function
2517   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2518   SDLoc dl(Op);
2519 
2520   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2521   bool isPPC64 = (PtrVT == MVT::i64);
2522   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2523 
2524   TargetLowering::ArgListTy Args;
2525   TargetLowering::ArgListEntry Entry;
2526 
2527   Entry.Ty = IntPtrTy;
2528   Entry.Node = Trmp; Args.push_back(Entry);
2529 
2530   // TrampSize == (isPPC64 ? 48 : 40);
2531   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2532                                isPPC64 ? MVT::i64 : MVT::i32);
2533   Args.push_back(Entry);
2534 
2535   Entry.Node = FPtr; Args.push_back(Entry);
2536   Entry.Node = Nest; Args.push_back(Entry);
2537 
2538   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2539   TargetLowering::CallLoweringInfo CLI(DAG);
2540   CLI.setDebugLoc(dl).setChain(Chain)
2541     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2542                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2543                std::move(Args));
2544 
2545   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2546   return CallResult.second;
2547 }
2548 
2549 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2550   MachineFunction &MF = DAG.getMachineFunction();
2551   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2552   EVT PtrVT = getPointerTy(MF.getDataLayout());
2553 
2554   SDLoc dl(Op);
2555 
2556   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2557     // vastart just stores the address of the VarArgsFrameIndex slot into the
2558     // memory location argument.
2559     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2560     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2561     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2562                         MachinePointerInfo(SV));
2563   }
2564 
2565   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2566   // We suppose the given va_list is already allocated.
2567   //
2568   // typedef struct {
2569   //  char gpr;     /* index into the array of 8 GPRs
2570   //                 * stored in the register save area
2571   //                 * gpr=0 corresponds to r3,
2572   //                 * gpr=1 to r4, etc.
2573   //                 */
2574   //  char fpr;     /* index into the array of 8 FPRs
2575   //                 * stored in the register save area
2576   //                 * fpr=0 corresponds to f1,
2577   //                 * fpr=1 to f2, etc.
2578   //                 */
2579   //  char *overflow_arg_area;
2580   //                /* location on stack that holds
2581   //                 * the next overflow argument
2582   //                 */
2583   //  char *reg_save_area;
2584   //               /* where r3:r10 and f1:f8 (if saved)
2585   //                * are stored
2586   //                */
2587   // } va_list[1];
2588 
2589   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2590   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2591   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2592                                             PtrVT);
2593   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2594                                  PtrVT);
2595 
2596   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2597   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2598 
2599   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2600   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2601 
2602   uint64_t FPROffset = 1;
2603   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2604 
2605   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2606 
2607   // Store first byte : number of int regs
2608   SDValue firstStore =
2609       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2610                         MachinePointerInfo(SV), MVT::i8);
2611   uint64_t nextOffset = FPROffset;
2612   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2613                                   ConstFPROffset);
2614 
2615   // Store second byte : number of float regs
2616   SDValue secondStore =
2617       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2618                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2619   nextOffset += StackOffset;
2620   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2621 
2622   // Store second word : arguments given on stack
2623   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2624                                     MachinePointerInfo(SV, nextOffset));
2625   nextOffset += FrameOffset;
2626   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2627 
2628   // Store third word : arguments given in registers
2629   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2630                       MachinePointerInfo(SV, nextOffset));
2631 }
2632 
2633 #include "PPCGenCallingConv.inc"
2634 
2635 // Function whose sole purpose is to kill compiler warnings
2636 // stemming from unused functions included from PPCGenCallingConv.inc.
2637 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2638   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2639 }
2640 
2641 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2642                                       CCValAssign::LocInfo &LocInfo,
2643                                       ISD::ArgFlagsTy &ArgFlags,
2644                                       CCState &State) {
2645   return true;
2646 }
2647 
2648 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2649                                              MVT &LocVT,
2650                                              CCValAssign::LocInfo &LocInfo,
2651                                              ISD::ArgFlagsTy &ArgFlags,
2652                                              CCState &State) {
2653   static const MCPhysReg ArgRegs[] = {
2654     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2655     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2656   };
2657   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2658 
2659   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2660 
2661   // Skip one register if the first unallocated register has an even register
2662   // number and there are still argument registers available which have not been
2663   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2664   // need to skip a register if RegNum is odd.
2665   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2666     State.AllocateReg(ArgRegs[RegNum]);
2667   }
2668 
2669   // Always return false here, as this function only makes sure that the first
2670   // unallocated register has an odd register number and does not actually
2671   // allocate a register for the current argument.
2672   return false;
2673 }
2674 
2675 bool
2676 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2677                                                   MVT &LocVT,
2678                                                   CCValAssign::LocInfo &LocInfo,
2679                                                   ISD::ArgFlagsTy &ArgFlags,
2680                                                   CCState &State) {
2681   static const MCPhysReg ArgRegs[] = {
2682     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2683     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2684   };
2685   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2686 
2687   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2688   int RegsLeft = NumArgRegs - RegNum;
2689 
2690   // Skip if there is not enough registers left for long double type (4 gpr regs
2691   // in soft float mode) and put long double argument on the stack.
2692   if (RegNum != NumArgRegs && RegsLeft < 4) {
2693     for (int i = 0; i < RegsLeft; i++) {
2694       State.AllocateReg(ArgRegs[RegNum + i]);
2695     }
2696   }
2697 
2698   return false;
2699 }
2700 
2701 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2702                                                MVT &LocVT,
2703                                                CCValAssign::LocInfo &LocInfo,
2704                                                ISD::ArgFlagsTy &ArgFlags,
2705                                                CCState &State) {
2706   static const MCPhysReg ArgRegs[] = {
2707     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2708     PPC::F8
2709   };
2710 
2711   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2712 
2713   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2714 
2715   // If there is only one Floating-point register left we need to put both f64
2716   // values of a split ppc_fp128 value on the stack.
2717   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2718     State.AllocateReg(ArgRegs[RegNum]);
2719   }
2720 
2721   // Always return false here, as this function only makes sure that the two f64
2722   // values a ppc_fp128 value is split into are both passed in registers or both
2723   // passed on the stack and does not actually allocate a register for the
2724   // current argument.
2725   return false;
2726 }
2727 
2728 /// FPR - The set of FP registers that should be allocated for arguments,
2729 /// on Darwin.
2730 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2731                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2732                                 PPC::F11, PPC::F12, PPC::F13};
2733 
2734 /// QFPR - The set of QPX registers that should be allocated for arguments.
2735 static const MCPhysReg QFPR[] = {
2736     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2737     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2738 
2739 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2740 /// the stack.
2741 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2742                                        unsigned PtrByteSize) {
2743   unsigned ArgSize = ArgVT.getStoreSize();
2744   if (Flags.isByVal())
2745     ArgSize = Flags.getByValSize();
2746 
2747   // Round up to multiples of the pointer size, except for array members,
2748   // which are always packed.
2749   if (!Flags.isInConsecutiveRegs())
2750     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2751 
2752   return ArgSize;
2753 }
2754 
2755 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2756 /// on the stack.
2757 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2758                                             ISD::ArgFlagsTy Flags,
2759                                             unsigned PtrByteSize) {
2760   unsigned Align = PtrByteSize;
2761 
2762   // Altivec parameters are padded to a 16 byte boundary.
2763   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2764       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2765       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2766       ArgVT == MVT::v1i128)
2767     Align = 16;
2768   // QPX vector types stored in double-precision are padded to a 32 byte
2769   // boundary.
2770   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2771     Align = 32;
2772 
2773   // ByVal parameters are aligned as requested.
2774   if (Flags.isByVal()) {
2775     unsigned BVAlign = Flags.getByValAlign();
2776     if (BVAlign > PtrByteSize) {
2777       if (BVAlign % PtrByteSize != 0)
2778           llvm_unreachable(
2779             "ByVal alignment is not a multiple of the pointer size");
2780 
2781       Align = BVAlign;
2782     }
2783   }
2784 
2785   // Array members are always packed to their original alignment.
2786   if (Flags.isInConsecutiveRegs()) {
2787     // If the array member was split into multiple registers, the first
2788     // needs to be aligned to the size of the full type.  (Except for
2789     // ppcf128, which is only aligned as its f64 components.)
2790     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2791       Align = OrigVT.getStoreSize();
2792     else
2793       Align = ArgVT.getStoreSize();
2794   }
2795 
2796   return Align;
2797 }
2798 
2799 /// CalculateStackSlotUsed - Return whether this argument will use its
2800 /// stack slot (instead of being passed in registers).  ArgOffset,
2801 /// AvailableFPRs, and AvailableVRs must hold the current argument
2802 /// position, and will be updated to account for this argument.
2803 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2804                                    ISD::ArgFlagsTy Flags,
2805                                    unsigned PtrByteSize,
2806                                    unsigned LinkageSize,
2807                                    unsigned ParamAreaSize,
2808                                    unsigned &ArgOffset,
2809                                    unsigned &AvailableFPRs,
2810                                    unsigned &AvailableVRs, bool HasQPX) {
2811   bool UseMemory = false;
2812 
2813   // Respect alignment of argument on the stack.
2814   unsigned Align =
2815     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2816   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2817   // If there's no space left in the argument save area, we must
2818   // use memory (this check also catches zero-sized arguments).
2819   if (ArgOffset >= LinkageSize + ParamAreaSize)
2820     UseMemory = true;
2821 
2822   // Allocate argument on the stack.
2823   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2824   if (Flags.isInConsecutiveRegsLast())
2825     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2826   // If we overran the argument save area, we must use memory
2827   // (this check catches arguments passed partially in memory)
2828   if (ArgOffset > LinkageSize + ParamAreaSize)
2829     UseMemory = true;
2830 
2831   // However, if the argument is actually passed in an FPR or a VR,
2832   // we don't use memory after all.
2833   if (!Flags.isByVal()) {
2834     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2835         // QPX registers overlap with the scalar FP registers.
2836         (HasQPX && (ArgVT == MVT::v4f32 ||
2837                     ArgVT == MVT::v4f64 ||
2838                     ArgVT == MVT::v4i1)))
2839       if (AvailableFPRs > 0) {
2840         --AvailableFPRs;
2841         return false;
2842       }
2843     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2844         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2845         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2846         ArgVT == MVT::v1i128)
2847       if (AvailableVRs > 0) {
2848         --AvailableVRs;
2849         return false;
2850       }
2851   }
2852 
2853   return UseMemory;
2854 }
2855 
2856 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2857 /// ensure minimum alignment required for target.
2858 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2859                                      unsigned NumBytes) {
2860   unsigned TargetAlign = Lowering->getStackAlignment();
2861   unsigned AlignMask = TargetAlign - 1;
2862   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2863   return NumBytes;
2864 }
2865 
2866 SDValue PPCTargetLowering::LowerFormalArguments(
2867     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2868     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2869     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2870   if (Subtarget.isSVR4ABI()) {
2871     if (Subtarget.isPPC64())
2872       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2873                                          dl, DAG, InVals);
2874     else
2875       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2876                                          dl, DAG, InVals);
2877   } else {
2878     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2879                                        dl, DAG, InVals);
2880   }
2881 }
2882 
2883 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2884     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2885     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2886     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2887 
2888   // 32-bit SVR4 ABI Stack Frame Layout:
2889   //              +-----------------------------------+
2890   //        +-->  |            Back chain             |
2891   //        |     +-----------------------------------+
2892   //        |     | Floating-point register save area |
2893   //        |     +-----------------------------------+
2894   //        |     |    General register save area     |
2895   //        |     +-----------------------------------+
2896   //        |     |          CR save word             |
2897   //        |     +-----------------------------------+
2898   //        |     |         VRSAVE save word          |
2899   //        |     +-----------------------------------+
2900   //        |     |         Alignment padding         |
2901   //        |     +-----------------------------------+
2902   //        |     |     Vector register save area     |
2903   //        |     +-----------------------------------+
2904   //        |     |       Local variable space        |
2905   //        |     +-----------------------------------+
2906   //        |     |        Parameter list area        |
2907   //        |     +-----------------------------------+
2908   //        |     |           LR save word            |
2909   //        |     +-----------------------------------+
2910   // SP-->  +---  |            Back chain             |
2911   //              +-----------------------------------+
2912   //
2913   // Specifications:
2914   //   System V Application Binary Interface PowerPC Processor Supplement
2915   //   AltiVec Technology Programming Interface Manual
2916 
2917   MachineFunction &MF = DAG.getMachineFunction();
2918   MachineFrameInfo &MFI = MF.getFrameInfo();
2919   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2920 
2921   EVT PtrVT = getPointerTy(MF.getDataLayout());
2922   // Potential tail calls could cause overwriting of argument stack slots.
2923   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2924                        (CallConv == CallingConv::Fast));
2925   unsigned PtrByteSize = 4;
2926 
2927   // Assign locations to all of the incoming arguments.
2928   SmallVector<CCValAssign, 16> ArgLocs;
2929   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2930                  *DAG.getContext());
2931 
2932   // Reserve space for the linkage area on the stack.
2933   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2934   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2935   if (useSoftFloat())
2936     CCInfo.PreAnalyzeFormalArguments(Ins);
2937 
2938   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2939   CCInfo.clearWasPPCF128();
2940 
2941   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2942     CCValAssign &VA = ArgLocs[i];
2943 
2944     // Arguments stored in registers.
2945     if (VA.isRegLoc()) {
2946       const TargetRegisterClass *RC;
2947       EVT ValVT = VA.getValVT();
2948 
2949       switch (ValVT.getSimpleVT().SimpleTy) {
2950         default:
2951           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2952         case MVT::i1:
2953         case MVT::i32:
2954           RC = &PPC::GPRCRegClass;
2955           break;
2956         case MVT::f32:
2957           if (Subtarget.hasP8Vector())
2958             RC = &PPC::VSSRCRegClass;
2959           else
2960             RC = &PPC::F4RCRegClass;
2961           break;
2962         case MVT::f64:
2963           if (Subtarget.hasVSX())
2964             RC = &PPC::VSFRCRegClass;
2965           else
2966             RC = &PPC::F8RCRegClass;
2967           break;
2968         case MVT::v16i8:
2969         case MVT::v8i16:
2970         case MVT::v4i32:
2971           RC = &PPC::VRRCRegClass;
2972           break;
2973         case MVT::v4f32:
2974           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2975           break;
2976         case MVT::v2f64:
2977         case MVT::v2i64:
2978           RC = &PPC::VSHRCRegClass;
2979           break;
2980         case MVT::v4f64:
2981           RC = &PPC::QFRCRegClass;
2982           break;
2983         case MVT::v4i1:
2984           RC = &PPC::QBRCRegClass;
2985           break;
2986       }
2987 
2988       // Transform the arguments stored in physical registers into virtual ones.
2989       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2990       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2991                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2992 
2993       if (ValVT == MVT::i1)
2994         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2995 
2996       InVals.push_back(ArgValue);
2997     } else {
2998       // Argument stored in memory.
2999       assert(VA.isMemLoc());
3000 
3001       unsigned ArgSize = VA.getLocVT().getStoreSize();
3002       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3003                                      isImmutable);
3004 
3005       // Create load nodes to retrieve arguments from the stack.
3006       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3007       InVals.push_back(
3008           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3009     }
3010   }
3011 
3012   // Assign locations to all of the incoming aggregate by value arguments.
3013   // Aggregates passed by value are stored in the local variable space of the
3014   // caller's stack frame, right above the parameter list area.
3015   SmallVector<CCValAssign, 16> ByValArgLocs;
3016   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3017                       ByValArgLocs, *DAG.getContext());
3018 
3019   // Reserve stack space for the allocations in CCInfo.
3020   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3021 
3022   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3023 
3024   // Area that is at least reserved in the caller of this function.
3025   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3026   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3027 
3028   // Set the size that is at least reserved in caller of this function.  Tail
3029   // call optimized function's reserved stack space needs to be aligned so that
3030   // taking the difference between two stack areas will result in an aligned
3031   // stack.
3032   MinReservedArea =
3033       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3034   FuncInfo->setMinReservedArea(MinReservedArea);
3035 
3036   SmallVector<SDValue, 8> MemOps;
3037 
3038   // If the function takes variable number of arguments, make a frame index for
3039   // the start of the first vararg value... for expansion of llvm.va_start.
3040   if (isVarArg) {
3041     static const MCPhysReg GPArgRegs[] = {
3042       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3043       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3044     };
3045     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3046 
3047     static const MCPhysReg FPArgRegs[] = {
3048       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3049       PPC::F8
3050     };
3051     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3052 
3053     if (useSoftFloat())
3054        NumFPArgRegs = 0;
3055 
3056     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3057     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3058 
3059     // Make room for NumGPArgRegs and NumFPArgRegs.
3060     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3061                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3062 
3063     FuncInfo->setVarArgsStackOffset(
3064       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3065                             CCInfo.getNextStackOffset(), true));
3066 
3067     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3068     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3069 
3070     // The fixed integer arguments of a variadic function are stored to the
3071     // VarArgsFrameIndex on the stack so that they may be loaded by
3072     // dereferencing the result of va_next.
3073     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3074       // Get an existing live-in vreg, or add a new one.
3075       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3076       if (!VReg)
3077         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3078 
3079       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3080       SDValue Store =
3081           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3082       MemOps.push_back(Store);
3083       // Increment the address by four for the next argument to store
3084       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3085       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3086     }
3087 
3088     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3089     // is set.
3090     // The double arguments are stored to the VarArgsFrameIndex
3091     // on the stack.
3092     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3093       // Get an existing live-in vreg, or add a new one.
3094       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3095       if (!VReg)
3096         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3097 
3098       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3099       SDValue Store =
3100           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3101       MemOps.push_back(Store);
3102       // Increment the address by eight for the next argument to store
3103       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3104                                          PtrVT);
3105       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3106     }
3107   }
3108 
3109   if (!MemOps.empty())
3110     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3111 
3112   return Chain;
3113 }
3114 
3115 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3116 // value to MVT::i64 and then truncate to the correct register size.
3117 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3118                                              EVT ObjectVT, SelectionDAG &DAG,
3119                                              SDValue ArgVal,
3120                                              const SDLoc &dl) const {
3121   if (Flags.isSExt())
3122     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3123                          DAG.getValueType(ObjectVT));
3124   else if (Flags.isZExt())
3125     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3126                          DAG.getValueType(ObjectVT));
3127 
3128   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3129 }
3130 
3131 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3132     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3133     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3134     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3135   // TODO: add description of PPC stack frame format, or at least some docs.
3136   //
3137   bool isELFv2ABI = Subtarget.isELFv2ABI();
3138   bool isLittleEndian = Subtarget.isLittleEndian();
3139   MachineFunction &MF = DAG.getMachineFunction();
3140   MachineFrameInfo &MFI = MF.getFrameInfo();
3141   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3142 
3143   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3144          "fastcc not supported on varargs functions");
3145 
3146   EVT PtrVT = getPointerTy(MF.getDataLayout());
3147   // Potential tail calls could cause overwriting of argument stack slots.
3148   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3149                        (CallConv == CallingConv::Fast));
3150   unsigned PtrByteSize = 8;
3151   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3152 
3153   static const MCPhysReg GPR[] = {
3154     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3155     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3156   };
3157   static const MCPhysReg VR[] = {
3158     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3159     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3160   };
3161   static const MCPhysReg VSRH[] = {
3162     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3163     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3164   };
3165 
3166   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3167   const unsigned Num_FPR_Regs = 13;
3168   const unsigned Num_VR_Regs  = array_lengthof(VR);
3169   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3170 
3171   // Do a first pass over the arguments to determine whether the ABI
3172   // guarantees that our caller has allocated the parameter save area
3173   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3174   // in the ELFv2 ABI, it is true if this is a vararg function or if
3175   // any parameter is located in a stack slot.
3176 
3177   bool HasParameterArea = !isELFv2ABI || isVarArg;
3178   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3179   unsigned NumBytes = LinkageSize;
3180   unsigned AvailableFPRs = Num_FPR_Regs;
3181   unsigned AvailableVRs = Num_VR_Regs;
3182   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3183     if (Ins[i].Flags.isNest())
3184       continue;
3185 
3186     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3187                                PtrByteSize, LinkageSize, ParamAreaSize,
3188                                NumBytes, AvailableFPRs, AvailableVRs,
3189                                Subtarget.hasQPX()))
3190       HasParameterArea = true;
3191   }
3192 
3193   // Add DAG nodes to load the arguments or copy them out of registers.  On
3194   // entry to a function on PPC, the arguments start after the linkage area,
3195   // although the first ones are often in registers.
3196 
3197   unsigned ArgOffset = LinkageSize;
3198   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3199   unsigned &QFPR_idx = FPR_idx;
3200   SmallVector<SDValue, 8> MemOps;
3201   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3202   unsigned CurArgIdx = 0;
3203   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3204     SDValue ArgVal;
3205     bool needsLoad = false;
3206     EVT ObjectVT = Ins[ArgNo].VT;
3207     EVT OrigVT = Ins[ArgNo].ArgVT;
3208     unsigned ObjSize = ObjectVT.getStoreSize();
3209     unsigned ArgSize = ObjSize;
3210     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3211     if (Ins[ArgNo].isOrigArg()) {
3212       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3213       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3214     }
3215     // We re-align the argument offset for each argument, except when using the
3216     // fast calling convention, when we need to make sure we do that only when
3217     // we'll actually use a stack slot.
3218     unsigned CurArgOffset, Align;
3219     auto ComputeArgOffset = [&]() {
3220       /* Respect alignment of argument on the stack.  */
3221       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3222       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3223       CurArgOffset = ArgOffset;
3224     };
3225 
3226     if (CallConv != CallingConv::Fast) {
3227       ComputeArgOffset();
3228 
3229       /* Compute GPR index associated with argument offset.  */
3230       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3231       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3232     }
3233 
3234     // FIXME the codegen can be much improved in some cases.
3235     // We do not have to keep everything in memory.
3236     if (Flags.isByVal()) {
3237       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3238 
3239       if (CallConv == CallingConv::Fast)
3240         ComputeArgOffset();
3241 
3242       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3243       ObjSize = Flags.getByValSize();
3244       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3245       // Empty aggregate parameters do not take up registers.  Examples:
3246       //   struct { } a;
3247       //   union  { } b;
3248       //   int c[0];
3249       // etc.  However, we have to provide a place-holder in InVals, so
3250       // pretend we have an 8-byte item at the current address for that
3251       // purpose.
3252       if (!ObjSize) {
3253         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3254         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3255         InVals.push_back(FIN);
3256         continue;
3257       }
3258 
3259       // Create a stack object covering all stack doublewords occupied
3260       // by the argument.  If the argument is (fully or partially) on
3261       // the stack, or if the argument is fully in registers but the
3262       // caller has allocated the parameter save anyway, we can refer
3263       // directly to the caller's stack frame.  Otherwise, create a
3264       // local copy in our own frame.
3265       int FI;
3266       if (HasParameterArea ||
3267           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3268         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3269       else
3270         FI = MFI.CreateStackObject(ArgSize, Align, false);
3271       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3272 
3273       // Handle aggregates smaller than 8 bytes.
3274       if (ObjSize < PtrByteSize) {
3275         // The value of the object is its address, which differs from the
3276         // address of the enclosing doubleword on big-endian systems.
3277         SDValue Arg = FIN;
3278         if (!isLittleEndian) {
3279           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3280           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3281         }
3282         InVals.push_back(Arg);
3283 
3284         if (GPR_idx != Num_GPR_Regs) {
3285           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3286           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3287           SDValue Store;
3288 
3289           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3290             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3291                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3292             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3293                                       MachinePointerInfo(&*FuncArg), ObjType);
3294           } else {
3295             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3296             // store the whole register as-is to the parameter save area
3297             // slot.
3298             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3299                                  MachinePointerInfo(&*FuncArg));
3300           }
3301 
3302           MemOps.push_back(Store);
3303         }
3304         // Whether we copied from a register or not, advance the offset
3305         // into the parameter save area by a full doubleword.
3306         ArgOffset += PtrByteSize;
3307         continue;
3308       }
3309 
3310       // The value of the object is its address, which is the address of
3311       // its first stack doubleword.
3312       InVals.push_back(FIN);
3313 
3314       // Store whatever pieces of the object are in registers to memory.
3315       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3316         if (GPR_idx == Num_GPR_Regs)
3317           break;
3318 
3319         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3320         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3321         SDValue Addr = FIN;
3322         if (j) {
3323           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3324           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3325         }
3326         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3327                                      MachinePointerInfo(&*FuncArg, j));
3328         MemOps.push_back(Store);
3329         ++GPR_idx;
3330       }
3331       ArgOffset += ArgSize;
3332       continue;
3333     }
3334 
3335     switch (ObjectVT.getSimpleVT().SimpleTy) {
3336     default: llvm_unreachable("Unhandled argument type!");
3337     case MVT::i1:
3338     case MVT::i32:
3339     case MVT::i64:
3340       if (Flags.isNest()) {
3341         // The 'nest' parameter, if any, is passed in R11.
3342         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3343         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3344 
3345         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3346           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3347 
3348         break;
3349       }
3350 
3351       // These can be scalar arguments or elements of an integer array type
3352       // passed directly.  Clang may use those instead of "byval" aggregate
3353       // types to avoid forcing arguments to memory unnecessarily.
3354       if (GPR_idx != Num_GPR_Regs) {
3355         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3356         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3357 
3358         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3359           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3360           // value to MVT::i64 and then truncate to the correct register size.
3361           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3362       } else {
3363         if (CallConv == CallingConv::Fast)
3364           ComputeArgOffset();
3365 
3366         needsLoad = true;
3367         ArgSize = PtrByteSize;
3368       }
3369       if (CallConv != CallingConv::Fast || needsLoad)
3370         ArgOffset += 8;
3371       break;
3372 
3373     case MVT::f32:
3374     case MVT::f64:
3375       // These can be scalar arguments or elements of a float array type
3376       // passed directly.  The latter are used to implement ELFv2 homogenous
3377       // float aggregates.
3378       if (FPR_idx != Num_FPR_Regs) {
3379         unsigned VReg;
3380 
3381         if (ObjectVT == MVT::f32)
3382           VReg = MF.addLiveIn(FPR[FPR_idx],
3383                               Subtarget.hasP8Vector()
3384                                   ? &PPC::VSSRCRegClass
3385                                   : &PPC::F4RCRegClass);
3386         else
3387           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3388                                                 ? &PPC::VSFRCRegClass
3389                                                 : &PPC::F8RCRegClass);
3390 
3391         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3392         ++FPR_idx;
3393       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3394         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3395         // once we support fp <-> gpr moves.
3396 
3397         // This can only ever happen in the presence of f32 array types,
3398         // since otherwise we never run out of FPRs before running out
3399         // of GPRs.
3400         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3401         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3402 
3403         if (ObjectVT == MVT::f32) {
3404           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3405             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3406                                  DAG.getConstant(32, dl, MVT::i32));
3407           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3408         }
3409 
3410         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3411       } else {
3412         if (CallConv == CallingConv::Fast)
3413           ComputeArgOffset();
3414 
3415         needsLoad = true;
3416       }
3417 
3418       // When passing an array of floats, the array occupies consecutive
3419       // space in the argument area; only round up to the next doubleword
3420       // at the end of the array.  Otherwise, each float takes 8 bytes.
3421       if (CallConv != CallingConv::Fast || needsLoad) {
3422         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3423         ArgOffset += ArgSize;
3424         if (Flags.isInConsecutiveRegsLast())
3425           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3426       }
3427       break;
3428     case MVT::v4f32:
3429     case MVT::v4i32:
3430     case MVT::v8i16:
3431     case MVT::v16i8:
3432     case MVT::v2f64:
3433     case MVT::v2i64:
3434     case MVT::v1i128:
3435       if (!Subtarget.hasQPX()) {
3436       // These can be scalar arguments or elements of a vector array type
3437       // passed directly.  The latter are used to implement ELFv2 homogenous
3438       // vector aggregates.
3439       if (VR_idx != Num_VR_Regs) {
3440         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3441                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3442                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3443         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3444         ++VR_idx;
3445       } else {
3446         if (CallConv == CallingConv::Fast)
3447           ComputeArgOffset();
3448 
3449         needsLoad = true;
3450       }
3451       if (CallConv != CallingConv::Fast || needsLoad)
3452         ArgOffset += 16;
3453       break;
3454       } // not QPX
3455 
3456       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3457              "Invalid QPX parameter type");
3458       /* fall through */
3459 
3460     case MVT::v4f64:
3461     case MVT::v4i1:
3462       // QPX vectors are treated like their scalar floating-point subregisters
3463       // (except that they're larger).
3464       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3465       if (QFPR_idx != Num_QFPR_Regs) {
3466         const TargetRegisterClass *RC;
3467         switch (ObjectVT.getSimpleVT().SimpleTy) {
3468         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3469         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3470         default:         RC = &PPC::QBRCRegClass; break;
3471         }
3472 
3473         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3474         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3475         ++QFPR_idx;
3476       } else {
3477         if (CallConv == CallingConv::Fast)
3478           ComputeArgOffset();
3479         needsLoad = true;
3480       }
3481       if (CallConv != CallingConv::Fast || needsLoad)
3482         ArgOffset += Sz;
3483       break;
3484     }
3485 
3486     // We need to load the argument to a virtual register if we determined
3487     // above that we ran out of physical registers of the appropriate type.
3488     if (needsLoad) {
3489       if (ObjSize < ArgSize && !isLittleEndian)
3490         CurArgOffset += ArgSize - ObjSize;
3491       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3492       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3493       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3494     }
3495 
3496     InVals.push_back(ArgVal);
3497   }
3498 
3499   // Area that is at least reserved in the caller of this function.
3500   unsigned MinReservedArea;
3501   if (HasParameterArea)
3502     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3503   else
3504     MinReservedArea = LinkageSize;
3505 
3506   // Set the size that is at least reserved in caller of this function.  Tail
3507   // call optimized functions' reserved stack space needs to be aligned so that
3508   // taking the difference between two stack areas will result in an aligned
3509   // stack.
3510   MinReservedArea =
3511       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3512   FuncInfo->setMinReservedArea(MinReservedArea);
3513 
3514   // If the function takes variable number of arguments, make a frame index for
3515   // the start of the first vararg value... for expansion of llvm.va_start.
3516   if (isVarArg) {
3517     int Depth = ArgOffset;
3518 
3519     FuncInfo->setVarArgsFrameIndex(
3520       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3521     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3522 
3523     // If this function is vararg, store any remaining integer argument regs
3524     // to their spots on the stack so that they may be loaded by dereferencing
3525     // the result of va_next.
3526     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3527          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3528       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3529       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3530       SDValue Store =
3531           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3532       MemOps.push_back(Store);
3533       // Increment the address by four for the next argument to store
3534       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3535       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3536     }
3537   }
3538 
3539   if (!MemOps.empty())
3540     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3541 
3542   return Chain;
3543 }
3544 
3545 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3546     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3547     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3548     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3549   // TODO: add description of PPC stack frame format, or at least some docs.
3550   //
3551   MachineFunction &MF = DAG.getMachineFunction();
3552   MachineFrameInfo &MFI = MF.getFrameInfo();
3553   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3554 
3555   EVT PtrVT = getPointerTy(MF.getDataLayout());
3556   bool isPPC64 = PtrVT == MVT::i64;
3557   // Potential tail calls could cause overwriting of argument stack slots.
3558   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3559                        (CallConv == CallingConv::Fast));
3560   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3561   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3562   unsigned ArgOffset = LinkageSize;
3563   // Area that is at least reserved in caller of this function.
3564   unsigned MinReservedArea = ArgOffset;
3565 
3566   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3567     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3568     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3569   };
3570   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3571     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3572     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3573   };
3574   static const MCPhysReg VR[] = {
3575     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3576     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3577   };
3578 
3579   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3580   const unsigned Num_FPR_Regs = 13;
3581   const unsigned Num_VR_Regs  = array_lengthof( VR);
3582 
3583   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3584 
3585   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3586 
3587   // In 32-bit non-varargs functions, the stack space for vectors is after the
3588   // stack space for non-vectors.  We do not use this space unless we have
3589   // too many vectors to fit in registers, something that only occurs in
3590   // constructed examples:), but we have to walk the arglist to figure
3591   // that out...for the pathological case, compute VecArgOffset as the
3592   // start of the vector parameter area.  Computing VecArgOffset is the
3593   // entire point of the following loop.
3594   unsigned VecArgOffset = ArgOffset;
3595   if (!isVarArg && !isPPC64) {
3596     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3597          ++ArgNo) {
3598       EVT ObjectVT = Ins[ArgNo].VT;
3599       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3600 
3601       if (Flags.isByVal()) {
3602         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3603         unsigned ObjSize = Flags.getByValSize();
3604         unsigned ArgSize =
3605                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3606         VecArgOffset += ArgSize;
3607         continue;
3608       }
3609 
3610       switch(ObjectVT.getSimpleVT().SimpleTy) {
3611       default: llvm_unreachable("Unhandled argument type!");
3612       case MVT::i1:
3613       case MVT::i32:
3614       case MVT::f32:
3615         VecArgOffset += 4;
3616         break;
3617       case MVT::i64:  // PPC64
3618       case MVT::f64:
3619         // FIXME: We are guaranteed to be !isPPC64 at this point.
3620         // Does MVT::i64 apply?
3621         VecArgOffset += 8;
3622         break;
3623       case MVT::v4f32:
3624       case MVT::v4i32:
3625       case MVT::v8i16:
3626       case MVT::v16i8:
3627         // Nothing to do, we're only looking at Nonvector args here.
3628         break;
3629       }
3630     }
3631   }
3632   // We've found where the vector parameter area in memory is.  Skip the
3633   // first 12 parameters; these don't use that memory.
3634   VecArgOffset = ((VecArgOffset+15)/16)*16;
3635   VecArgOffset += 12*16;
3636 
3637   // Add DAG nodes to load the arguments or copy them out of registers.  On
3638   // entry to a function on PPC, the arguments start after the linkage area,
3639   // although the first ones are often in registers.
3640 
3641   SmallVector<SDValue, 8> MemOps;
3642   unsigned nAltivecParamsAtEnd = 0;
3643   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3644   unsigned CurArgIdx = 0;
3645   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3646     SDValue ArgVal;
3647     bool needsLoad = false;
3648     EVT ObjectVT = Ins[ArgNo].VT;
3649     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3650     unsigned ArgSize = ObjSize;
3651     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3652     if (Ins[ArgNo].isOrigArg()) {
3653       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3654       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3655     }
3656     unsigned CurArgOffset = ArgOffset;
3657 
3658     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3659     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3660         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3661       if (isVarArg || isPPC64) {
3662         MinReservedArea = ((MinReservedArea+15)/16)*16;
3663         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3664                                                   Flags,
3665                                                   PtrByteSize);
3666       } else  nAltivecParamsAtEnd++;
3667     } else
3668       // Calculate min reserved area.
3669       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3670                                                 Flags,
3671                                                 PtrByteSize);
3672 
3673     // FIXME the codegen can be much improved in some cases.
3674     // We do not have to keep everything in memory.
3675     if (Flags.isByVal()) {
3676       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3677 
3678       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3679       ObjSize = Flags.getByValSize();
3680       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3681       // Objects of size 1 and 2 are right justified, everything else is
3682       // left justified.  This means the memory address is adjusted forwards.
3683       if (ObjSize==1 || ObjSize==2) {
3684         CurArgOffset = CurArgOffset + (4 - ObjSize);
3685       }
3686       // The value of the object is its address.
3687       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3688       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3689       InVals.push_back(FIN);
3690       if (ObjSize==1 || ObjSize==2) {
3691         if (GPR_idx != Num_GPR_Regs) {
3692           unsigned VReg;
3693           if (isPPC64)
3694             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3695           else
3696             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3697           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3698           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3699           SDValue Store =
3700               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3701                                 MachinePointerInfo(&*FuncArg), ObjType);
3702           MemOps.push_back(Store);
3703           ++GPR_idx;
3704         }
3705 
3706         ArgOffset += PtrByteSize;
3707 
3708         continue;
3709       }
3710       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3711         // Store whatever pieces of the object are in registers
3712         // to memory.  ArgOffset will be the address of the beginning
3713         // of the object.
3714         if (GPR_idx != Num_GPR_Regs) {
3715           unsigned VReg;
3716           if (isPPC64)
3717             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3718           else
3719             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3720           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3721           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3722           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3723           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3724                                        MachinePointerInfo(&*FuncArg, j));
3725           MemOps.push_back(Store);
3726           ++GPR_idx;
3727           ArgOffset += PtrByteSize;
3728         } else {
3729           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3730           break;
3731         }
3732       }
3733       continue;
3734     }
3735 
3736     switch (ObjectVT.getSimpleVT().SimpleTy) {
3737     default: llvm_unreachable("Unhandled argument type!");
3738     case MVT::i1:
3739     case MVT::i32:
3740       if (!isPPC64) {
3741         if (GPR_idx != Num_GPR_Regs) {
3742           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3743           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3744 
3745           if (ObjectVT == MVT::i1)
3746             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3747 
3748           ++GPR_idx;
3749         } else {
3750           needsLoad = true;
3751           ArgSize = PtrByteSize;
3752         }
3753         // All int arguments reserve stack space in the Darwin ABI.
3754         ArgOffset += PtrByteSize;
3755         break;
3756       }
3757       LLVM_FALLTHROUGH;
3758     case MVT::i64:  // PPC64
3759       if (GPR_idx != Num_GPR_Regs) {
3760         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3761         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3762 
3763         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3764           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3765           // value to MVT::i64 and then truncate to the correct register size.
3766           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3767 
3768         ++GPR_idx;
3769       } else {
3770         needsLoad = true;
3771         ArgSize = PtrByteSize;
3772       }
3773       // All int arguments reserve stack space in the Darwin ABI.
3774       ArgOffset += 8;
3775       break;
3776 
3777     case MVT::f32:
3778     case MVT::f64:
3779       // Every 4 bytes of argument space consumes one of the GPRs available for
3780       // argument passing.
3781       if (GPR_idx != Num_GPR_Regs) {
3782         ++GPR_idx;
3783         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3784           ++GPR_idx;
3785       }
3786       if (FPR_idx != Num_FPR_Regs) {
3787         unsigned VReg;
3788 
3789         if (ObjectVT == MVT::f32)
3790           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3791         else
3792           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3793 
3794         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3795         ++FPR_idx;
3796       } else {
3797         needsLoad = true;
3798       }
3799 
3800       // All FP arguments reserve stack space in the Darwin ABI.
3801       ArgOffset += isPPC64 ? 8 : ObjSize;
3802       break;
3803     case MVT::v4f32:
3804     case MVT::v4i32:
3805     case MVT::v8i16:
3806     case MVT::v16i8:
3807       // Note that vector arguments in registers don't reserve stack space,
3808       // except in varargs functions.
3809       if (VR_idx != Num_VR_Regs) {
3810         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3811         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3812         if (isVarArg) {
3813           while ((ArgOffset % 16) != 0) {
3814             ArgOffset += PtrByteSize;
3815             if (GPR_idx != Num_GPR_Regs)
3816               GPR_idx++;
3817           }
3818           ArgOffset += 16;
3819           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3820         }
3821         ++VR_idx;
3822       } else {
3823         if (!isVarArg && !isPPC64) {
3824           // Vectors go after all the nonvectors.
3825           CurArgOffset = VecArgOffset;
3826           VecArgOffset += 16;
3827         } else {
3828           // Vectors are aligned.
3829           ArgOffset = ((ArgOffset+15)/16)*16;
3830           CurArgOffset = ArgOffset;
3831           ArgOffset += 16;
3832         }
3833         needsLoad = true;
3834       }
3835       break;
3836     }
3837 
3838     // We need to load the argument to a virtual register if we determined above
3839     // that we ran out of physical registers of the appropriate type.
3840     if (needsLoad) {
3841       int FI = MFI.CreateFixedObject(ObjSize,
3842                                      CurArgOffset + (ArgSize - ObjSize),
3843                                      isImmutable);
3844       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3845       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3846     }
3847 
3848     InVals.push_back(ArgVal);
3849   }
3850 
3851   // Allow for Altivec parameters at the end, if needed.
3852   if (nAltivecParamsAtEnd) {
3853     MinReservedArea = ((MinReservedArea+15)/16)*16;
3854     MinReservedArea += 16*nAltivecParamsAtEnd;
3855   }
3856 
3857   // Area that is at least reserved in the caller of this function.
3858   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3859 
3860   // Set the size that is at least reserved in caller of this function.  Tail
3861   // call optimized functions' reserved stack space needs to be aligned so that
3862   // taking the difference between two stack areas will result in an aligned
3863   // stack.
3864   MinReservedArea =
3865       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3866   FuncInfo->setMinReservedArea(MinReservedArea);
3867 
3868   // If the function takes variable number of arguments, make a frame index for
3869   // the start of the first vararg value... for expansion of llvm.va_start.
3870   if (isVarArg) {
3871     int Depth = ArgOffset;
3872 
3873     FuncInfo->setVarArgsFrameIndex(
3874       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3875                             Depth, true));
3876     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3877 
3878     // If this function is vararg, store any remaining integer argument regs
3879     // to their spots on the stack so that they may be loaded by dereferencing
3880     // the result of va_next.
3881     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3882       unsigned VReg;
3883 
3884       if (isPPC64)
3885         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3886       else
3887         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3888 
3889       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3890       SDValue Store =
3891           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3892       MemOps.push_back(Store);
3893       // Increment the address by four for the next argument to store
3894       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3895       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3896     }
3897   }
3898 
3899   if (!MemOps.empty())
3900     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3901 
3902   return Chain;
3903 }
3904 
3905 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3906 /// adjusted to accommodate the arguments for the tailcall.
3907 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3908                                    unsigned ParamSize) {
3909 
3910   if (!isTailCall) return 0;
3911 
3912   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3913   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3914   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3915   // Remember only if the new adjustement is bigger.
3916   if (SPDiff < FI->getTailCallSPDelta())
3917     FI->setTailCallSPDelta(SPDiff);
3918 
3919   return SPDiff;
3920 }
3921 
3922 static bool isFunctionGlobalAddress(SDValue Callee);
3923 
3924 static bool
3925 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3926   // If !G, Callee can be an external symbol.
3927   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3928   if (!G) return false;
3929 
3930   const GlobalValue *GV = G->getGlobal();
3931 
3932   if (GV->isDeclaration()) return false;
3933 
3934   switch(GV->getLinkage()) {
3935   default: llvm_unreachable("unknow linkage type");
3936   case GlobalValue::AvailableExternallyLinkage:
3937   case GlobalValue::ExternalWeakLinkage:
3938     return false;
3939 
3940   // Callee with weak linkage is allowed if it has hidden or protected
3941   // visibility
3942   case GlobalValue::LinkOnceAnyLinkage:
3943   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3944   case GlobalValue::WeakAnyLinkage:
3945   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3946     if (GV->hasDefaultVisibility())
3947       return false;
3948 
3949   case GlobalValue::ExternalLinkage:
3950   case GlobalValue::InternalLinkage:
3951   case GlobalValue::PrivateLinkage:
3952     break;
3953   }
3954 
3955   // With '-fPIC', calling default visiblity function need insert 'nop' after
3956   // function call, no matter that function resides in same module or not, so
3957   // we treat it as in different module.
3958   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3959     return false;
3960 
3961   return true;
3962 }
3963 
3964 static bool
3965 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3966                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3967   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3968 
3969   const unsigned PtrByteSize = 8;
3970   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3971 
3972   static const MCPhysReg GPR[] = {
3973     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3974     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3975   };
3976   static const MCPhysReg VR[] = {
3977     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3978     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3979   };
3980 
3981   const unsigned NumGPRs = array_lengthof(GPR);
3982   const unsigned NumFPRs = 13;
3983   const unsigned NumVRs = array_lengthof(VR);
3984   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3985 
3986   unsigned NumBytes = LinkageSize;
3987   unsigned AvailableFPRs = NumFPRs;
3988   unsigned AvailableVRs = NumVRs;
3989 
3990   for (const ISD::OutputArg& Param : Outs) {
3991     if (Param.Flags.isNest()) continue;
3992 
3993     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3994                                PtrByteSize, LinkageSize, ParamAreaSize,
3995                                NumBytes, AvailableFPRs, AvailableVRs,
3996                                Subtarget.hasQPX()))
3997       return true;
3998   }
3999   return false;
4000 }
4001 
4002 static bool
4003 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4004   if (CS->arg_size() != CallerFn->getArgumentList().size())
4005     return false;
4006 
4007   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4008   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4009   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4010 
4011   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4012     const Value* CalleeArg = *CalleeArgIter;
4013     const Value* CallerArg = &(*CallerArgIter);
4014     if (CalleeArg == CallerArg)
4015       continue;
4016 
4017     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4018     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4019     //      }
4020     // 1st argument of callee is undef and has the same type as caller.
4021     if (CalleeArg->getType() == CallerArg->getType() &&
4022         isa<UndefValue>(CalleeArg))
4023       continue;
4024 
4025     return false;
4026   }
4027 
4028   return true;
4029 }
4030 
4031 bool
4032 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4033                                     SDValue Callee,
4034                                     CallingConv::ID CalleeCC,
4035                                     ImmutableCallSite *CS,
4036                                     bool isVarArg,
4037                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4038                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4039                                     SelectionDAG& DAG) const {
4040   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4041 
4042   if (DisableSCO && !TailCallOpt) return false;
4043 
4044   // Variadic argument functions are not supported.
4045   if (isVarArg) return false;
4046 
4047   MachineFunction &MF = DAG.getMachineFunction();
4048   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4049 
4050   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4051   // the same calling convention
4052   if (CallerCC != CalleeCC) return false;
4053 
4054   // SCO support C calling convention
4055   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4056     return false;
4057 
4058   // Caller contains any byval parameter is not supported.
4059   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4060     return false;
4061 
4062   // Callee contains any byval parameter is not supported, too.
4063   // Note: This is a quick work around, because in some cases, e.g.
4064   // caller's stack size > callee's stack size, we are still able to apply
4065   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4066   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4067     return false;
4068 
4069   // No TCO/SCO on indirect call because Caller have to restore its TOC
4070   if (!isFunctionGlobalAddress(Callee) &&
4071       !isa<ExternalSymbolSDNode>(Callee))
4072     return false;
4073 
4074   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4075   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4076   // module.
4077   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4078   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4079     return false;
4080 
4081   // TCO allows altering callee ABI, so we don't have to check further.
4082   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4083     return true;
4084 
4085   if (DisableSCO) return false;
4086 
4087   // If callee use the same argument list that caller is using, then we can
4088   // apply SCO on this case. If it is not, then we need to check if callee needs
4089   // stack for passing arguments.
4090   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4091       needStackSlotPassParameters(Subtarget, Outs)) {
4092     return false;
4093   }
4094 
4095   return true;
4096 }
4097 
4098 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4099 /// for tail call optimization. Targets which want to do tail call
4100 /// optimization should implement this function.
4101 bool
4102 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4103                                                      CallingConv::ID CalleeCC,
4104                                                      bool isVarArg,
4105                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4106                                                      SelectionDAG& DAG) const {
4107   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4108     return false;
4109 
4110   // Variable argument functions are not supported.
4111   if (isVarArg)
4112     return false;
4113 
4114   MachineFunction &MF = DAG.getMachineFunction();
4115   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4116   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4117     // Functions containing by val parameters are not supported.
4118     for (unsigned i = 0; i != Ins.size(); i++) {
4119        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4120        if (Flags.isByVal()) return false;
4121     }
4122 
4123     // Non-PIC/GOT tail calls are supported.
4124     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4125       return true;
4126 
4127     // At the moment we can only do local tail calls (in same module, hidden
4128     // or protected) if we are generating PIC.
4129     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4130       return G->getGlobal()->hasHiddenVisibility()
4131           || G->getGlobal()->hasProtectedVisibility();
4132   }
4133 
4134   return false;
4135 }
4136 
4137 /// isCallCompatibleAddress - Return the immediate to use if the specified
4138 /// 32-bit value is representable in the immediate field of a BxA instruction.
4139 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4140   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4141   if (!C) return nullptr;
4142 
4143   int Addr = C->getZExtValue();
4144   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4145       SignExtend32<26>(Addr) != Addr)
4146     return nullptr;  // Top 6 bits have to be sext of immediate.
4147 
4148   return DAG
4149       .getConstant(
4150           (int)C->getZExtValue() >> 2, SDLoc(Op),
4151           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4152       .getNode();
4153 }
4154 
4155 namespace {
4156 
4157 struct TailCallArgumentInfo {
4158   SDValue Arg;
4159   SDValue FrameIdxOp;
4160   int       FrameIdx;
4161 
4162   TailCallArgumentInfo() : FrameIdx(0) {}
4163 };
4164 }
4165 
4166 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4167 static void StoreTailCallArgumentsToStackSlot(
4168     SelectionDAG &DAG, SDValue Chain,
4169     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4170     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4171   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4172     SDValue Arg = TailCallArgs[i].Arg;
4173     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4174     int FI = TailCallArgs[i].FrameIdx;
4175     // Store relative to framepointer.
4176     MemOpChains.push_back(DAG.getStore(
4177         Chain, dl, Arg, FIN,
4178         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4179   }
4180 }
4181 
4182 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4183 /// the appropriate stack slot for the tail call optimized function call.
4184 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4185                                              SDValue OldRetAddr, SDValue OldFP,
4186                                              int SPDiff, const SDLoc &dl) {
4187   if (SPDiff) {
4188     // Calculate the new stack slot for the return address.
4189     MachineFunction &MF = DAG.getMachineFunction();
4190     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4191     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4192     bool isPPC64 = Subtarget.isPPC64();
4193     int SlotSize = isPPC64 ? 8 : 4;
4194     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4195     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4196                                                          NewRetAddrLoc, true);
4197     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4198     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4199     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4200                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4201 
4202     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4203     // slot as the FP is never overwritten.
4204     if (Subtarget.isDarwinABI()) {
4205       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4206       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4207                                                          true);
4208       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4209       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4210                            MachinePointerInfo::getFixedStack(
4211                                DAG.getMachineFunction(), NewFPIdx));
4212     }
4213   }
4214   return Chain;
4215 }
4216 
4217 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4218 /// the position of the argument.
4219 static void
4220 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4221                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4222                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4223   int Offset = ArgOffset + SPDiff;
4224   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4225   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4226   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4227   SDValue FIN = DAG.getFrameIndex(FI, VT);
4228   TailCallArgumentInfo Info;
4229   Info.Arg = Arg;
4230   Info.FrameIdxOp = FIN;
4231   Info.FrameIdx = FI;
4232   TailCallArguments.push_back(Info);
4233 }
4234 
4235 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4236 /// stack slot. Returns the chain as result and the loaded frame pointers in
4237 /// LROpOut/FPOpout. Used when tail calling.
4238 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4239     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4240     SDValue &FPOpOut, const SDLoc &dl) const {
4241   if (SPDiff) {
4242     // Load the LR and FP stack slot for later adjusting.
4243     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4244     LROpOut = getReturnAddrFrameIndex(DAG);
4245     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4246     Chain = SDValue(LROpOut.getNode(), 1);
4247 
4248     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4249     // slot as the FP is never overwritten.
4250     if (Subtarget.isDarwinABI()) {
4251       FPOpOut = getFramePointerFrameIndex(DAG);
4252       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4253       Chain = SDValue(FPOpOut.getNode(), 1);
4254     }
4255   }
4256   return Chain;
4257 }
4258 
4259 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4260 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4261 /// specified by the specific parameter attribute. The copy will be passed as
4262 /// a byval function parameter.
4263 /// Sometimes what we are copying is the end of a larger object, the part that
4264 /// does not fit in registers.
4265 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4266                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4267                                          SelectionDAG &DAG, const SDLoc &dl) {
4268   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4269   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4270                        false, false, false, MachinePointerInfo(),
4271                        MachinePointerInfo());
4272 }
4273 
4274 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4275 /// tail calls.
4276 static void LowerMemOpCallTo(
4277     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4278     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4279     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4280     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4281   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4282   if (!isTailCall) {
4283     if (isVector) {
4284       SDValue StackPtr;
4285       if (isPPC64)
4286         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4287       else
4288         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4289       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4290                            DAG.getConstant(ArgOffset, dl, PtrVT));
4291     }
4292     MemOpChains.push_back(
4293         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4294     // Calculate and remember argument location.
4295   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4296                                   TailCallArguments);
4297 }
4298 
4299 static void
4300 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4301                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4302                 SDValue FPOp,
4303                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4304   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4305   // might overwrite each other in case of tail call optimization.
4306   SmallVector<SDValue, 8> MemOpChains2;
4307   // Do not flag preceding copytoreg stuff together with the following stuff.
4308   InFlag = SDValue();
4309   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4310                                     MemOpChains2, dl);
4311   if (!MemOpChains2.empty())
4312     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4313 
4314   // Store the return address to the appropriate stack slot.
4315   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4316 
4317   // Emit callseq_end just before tailcall node.
4318   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4319                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4320   InFlag = Chain.getValue(1);
4321 }
4322 
4323 // Is this global address that of a function that can be called by name? (as
4324 // opposed to something that must hold a descriptor for an indirect call).
4325 static bool isFunctionGlobalAddress(SDValue Callee) {
4326   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4327     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4328         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4329       return false;
4330 
4331     return G->getGlobal()->getValueType()->isFunctionTy();
4332   }
4333 
4334   return false;
4335 }
4336 
4337 static unsigned
4338 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4339             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4340             bool isPatchPoint, bool hasNest,
4341             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4342             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4343             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4344 
4345   bool isPPC64 = Subtarget.isPPC64();
4346   bool isSVR4ABI = Subtarget.isSVR4ABI();
4347   bool isELFv2ABI = Subtarget.isELFv2ABI();
4348 
4349   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4350   NodeTys.push_back(MVT::Other);   // Returns a chain
4351   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4352 
4353   unsigned CallOpc = PPCISD::CALL;
4354 
4355   bool needIndirectCall = true;
4356   if (!isSVR4ABI || !isPPC64)
4357     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4358       // If this is an absolute destination address, use the munged value.
4359       Callee = SDValue(Dest, 0);
4360       needIndirectCall = false;
4361     }
4362 
4363   // PC-relative references to external symbols should go through $stub, unless
4364   // we're building with the leopard linker or later, which automatically
4365   // synthesizes these stubs.
4366   const TargetMachine &TM = DAG.getTarget();
4367   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4368   const GlobalValue *GV = nullptr;
4369   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4370     GV = G->getGlobal();
4371   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4372   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4373 
4374   if (isFunctionGlobalAddress(Callee)) {
4375     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4376     // A call to a TLS address is actually an indirect call to a
4377     // thread-specific pointer.
4378     unsigned OpFlags = 0;
4379     if (UsePlt)
4380       OpFlags = PPCII::MO_PLT;
4381 
4382     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4383     // every direct call is) turn it into a TargetGlobalAddress /
4384     // TargetExternalSymbol node so that legalize doesn't hack it.
4385     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4386                                         Callee.getValueType(), 0, OpFlags);
4387     needIndirectCall = false;
4388   }
4389 
4390   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4391     unsigned char OpFlags = 0;
4392 
4393     if (UsePlt)
4394       OpFlags = PPCII::MO_PLT;
4395 
4396     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4397                                          OpFlags);
4398     needIndirectCall = false;
4399   }
4400 
4401   if (isPatchPoint) {
4402     // We'll form an invalid direct call when lowering a patchpoint; the full
4403     // sequence for an indirect call is complicated, and many of the
4404     // instructions introduced might have side effects (and, thus, can't be
4405     // removed later). The call itself will be removed as soon as the
4406     // argument/return lowering is complete, so the fact that it has the wrong
4407     // kind of operands should not really matter.
4408     needIndirectCall = false;
4409   }
4410 
4411   if (needIndirectCall) {
4412     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4413     // to do the call, we can't use PPCISD::CALL.
4414     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4415 
4416     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4417       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4418       // entry point, but to the function descriptor (the function entry point
4419       // address is part of the function descriptor though).
4420       // The function descriptor is a three doubleword structure with the
4421       // following fields: function entry point, TOC base address and
4422       // environment pointer.
4423       // Thus for a call through a function pointer, the following actions need
4424       // to be performed:
4425       //   1. Save the TOC of the caller in the TOC save area of its stack
4426       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4427       //   2. Load the address of the function entry point from the function
4428       //      descriptor.
4429       //   3. Load the TOC of the callee from the function descriptor into r2.
4430       //   4. Load the environment pointer from the function descriptor into
4431       //      r11.
4432       //   5. Branch to the function entry point address.
4433       //   6. On return of the callee, the TOC of the caller needs to be
4434       //      restored (this is done in FinishCall()).
4435       //
4436       // The loads are scheduled at the beginning of the call sequence, and the
4437       // register copies are flagged together to ensure that no other
4438       // operations can be scheduled in between. E.g. without flagging the
4439       // copies together, a TOC access in the caller could be scheduled between
4440       // the assignment of the callee TOC and the branch to the callee, which
4441       // results in the TOC access going through the TOC of the callee instead
4442       // of going through the TOC of the caller, which leads to incorrect code.
4443 
4444       // Load the address of the function entry point from the function
4445       // descriptor.
4446       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4447       if (LDChain.getValueType() == MVT::Glue)
4448         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4449 
4450       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4451                           ? (MachineMemOperand::MODereferenceable |
4452                              MachineMemOperand::MOInvariant)
4453                           : MachineMemOperand::MONone;
4454 
4455       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4456       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4457                                         /* Alignment = */ 8, MMOFlags);
4458 
4459       // Load environment pointer into r11.
4460       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4461       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4462       SDValue LoadEnvPtr =
4463           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4464                       /* Alignment = */ 8, MMOFlags);
4465 
4466       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4467       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4468       SDValue TOCPtr =
4469           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4470                       /* Alignment = */ 8, MMOFlags);
4471 
4472       setUsesTOCBasePtr(DAG);
4473       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4474                                         InFlag);
4475       Chain = TOCVal.getValue(0);
4476       InFlag = TOCVal.getValue(1);
4477 
4478       // If the function call has an explicit 'nest' parameter, it takes the
4479       // place of the environment pointer.
4480       if (!hasNest) {
4481         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4482                                           InFlag);
4483 
4484         Chain = EnvVal.getValue(0);
4485         InFlag = EnvVal.getValue(1);
4486       }
4487 
4488       MTCTROps[0] = Chain;
4489       MTCTROps[1] = LoadFuncPtr;
4490       MTCTROps[2] = InFlag;
4491     }
4492 
4493     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4494                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4495     InFlag = Chain.getValue(1);
4496 
4497     NodeTys.clear();
4498     NodeTys.push_back(MVT::Other);
4499     NodeTys.push_back(MVT::Glue);
4500     Ops.push_back(Chain);
4501     CallOpc = PPCISD::BCTRL;
4502     Callee.setNode(nullptr);
4503     // Add use of X11 (holding environment pointer)
4504     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4505       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4506     // Add CTR register as callee so a bctr can be emitted later.
4507     if (isTailCall)
4508       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4509   }
4510 
4511   // If this is a direct call, pass the chain and the callee.
4512   if (Callee.getNode()) {
4513     Ops.push_back(Chain);
4514     Ops.push_back(Callee);
4515   }
4516   // If this is a tail call add stack pointer delta.
4517   if (isTailCall)
4518     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4519 
4520   // Add argument registers to the end of the list so that they are known live
4521   // into the call.
4522   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4523     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4524                                   RegsToPass[i].second.getValueType()));
4525 
4526   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4527   // into the call.
4528   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4529     setUsesTOCBasePtr(DAG);
4530     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4531   }
4532 
4533   return CallOpc;
4534 }
4535 
4536 static
4537 bool isLocalCall(const SDValue &Callee)
4538 {
4539   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4540     return G->getGlobal()->isStrongDefinitionForLinker();
4541   return false;
4542 }
4543 
4544 SDValue PPCTargetLowering::LowerCallResult(
4545     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4546     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4547     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4548 
4549   SmallVector<CCValAssign, 16> RVLocs;
4550   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4551                     *DAG.getContext());
4552   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4553 
4554   // Copy all of the result registers out of their specified physreg.
4555   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4556     CCValAssign &VA = RVLocs[i];
4557     assert(VA.isRegLoc() && "Can only return in registers!");
4558 
4559     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4560                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4561     Chain = Val.getValue(1);
4562     InFlag = Val.getValue(2);
4563 
4564     switch (VA.getLocInfo()) {
4565     default: llvm_unreachable("Unknown loc info!");
4566     case CCValAssign::Full: break;
4567     case CCValAssign::AExt:
4568       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4569       break;
4570     case CCValAssign::ZExt:
4571       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4572                         DAG.getValueType(VA.getValVT()));
4573       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4574       break;
4575     case CCValAssign::SExt:
4576       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4577                         DAG.getValueType(VA.getValVT()));
4578       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4579       break;
4580     }
4581 
4582     InVals.push_back(Val);
4583   }
4584 
4585   return Chain;
4586 }
4587 
4588 SDValue PPCTargetLowering::FinishCall(
4589     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4590     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4591     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4592     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4593     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4594     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4595 
4596   std::vector<EVT> NodeTys;
4597   SmallVector<SDValue, 8> Ops;
4598   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4599                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4600                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4601 
4602   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4603   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4604     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4605 
4606   // When performing tail call optimization the callee pops its arguments off
4607   // the stack. Account for this here so these bytes can be pushed back on in
4608   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4609   int BytesCalleePops =
4610     (CallConv == CallingConv::Fast &&
4611      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4612 
4613   // Add a register mask operand representing the call-preserved registers.
4614   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4615   const uint32_t *Mask =
4616       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4617   assert(Mask && "Missing call preserved mask for calling convention");
4618   Ops.push_back(DAG.getRegisterMask(Mask));
4619 
4620   if (InFlag.getNode())
4621     Ops.push_back(InFlag);
4622 
4623   // Emit tail call.
4624   if (isTailCall) {
4625     assert(((Callee.getOpcode() == ISD::Register &&
4626              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4627             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4628             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4629             isa<ConstantSDNode>(Callee)) &&
4630     "Expecting an global address, external symbol, absolute value or register");
4631 
4632     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4633     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4634   }
4635 
4636   // Add a NOP immediately after the branch instruction when using the 64-bit
4637   // SVR4 ABI. At link time, if caller and callee are in a different module and
4638   // thus have a different TOC, the call will be replaced with a call to a stub
4639   // function which saves the current TOC, loads the TOC of the callee and
4640   // branches to the callee. The NOP will be replaced with a load instruction
4641   // which restores the TOC of the caller from the TOC save slot of the current
4642   // stack frame. If caller and callee belong to the same module (and have the
4643   // same TOC), the NOP will remain unchanged.
4644 
4645   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4646       !isPatchPoint) {
4647     if (CallOpc == PPCISD::BCTRL) {
4648       // This is a call through a function pointer.
4649       // Restore the caller TOC from the save area into R2.
4650       // See PrepareCall() for more information about calls through function
4651       // pointers in the 64-bit SVR4 ABI.
4652       // We are using a target-specific load with r2 hard coded, because the
4653       // result of a target-independent load would never go directly into r2,
4654       // since r2 is a reserved register (which prevents the register allocator
4655       // from allocating it), resulting in an additional register being
4656       // allocated and an unnecessary move instruction being generated.
4657       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4658 
4659       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4660       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4661       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4662       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4663       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4664 
4665       // The address needs to go after the chain input but before the flag (or
4666       // any other variadic arguments).
4667       Ops.insert(std::next(Ops.begin()), AddTOC);
4668     } else if ((CallOpc == PPCISD::CALL) &&
4669                (!isLocalCall(Callee) ||
4670                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4671       // Otherwise insert NOP for non-local calls.
4672       CallOpc = PPCISD::CALL_NOP;
4673   }
4674 
4675   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4676   InFlag = Chain.getValue(1);
4677 
4678   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4679                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4680                              InFlag, dl);
4681   if (!Ins.empty())
4682     InFlag = Chain.getValue(1);
4683 
4684   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4685                          Ins, dl, DAG, InVals);
4686 }
4687 
4688 SDValue
4689 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4690                              SmallVectorImpl<SDValue> &InVals) const {
4691   SelectionDAG &DAG                     = CLI.DAG;
4692   SDLoc &dl                             = CLI.DL;
4693   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4694   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4695   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4696   SDValue Chain                         = CLI.Chain;
4697   SDValue Callee                        = CLI.Callee;
4698   bool &isTailCall                      = CLI.IsTailCall;
4699   CallingConv::ID CallConv              = CLI.CallConv;
4700   bool isVarArg                         = CLI.IsVarArg;
4701   bool isPatchPoint                     = CLI.IsPatchPoint;
4702   ImmutableCallSite *CS                 = CLI.CS;
4703 
4704   if (isTailCall) {
4705     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4706       isTailCall = false;
4707     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4708       isTailCall =
4709         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4710                                                  isVarArg, Outs, Ins, DAG);
4711     else
4712       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4713                                                      Ins, DAG);
4714     if (isTailCall) {
4715       ++NumTailCalls;
4716       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4717         ++NumSiblingCalls;
4718 
4719       assert(isa<GlobalAddressSDNode>(Callee) &&
4720              "Callee should be an llvm::Function object.");
4721       DEBUG(
4722         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4723         const unsigned Width = 80 - strlen("TCO caller: ")
4724                                   - strlen(", callee linkage: 0, 0");
4725         dbgs() << "TCO caller: "
4726                << left_justify(DAG.getMachineFunction().getName(), Width)
4727                << ", callee linkage: "
4728                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4729       );
4730     }
4731   }
4732 
4733   if (!isTailCall && CS && CS->isMustTailCall())
4734     report_fatal_error("failed to perform tail call elimination on a call "
4735                        "site marked musttail");
4736 
4737   // When long calls (i.e. indirect calls) are always used, calls are always
4738   // made via function pointer. If we have a function name, first translate it
4739   // into a pointer.
4740   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4741       !isTailCall)
4742     Callee = LowerGlobalAddress(Callee, DAG);
4743 
4744   if (Subtarget.isSVR4ABI()) {
4745     if (Subtarget.isPPC64())
4746       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4747                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4748                               dl, DAG, InVals, CS);
4749     else
4750       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4751                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4752                               dl, DAG, InVals, CS);
4753   }
4754 
4755   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4756                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4757                           dl, DAG, InVals, CS);
4758 }
4759 
4760 SDValue PPCTargetLowering::LowerCall_32SVR4(
4761     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4762     bool isTailCall, bool isPatchPoint,
4763     const SmallVectorImpl<ISD::OutputArg> &Outs,
4764     const SmallVectorImpl<SDValue> &OutVals,
4765     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4766     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4767     ImmutableCallSite *CS) const {
4768   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4769   // of the 32-bit SVR4 ABI stack frame layout.
4770 
4771   assert((CallConv == CallingConv::C ||
4772           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4773 
4774   unsigned PtrByteSize = 4;
4775 
4776   MachineFunction &MF = DAG.getMachineFunction();
4777 
4778   // Mark this function as potentially containing a function that contains a
4779   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4780   // and restoring the callers stack pointer in this functions epilog. This is
4781   // done because by tail calling the called function might overwrite the value
4782   // in this function's (MF) stack pointer stack slot 0(SP).
4783   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4784       CallConv == CallingConv::Fast)
4785     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4786 
4787   // Count how many bytes are to be pushed on the stack, including the linkage
4788   // area, parameter list area and the part of the local variable space which
4789   // contains copies of aggregates which are passed by value.
4790 
4791   // Assign locations to all of the outgoing arguments.
4792   SmallVector<CCValAssign, 16> ArgLocs;
4793   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4794 
4795   // Reserve space for the linkage area on the stack.
4796   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4797                        PtrByteSize);
4798   if (useSoftFloat())
4799     CCInfo.PreAnalyzeCallOperands(Outs);
4800 
4801   if (isVarArg) {
4802     // Handle fixed and variable vector arguments differently.
4803     // Fixed vector arguments go into registers as long as registers are
4804     // available. Variable vector arguments always go into memory.
4805     unsigned NumArgs = Outs.size();
4806 
4807     for (unsigned i = 0; i != NumArgs; ++i) {
4808       MVT ArgVT = Outs[i].VT;
4809       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4810       bool Result;
4811 
4812       if (Outs[i].IsFixed) {
4813         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4814                                CCInfo);
4815       } else {
4816         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4817                                       ArgFlags, CCInfo);
4818       }
4819 
4820       if (Result) {
4821 #ifndef NDEBUG
4822         errs() << "Call operand #" << i << " has unhandled type "
4823              << EVT(ArgVT).getEVTString() << "\n";
4824 #endif
4825         llvm_unreachable(nullptr);
4826       }
4827     }
4828   } else {
4829     // All arguments are treated the same.
4830     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4831   }
4832   CCInfo.clearWasPPCF128();
4833 
4834   // Assign locations to all of the outgoing aggregate by value arguments.
4835   SmallVector<CCValAssign, 16> ByValArgLocs;
4836   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4837 
4838   // Reserve stack space for the allocations in CCInfo.
4839   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4840 
4841   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4842 
4843   // Size of the linkage area, parameter list area and the part of the local
4844   // space variable where copies of aggregates which are passed by value are
4845   // stored.
4846   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4847 
4848   // Calculate by how many bytes the stack has to be adjusted in case of tail
4849   // call optimization.
4850   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4851 
4852   // Adjust the stack pointer for the new arguments...
4853   // These operations are automatically eliminated by the prolog/epilog pass
4854   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4855                                dl);
4856   SDValue CallSeqStart = Chain;
4857 
4858   // Load the return address and frame pointer so it can be moved somewhere else
4859   // later.
4860   SDValue LROp, FPOp;
4861   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4862 
4863   // Set up a copy of the stack pointer for use loading and storing any
4864   // arguments that may not fit in the registers available for argument
4865   // passing.
4866   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4867 
4868   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4869   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4870   SmallVector<SDValue, 8> MemOpChains;
4871 
4872   bool seenFloatArg = false;
4873   // Walk the register/memloc assignments, inserting copies/loads.
4874   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4875        i != e;
4876        ++i) {
4877     CCValAssign &VA = ArgLocs[i];
4878     SDValue Arg = OutVals[i];
4879     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4880 
4881     if (Flags.isByVal()) {
4882       // Argument is an aggregate which is passed by value, thus we need to
4883       // create a copy of it in the local variable space of the current stack
4884       // frame (which is the stack frame of the caller) and pass the address of
4885       // this copy to the callee.
4886       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4887       CCValAssign &ByValVA = ByValArgLocs[j++];
4888       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4889 
4890       // Memory reserved in the local variable space of the callers stack frame.
4891       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4892 
4893       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4894       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4895                            StackPtr, PtrOff);
4896 
4897       // Create a copy of the argument in the local area of the current
4898       // stack frame.
4899       SDValue MemcpyCall =
4900         CreateCopyOfByValArgument(Arg, PtrOff,
4901                                   CallSeqStart.getNode()->getOperand(0),
4902                                   Flags, DAG, dl);
4903 
4904       // This must go outside the CALLSEQ_START..END.
4905       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4906                            CallSeqStart.getNode()->getOperand(1),
4907                            SDLoc(MemcpyCall));
4908       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4909                              NewCallSeqStart.getNode());
4910       Chain = CallSeqStart = NewCallSeqStart;
4911 
4912       // Pass the address of the aggregate copy on the stack either in a
4913       // physical register or in the parameter list area of the current stack
4914       // frame to the callee.
4915       Arg = PtrOff;
4916     }
4917 
4918     if (VA.isRegLoc()) {
4919       if (Arg.getValueType() == MVT::i1)
4920         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4921 
4922       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4923       // Put argument in a physical register.
4924       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4925     } else {
4926       // Put argument in the parameter list area of the current stack frame.
4927       assert(VA.isMemLoc());
4928       unsigned LocMemOffset = VA.getLocMemOffset();
4929 
4930       if (!isTailCall) {
4931         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4932         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4933                              StackPtr, PtrOff);
4934 
4935         MemOpChains.push_back(
4936             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4937       } else {
4938         // Calculate and remember argument location.
4939         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4940                                  TailCallArguments);
4941       }
4942     }
4943   }
4944 
4945   if (!MemOpChains.empty())
4946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4947 
4948   // Build a sequence of copy-to-reg nodes chained together with token chain
4949   // and flag operands which copy the outgoing args into the appropriate regs.
4950   SDValue InFlag;
4951   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4952     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4953                              RegsToPass[i].second, InFlag);
4954     InFlag = Chain.getValue(1);
4955   }
4956 
4957   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4958   // registers.
4959   if (isVarArg) {
4960     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4961     SDValue Ops[] = { Chain, InFlag };
4962 
4963     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4964                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4965 
4966     InFlag = Chain.getValue(1);
4967   }
4968 
4969   if (isTailCall)
4970     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
4971                     TailCallArguments);
4972 
4973   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
4974                     /* unused except on PPC64 ELFv1 */ false, DAG,
4975                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4976                     NumBytes, Ins, InVals, CS);
4977 }
4978 
4979 // Copy an argument into memory, being careful to do this outside the
4980 // call sequence for the call to which the argument belongs.
4981 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4982     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4983     SelectionDAG &DAG, const SDLoc &dl) const {
4984   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4985                         CallSeqStart.getNode()->getOperand(0),
4986                         Flags, DAG, dl);
4987   // The MEMCPY must go outside the CALLSEQ_START..END.
4988   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4989                              CallSeqStart.getNode()->getOperand(1),
4990                              SDLoc(MemcpyCall));
4991   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4992                          NewCallSeqStart.getNode());
4993   return NewCallSeqStart;
4994 }
4995 
4996 SDValue PPCTargetLowering::LowerCall_64SVR4(
4997     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4998     bool isTailCall, bool isPatchPoint,
4999     const SmallVectorImpl<ISD::OutputArg> &Outs,
5000     const SmallVectorImpl<SDValue> &OutVals,
5001     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5002     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5003     ImmutableCallSite *CS) const {
5004 
5005   bool isELFv2ABI = Subtarget.isELFv2ABI();
5006   bool isLittleEndian = Subtarget.isLittleEndian();
5007   unsigned NumOps = Outs.size();
5008   bool hasNest = false;
5009   bool IsSibCall = false;
5010 
5011   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5012   unsigned PtrByteSize = 8;
5013 
5014   MachineFunction &MF = DAG.getMachineFunction();
5015 
5016   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5017     IsSibCall = true;
5018 
5019   // Mark this function as potentially containing a function that contains a
5020   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5021   // and restoring the callers stack pointer in this functions epilog. This is
5022   // done because by tail calling the called function might overwrite the value
5023   // in this function's (MF) stack pointer stack slot 0(SP).
5024   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5025       CallConv == CallingConv::Fast)
5026     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5027 
5028   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5029          "fastcc not supported on varargs functions");
5030 
5031   // Count how many bytes are to be pushed on the stack, including the linkage
5032   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5033   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5034   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5035   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5036   unsigned NumBytes = LinkageSize;
5037   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5038   unsigned &QFPR_idx = FPR_idx;
5039 
5040   static const MCPhysReg GPR[] = {
5041     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5042     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5043   };
5044   static const MCPhysReg VR[] = {
5045     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5046     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5047   };
5048   static const MCPhysReg VSRH[] = {
5049     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
5050     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
5051   };
5052 
5053   const unsigned NumGPRs = array_lengthof(GPR);
5054   const unsigned NumFPRs = 13;
5055   const unsigned NumVRs  = array_lengthof(VR);
5056   const unsigned NumQFPRs = NumFPRs;
5057 
5058   // When using the fast calling convention, we don't provide backing for
5059   // arguments that will be in registers.
5060   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5061 
5062   // Add up all the space actually used.
5063   for (unsigned i = 0; i != NumOps; ++i) {
5064     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5065     EVT ArgVT = Outs[i].VT;
5066     EVT OrigVT = Outs[i].ArgVT;
5067 
5068     if (Flags.isNest())
5069       continue;
5070 
5071     if (CallConv == CallingConv::Fast) {
5072       if (Flags.isByVal())
5073         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5074       else
5075         switch (ArgVT.getSimpleVT().SimpleTy) {
5076         default: llvm_unreachable("Unexpected ValueType for argument!");
5077         case MVT::i1:
5078         case MVT::i32:
5079         case MVT::i64:
5080           if (++NumGPRsUsed <= NumGPRs)
5081             continue;
5082           break;
5083         case MVT::v4i32:
5084         case MVT::v8i16:
5085         case MVT::v16i8:
5086         case MVT::v2f64:
5087         case MVT::v2i64:
5088         case MVT::v1i128:
5089           if (++NumVRsUsed <= NumVRs)
5090             continue;
5091           break;
5092         case MVT::v4f32:
5093           // When using QPX, this is handled like a FP register, otherwise, it
5094           // is an Altivec register.
5095           if (Subtarget.hasQPX()) {
5096             if (++NumFPRsUsed <= NumFPRs)
5097               continue;
5098           } else {
5099             if (++NumVRsUsed <= NumVRs)
5100               continue;
5101           }
5102           break;
5103         case MVT::f32:
5104         case MVT::f64:
5105         case MVT::v4f64: // QPX
5106         case MVT::v4i1:  // QPX
5107           if (++NumFPRsUsed <= NumFPRs)
5108             continue;
5109           break;
5110         }
5111     }
5112 
5113     /* Respect alignment of argument on the stack.  */
5114     unsigned Align =
5115       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5116     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5117 
5118     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5119     if (Flags.isInConsecutiveRegsLast())
5120       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5121   }
5122 
5123   unsigned NumBytesActuallyUsed = NumBytes;
5124 
5125   // The prolog code of the callee may store up to 8 GPR argument registers to
5126   // the stack, allowing va_start to index over them in memory if its varargs.
5127   // Because we cannot tell if this is needed on the caller side, we have to
5128   // conservatively assume that it is needed.  As such, make sure we have at
5129   // least enough stack space for the caller to store the 8 GPRs.
5130   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5131   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5132 
5133   // Tail call needs the stack to be aligned.
5134   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5135       CallConv == CallingConv::Fast)
5136     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5137 
5138   int SPDiff = 0;
5139 
5140   // Calculate by how many bytes the stack has to be adjusted in case of tail
5141   // call optimization.
5142   if (!IsSibCall)
5143     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5144 
5145   // To protect arguments on the stack from being clobbered in a tail call,
5146   // force all the loads to happen before doing any other lowering.
5147   if (isTailCall)
5148     Chain = DAG.getStackArgumentTokenFactor(Chain);
5149 
5150   // Adjust the stack pointer for the new arguments...
5151   // These operations are automatically eliminated by the prolog/epilog pass
5152   if (!IsSibCall)
5153     Chain = DAG.getCALLSEQ_START(Chain,
5154                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5155   SDValue CallSeqStart = Chain;
5156 
5157   // Load the return address and frame pointer so it can be move somewhere else
5158   // later.
5159   SDValue LROp, FPOp;
5160   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5161 
5162   // Set up a copy of the stack pointer for use loading and storing any
5163   // arguments that may not fit in the registers available for argument
5164   // passing.
5165   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5166 
5167   // Figure out which arguments are going to go in registers, and which in
5168   // memory.  Also, if this is a vararg function, floating point operations
5169   // must be stored to our stack, and loaded into integer regs as well, if
5170   // any integer regs are available for argument passing.
5171   unsigned ArgOffset = LinkageSize;
5172 
5173   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5174   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5175 
5176   SmallVector<SDValue, 8> MemOpChains;
5177   for (unsigned i = 0; i != NumOps; ++i) {
5178     SDValue Arg = OutVals[i];
5179     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5180     EVT ArgVT = Outs[i].VT;
5181     EVT OrigVT = Outs[i].ArgVT;
5182 
5183     // PtrOff will be used to store the current argument to the stack if a
5184     // register cannot be found for it.
5185     SDValue PtrOff;
5186 
5187     // We re-align the argument offset for each argument, except when using the
5188     // fast calling convention, when we need to make sure we do that only when
5189     // we'll actually use a stack slot.
5190     auto ComputePtrOff = [&]() {
5191       /* Respect alignment of argument on the stack.  */
5192       unsigned Align =
5193         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5194       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5195 
5196       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5197 
5198       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5199     };
5200 
5201     if (CallConv != CallingConv::Fast) {
5202       ComputePtrOff();
5203 
5204       /* Compute GPR index associated with argument offset.  */
5205       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5206       GPR_idx = std::min(GPR_idx, NumGPRs);
5207     }
5208 
5209     // Promote integers to 64-bit values.
5210     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5211       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5212       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5213       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5214     }
5215 
5216     // FIXME memcpy is used way more than necessary.  Correctness first.
5217     // Note: "by value" is code for passing a structure by value, not
5218     // basic types.
5219     if (Flags.isByVal()) {
5220       // Note: Size includes alignment padding, so
5221       //   struct x { short a; char b; }
5222       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5223       // These are the proper values we need for right-justifying the
5224       // aggregate in a parameter register.
5225       unsigned Size = Flags.getByValSize();
5226 
5227       // An empty aggregate parameter takes up no storage and no
5228       // registers.
5229       if (Size == 0)
5230         continue;
5231 
5232       if (CallConv == CallingConv::Fast)
5233         ComputePtrOff();
5234 
5235       // All aggregates smaller than 8 bytes must be passed right-justified.
5236       if (Size==1 || Size==2 || Size==4) {
5237         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5238         if (GPR_idx != NumGPRs) {
5239           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5240                                         MachinePointerInfo(), VT);
5241           MemOpChains.push_back(Load.getValue(1));
5242           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5243 
5244           ArgOffset += PtrByteSize;
5245           continue;
5246         }
5247       }
5248 
5249       if (GPR_idx == NumGPRs && Size < 8) {
5250         SDValue AddPtr = PtrOff;
5251         if (!isLittleEndian) {
5252           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5253                                           PtrOff.getValueType());
5254           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5255         }
5256         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5257                                                           CallSeqStart,
5258                                                           Flags, DAG, dl);
5259         ArgOffset += PtrByteSize;
5260         continue;
5261       }
5262       // Copy entire object into memory.  There are cases where gcc-generated
5263       // code assumes it is there, even if it could be put entirely into
5264       // registers.  (This is not what the doc says.)
5265 
5266       // FIXME: The above statement is likely due to a misunderstanding of the
5267       // documents.  All arguments must be copied into the parameter area BY
5268       // THE CALLEE in the event that the callee takes the address of any
5269       // formal argument.  That has not yet been implemented.  However, it is
5270       // reasonable to use the stack area as a staging area for the register
5271       // load.
5272 
5273       // Skip this for small aggregates, as we will use the same slot for a
5274       // right-justified copy, below.
5275       if (Size >= 8)
5276         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5277                                                           CallSeqStart,
5278                                                           Flags, DAG, dl);
5279 
5280       // When a register is available, pass a small aggregate right-justified.
5281       if (Size < 8 && GPR_idx != NumGPRs) {
5282         // The easiest way to get this right-justified in a register
5283         // is to copy the structure into the rightmost portion of a
5284         // local variable slot, then load the whole slot into the
5285         // register.
5286         // FIXME: The memcpy seems to produce pretty awful code for
5287         // small aggregates, particularly for packed ones.
5288         // FIXME: It would be preferable to use the slot in the
5289         // parameter save area instead of a new local variable.
5290         SDValue AddPtr = PtrOff;
5291         if (!isLittleEndian) {
5292           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5293           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5294         }
5295         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5296                                                           CallSeqStart,
5297                                                           Flags, DAG, dl);
5298 
5299         // Load the slot into the register.
5300         SDValue Load =
5301             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5302         MemOpChains.push_back(Load.getValue(1));
5303         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5304 
5305         // Done with this argument.
5306         ArgOffset += PtrByteSize;
5307         continue;
5308       }
5309 
5310       // For aggregates larger than PtrByteSize, copy the pieces of the
5311       // object that fit into registers from the parameter save area.
5312       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5313         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5314         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5315         if (GPR_idx != NumGPRs) {
5316           SDValue Load =
5317               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5318           MemOpChains.push_back(Load.getValue(1));
5319           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5320           ArgOffset += PtrByteSize;
5321         } else {
5322           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5323           break;
5324         }
5325       }
5326       continue;
5327     }
5328 
5329     switch (Arg.getSimpleValueType().SimpleTy) {
5330     default: llvm_unreachable("Unexpected ValueType for argument!");
5331     case MVT::i1:
5332     case MVT::i32:
5333     case MVT::i64:
5334       if (Flags.isNest()) {
5335         // The 'nest' parameter, if any, is passed in R11.
5336         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5337         hasNest = true;
5338         break;
5339       }
5340 
5341       // These can be scalar arguments or elements of an integer array type
5342       // passed directly.  Clang may use those instead of "byval" aggregate
5343       // types to avoid forcing arguments to memory unnecessarily.
5344       if (GPR_idx != NumGPRs) {
5345         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5346       } else {
5347         if (CallConv == CallingConv::Fast)
5348           ComputePtrOff();
5349 
5350         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5351                          true, isTailCall, false, MemOpChains,
5352                          TailCallArguments, dl);
5353         if (CallConv == CallingConv::Fast)
5354           ArgOffset += PtrByteSize;
5355       }
5356       if (CallConv != CallingConv::Fast)
5357         ArgOffset += PtrByteSize;
5358       break;
5359     case MVT::f32:
5360     case MVT::f64: {
5361       // These can be scalar arguments or elements of a float array type
5362       // passed directly.  The latter are used to implement ELFv2 homogenous
5363       // float aggregates.
5364 
5365       // Named arguments go into FPRs first, and once they overflow, the
5366       // remaining arguments go into GPRs and then the parameter save area.
5367       // Unnamed arguments for vararg functions always go to GPRs and
5368       // then the parameter save area.  For now, put all arguments to vararg
5369       // routines always in both locations (FPR *and* GPR or stack slot).
5370       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5371       bool NeededLoad = false;
5372 
5373       // First load the argument into the next available FPR.
5374       if (FPR_idx != NumFPRs)
5375         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5376 
5377       // Next, load the argument into GPR or stack slot if needed.
5378       if (!NeedGPROrStack)
5379         ;
5380       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5381         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5382         // once we support fp <-> gpr moves.
5383 
5384         // In the non-vararg case, this can only ever happen in the
5385         // presence of f32 array types, since otherwise we never run
5386         // out of FPRs before running out of GPRs.
5387         SDValue ArgVal;
5388 
5389         // Double values are always passed in a single GPR.
5390         if (Arg.getValueType() != MVT::f32) {
5391           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5392 
5393         // Non-array float values are extended and passed in a GPR.
5394         } else if (!Flags.isInConsecutiveRegs()) {
5395           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5396           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5397 
5398         // If we have an array of floats, we collect every odd element
5399         // together with its predecessor into one GPR.
5400         } else if (ArgOffset % PtrByteSize != 0) {
5401           SDValue Lo, Hi;
5402           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5403           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5404           if (!isLittleEndian)
5405             std::swap(Lo, Hi);
5406           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5407 
5408         // The final element, if even, goes into the first half of a GPR.
5409         } else if (Flags.isInConsecutiveRegsLast()) {
5410           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5411           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5412           if (!isLittleEndian)
5413             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5414                                  DAG.getConstant(32, dl, MVT::i32));
5415 
5416         // Non-final even elements are skipped; they will be handled
5417         // together the with subsequent argument on the next go-around.
5418         } else
5419           ArgVal = SDValue();
5420 
5421         if (ArgVal.getNode())
5422           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5423       } else {
5424         if (CallConv == CallingConv::Fast)
5425           ComputePtrOff();
5426 
5427         // Single-precision floating-point values are mapped to the
5428         // second (rightmost) word of the stack doubleword.
5429         if (Arg.getValueType() == MVT::f32 &&
5430             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5431           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5432           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5433         }
5434 
5435         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5436                          true, isTailCall, false, MemOpChains,
5437                          TailCallArguments, dl);
5438 
5439         NeededLoad = true;
5440       }
5441       // When passing an array of floats, the array occupies consecutive
5442       // space in the argument area; only round up to the next doubleword
5443       // at the end of the array.  Otherwise, each float takes 8 bytes.
5444       if (CallConv != CallingConv::Fast || NeededLoad) {
5445         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5446                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5447         if (Flags.isInConsecutiveRegsLast())
5448           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5449       }
5450       break;
5451     }
5452     case MVT::v4f32:
5453     case MVT::v4i32:
5454     case MVT::v8i16:
5455     case MVT::v16i8:
5456     case MVT::v2f64:
5457     case MVT::v2i64:
5458     case MVT::v1i128:
5459       if (!Subtarget.hasQPX()) {
5460       // These can be scalar arguments or elements of a vector array type
5461       // passed directly.  The latter are used to implement ELFv2 homogenous
5462       // vector aggregates.
5463 
5464       // For a varargs call, named arguments go into VRs or on the stack as
5465       // usual; unnamed arguments always go to the stack or the corresponding
5466       // GPRs when within range.  For now, we always put the value in both
5467       // locations (or even all three).
5468       if (isVarArg) {
5469         // We could elide this store in the case where the object fits
5470         // entirely in R registers.  Maybe later.
5471         SDValue Store =
5472             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5473         MemOpChains.push_back(Store);
5474         if (VR_idx != NumVRs) {
5475           SDValue Load =
5476               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5477           MemOpChains.push_back(Load.getValue(1));
5478 
5479           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5480                            Arg.getSimpleValueType() == MVT::v2i64) ?
5481                           VSRH[VR_idx] : VR[VR_idx];
5482           ++VR_idx;
5483 
5484           RegsToPass.push_back(std::make_pair(VReg, Load));
5485         }
5486         ArgOffset += 16;
5487         for (unsigned i=0; i<16; i+=PtrByteSize) {
5488           if (GPR_idx == NumGPRs)
5489             break;
5490           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5491                                    DAG.getConstant(i, dl, PtrVT));
5492           SDValue Load =
5493               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5494           MemOpChains.push_back(Load.getValue(1));
5495           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5496         }
5497         break;
5498       }
5499 
5500       // Non-varargs Altivec params go into VRs or on the stack.
5501       if (VR_idx != NumVRs) {
5502         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5503                          Arg.getSimpleValueType() == MVT::v2i64) ?
5504                         VSRH[VR_idx] : VR[VR_idx];
5505         ++VR_idx;
5506 
5507         RegsToPass.push_back(std::make_pair(VReg, Arg));
5508       } else {
5509         if (CallConv == CallingConv::Fast)
5510           ComputePtrOff();
5511 
5512         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5513                          true, isTailCall, true, MemOpChains,
5514                          TailCallArguments, dl);
5515         if (CallConv == CallingConv::Fast)
5516           ArgOffset += 16;
5517       }
5518 
5519       if (CallConv != CallingConv::Fast)
5520         ArgOffset += 16;
5521       break;
5522       } // not QPX
5523 
5524       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5525              "Invalid QPX parameter type");
5526 
5527       /* fall through */
5528     case MVT::v4f64:
5529     case MVT::v4i1: {
5530       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5531       if (isVarArg) {
5532         // We could elide this store in the case where the object fits
5533         // entirely in R registers.  Maybe later.
5534         SDValue Store =
5535             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5536         MemOpChains.push_back(Store);
5537         if (QFPR_idx != NumQFPRs) {
5538           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5539                                      PtrOff, MachinePointerInfo());
5540           MemOpChains.push_back(Load.getValue(1));
5541           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5542         }
5543         ArgOffset += (IsF32 ? 16 : 32);
5544         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5545           if (GPR_idx == NumGPRs)
5546             break;
5547           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5548                                    DAG.getConstant(i, dl, PtrVT));
5549           SDValue Load =
5550               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5551           MemOpChains.push_back(Load.getValue(1));
5552           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5553         }
5554         break;
5555       }
5556 
5557       // Non-varargs QPX params go into registers or on the stack.
5558       if (QFPR_idx != NumQFPRs) {
5559         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5560       } else {
5561         if (CallConv == CallingConv::Fast)
5562           ComputePtrOff();
5563 
5564         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5565                          true, isTailCall, true, MemOpChains,
5566                          TailCallArguments, dl);
5567         if (CallConv == CallingConv::Fast)
5568           ArgOffset += (IsF32 ? 16 : 32);
5569       }
5570 
5571       if (CallConv != CallingConv::Fast)
5572         ArgOffset += (IsF32 ? 16 : 32);
5573       break;
5574       }
5575     }
5576   }
5577 
5578   assert(NumBytesActuallyUsed == ArgOffset);
5579   (void)NumBytesActuallyUsed;
5580 
5581   if (!MemOpChains.empty())
5582     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5583 
5584   // Check if this is an indirect call (MTCTR/BCTRL).
5585   // See PrepareCall() for more information about calls through function
5586   // pointers in the 64-bit SVR4 ABI.
5587   if (!isTailCall && !isPatchPoint &&
5588       !isFunctionGlobalAddress(Callee) &&
5589       !isa<ExternalSymbolSDNode>(Callee)) {
5590     // Load r2 into a virtual register and store it to the TOC save area.
5591     setUsesTOCBasePtr(DAG);
5592     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5593     // TOC save area offset.
5594     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5595     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5596     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5597     Chain = DAG.getStore(
5598         Val.getValue(1), dl, Val, AddPtr,
5599         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5600     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5601     // This does not mean the MTCTR instruction must use R12; it's easier
5602     // to model this as an extra parameter, so do that.
5603     if (isELFv2ABI && !isPatchPoint)
5604       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5605   }
5606 
5607   // Build a sequence of copy-to-reg nodes chained together with token chain
5608   // and flag operands which copy the outgoing args into the appropriate regs.
5609   SDValue InFlag;
5610   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5611     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5612                              RegsToPass[i].second, InFlag);
5613     InFlag = Chain.getValue(1);
5614   }
5615 
5616   if (isTailCall && !IsSibCall)
5617     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5618                     TailCallArguments);
5619 
5620   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5621                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5622                     SPDiff, NumBytes, Ins, InVals, CS);
5623 }
5624 
5625 SDValue PPCTargetLowering::LowerCall_Darwin(
5626     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5627     bool isTailCall, bool isPatchPoint,
5628     const SmallVectorImpl<ISD::OutputArg> &Outs,
5629     const SmallVectorImpl<SDValue> &OutVals,
5630     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5631     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5632     ImmutableCallSite *CS) const {
5633 
5634   unsigned NumOps = Outs.size();
5635 
5636   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5637   bool isPPC64 = PtrVT == MVT::i64;
5638   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5639 
5640   MachineFunction &MF = DAG.getMachineFunction();
5641 
5642   // Mark this function as potentially containing a function that contains a
5643   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5644   // and restoring the callers stack pointer in this functions epilog. This is
5645   // done because by tail calling the called function might overwrite the value
5646   // in this function's (MF) stack pointer stack slot 0(SP).
5647   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5648       CallConv == CallingConv::Fast)
5649     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5650 
5651   // Count how many bytes are to be pushed on the stack, including the linkage
5652   // area, and parameter passing area.  We start with 24/48 bytes, which is
5653   // prereserved space for [SP][CR][LR][3 x unused].
5654   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5655   unsigned NumBytes = LinkageSize;
5656 
5657   // Add up all the space actually used.
5658   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5659   // they all go in registers, but we must reserve stack space for them for
5660   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5661   // assigned stack space in order, with padding so Altivec parameters are
5662   // 16-byte aligned.
5663   unsigned nAltivecParamsAtEnd = 0;
5664   for (unsigned i = 0; i != NumOps; ++i) {
5665     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5666     EVT ArgVT = Outs[i].VT;
5667     // Varargs Altivec parameters are padded to a 16 byte boundary.
5668     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5669         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5670         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5671       if (!isVarArg && !isPPC64) {
5672         // Non-varargs Altivec parameters go after all the non-Altivec
5673         // parameters; handle those later so we know how much padding we need.
5674         nAltivecParamsAtEnd++;
5675         continue;
5676       }
5677       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5678       NumBytes = ((NumBytes+15)/16)*16;
5679     }
5680     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5681   }
5682 
5683   // Allow for Altivec parameters at the end, if needed.
5684   if (nAltivecParamsAtEnd) {
5685     NumBytes = ((NumBytes+15)/16)*16;
5686     NumBytes += 16*nAltivecParamsAtEnd;
5687   }
5688 
5689   // The prolog code of the callee may store up to 8 GPR argument registers to
5690   // the stack, allowing va_start to index over them in memory if its varargs.
5691   // Because we cannot tell if this is needed on the caller side, we have to
5692   // conservatively assume that it is needed.  As such, make sure we have at
5693   // least enough stack space for the caller to store the 8 GPRs.
5694   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5695 
5696   // Tail call needs the stack to be aligned.
5697   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5698       CallConv == CallingConv::Fast)
5699     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5700 
5701   // Calculate by how many bytes the stack has to be adjusted in case of tail
5702   // call optimization.
5703   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5704 
5705   // To protect arguments on the stack from being clobbered in a tail call,
5706   // force all the loads to happen before doing any other lowering.
5707   if (isTailCall)
5708     Chain = DAG.getStackArgumentTokenFactor(Chain);
5709 
5710   // Adjust the stack pointer for the new arguments...
5711   // These operations are automatically eliminated by the prolog/epilog pass
5712   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5713                                dl);
5714   SDValue CallSeqStart = Chain;
5715 
5716   // Load the return address and frame pointer so it can be move somewhere else
5717   // later.
5718   SDValue LROp, FPOp;
5719   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5720 
5721   // Set up a copy of the stack pointer for use loading and storing any
5722   // arguments that may not fit in the registers available for argument
5723   // passing.
5724   SDValue StackPtr;
5725   if (isPPC64)
5726     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5727   else
5728     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5729 
5730   // Figure out which arguments are going to go in registers, and which in
5731   // memory.  Also, if this is a vararg function, floating point operations
5732   // must be stored to our stack, and loaded into integer regs as well, if
5733   // any integer regs are available for argument passing.
5734   unsigned ArgOffset = LinkageSize;
5735   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5736 
5737   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5738     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5739     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5740   };
5741   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5742     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5743     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5744   };
5745   static const MCPhysReg VR[] = {
5746     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5747     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5748   };
5749   const unsigned NumGPRs = array_lengthof(GPR_32);
5750   const unsigned NumFPRs = 13;
5751   const unsigned NumVRs  = array_lengthof(VR);
5752 
5753   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5754 
5755   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5756   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5757 
5758   SmallVector<SDValue, 8> MemOpChains;
5759   for (unsigned i = 0; i != NumOps; ++i) {
5760     SDValue Arg = OutVals[i];
5761     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5762 
5763     // PtrOff will be used to store the current argument to the stack if a
5764     // register cannot be found for it.
5765     SDValue PtrOff;
5766 
5767     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5768 
5769     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5770 
5771     // On PPC64, promote integers to 64-bit values.
5772     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5773       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5774       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5775       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5776     }
5777 
5778     // FIXME memcpy is used way more than necessary.  Correctness first.
5779     // Note: "by value" is code for passing a structure by value, not
5780     // basic types.
5781     if (Flags.isByVal()) {
5782       unsigned Size = Flags.getByValSize();
5783       // Very small objects are passed right-justified.  Everything else is
5784       // passed left-justified.
5785       if (Size==1 || Size==2) {
5786         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5787         if (GPR_idx != NumGPRs) {
5788           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5789                                         MachinePointerInfo(), VT);
5790           MemOpChains.push_back(Load.getValue(1));
5791           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5792 
5793           ArgOffset += PtrByteSize;
5794         } else {
5795           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5796                                           PtrOff.getValueType());
5797           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5798           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5799                                                             CallSeqStart,
5800                                                             Flags, DAG, dl);
5801           ArgOffset += PtrByteSize;
5802         }
5803         continue;
5804       }
5805       // Copy entire object into memory.  There are cases where gcc-generated
5806       // code assumes it is there, even if it could be put entirely into
5807       // registers.  (This is not what the doc says.)
5808       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5809                                                         CallSeqStart,
5810                                                         Flags, DAG, dl);
5811 
5812       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5813       // copy the pieces of the object that fit into registers from the
5814       // parameter save area.
5815       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5816         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5817         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5818         if (GPR_idx != NumGPRs) {
5819           SDValue Load =
5820               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5821           MemOpChains.push_back(Load.getValue(1));
5822           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5823           ArgOffset += PtrByteSize;
5824         } else {
5825           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5826           break;
5827         }
5828       }
5829       continue;
5830     }
5831 
5832     switch (Arg.getSimpleValueType().SimpleTy) {
5833     default: llvm_unreachable("Unexpected ValueType for argument!");
5834     case MVT::i1:
5835     case MVT::i32:
5836     case MVT::i64:
5837       if (GPR_idx != NumGPRs) {
5838         if (Arg.getValueType() == MVT::i1)
5839           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5840 
5841         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5842       } else {
5843         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5844                          isPPC64, isTailCall, false, MemOpChains,
5845                          TailCallArguments, dl);
5846       }
5847       ArgOffset += PtrByteSize;
5848       break;
5849     case MVT::f32:
5850     case MVT::f64:
5851       if (FPR_idx != NumFPRs) {
5852         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5853 
5854         if (isVarArg) {
5855           SDValue Store =
5856               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5857           MemOpChains.push_back(Store);
5858 
5859           // Float varargs are always shadowed in available integer registers
5860           if (GPR_idx != NumGPRs) {
5861             SDValue Load =
5862                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5863             MemOpChains.push_back(Load.getValue(1));
5864             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5865           }
5866           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5867             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5868             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5869             SDValue Load =
5870                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5871             MemOpChains.push_back(Load.getValue(1));
5872             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5873           }
5874         } else {
5875           // If we have any FPRs remaining, we may also have GPRs remaining.
5876           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5877           // GPRs.
5878           if (GPR_idx != NumGPRs)
5879             ++GPR_idx;
5880           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5881               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5882             ++GPR_idx;
5883         }
5884       } else
5885         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5886                          isPPC64, isTailCall, false, MemOpChains,
5887                          TailCallArguments, dl);
5888       if (isPPC64)
5889         ArgOffset += 8;
5890       else
5891         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5892       break;
5893     case MVT::v4f32:
5894     case MVT::v4i32:
5895     case MVT::v8i16:
5896     case MVT::v16i8:
5897       if (isVarArg) {
5898         // These go aligned on the stack, or in the corresponding R registers
5899         // when within range.  The Darwin PPC ABI doc claims they also go in
5900         // V registers; in fact gcc does this only for arguments that are
5901         // prototyped, not for those that match the ...  We do it for all
5902         // arguments, seems to work.
5903         while (ArgOffset % 16 !=0) {
5904           ArgOffset += PtrByteSize;
5905           if (GPR_idx != NumGPRs)
5906             GPR_idx++;
5907         }
5908         // We could elide this store in the case where the object fits
5909         // entirely in R registers.  Maybe later.
5910         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5911                              DAG.getConstant(ArgOffset, dl, PtrVT));
5912         SDValue Store =
5913             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5914         MemOpChains.push_back(Store);
5915         if (VR_idx != NumVRs) {
5916           SDValue Load =
5917               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5918           MemOpChains.push_back(Load.getValue(1));
5919           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5920         }
5921         ArgOffset += 16;
5922         for (unsigned i=0; i<16; i+=PtrByteSize) {
5923           if (GPR_idx == NumGPRs)
5924             break;
5925           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5926                                    DAG.getConstant(i, dl, PtrVT));
5927           SDValue Load =
5928               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5929           MemOpChains.push_back(Load.getValue(1));
5930           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5931         }
5932         break;
5933       }
5934 
5935       // Non-varargs Altivec params generally go in registers, but have
5936       // stack space allocated at the end.
5937       if (VR_idx != NumVRs) {
5938         // Doesn't have GPR space allocated.
5939         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5940       } else if (nAltivecParamsAtEnd==0) {
5941         // We are emitting Altivec params in order.
5942         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5943                          isPPC64, isTailCall, true, MemOpChains,
5944                          TailCallArguments, dl);
5945         ArgOffset += 16;
5946       }
5947       break;
5948     }
5949   }
5950   // If all Altivec parameters fit in registers, as they usually do,
5951   // they get stack space following the non-Altivec parameters.  We
5952   // don't track this here because nobody below needs it.
5953   // If there are more Altivec parameters than fit in registers emit
5954   // the stores here.
5955   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5956     unsigned j = 0;
5957     // Offset is aligned; skip 1st 12 params which go in V registers.
5958     ArgOffset = ((ArgOffset+15)/16)*16;
5959     ArgOffset += 12*16;
5960     for (unsigned i = 0; i != NumOps; ++i) {
5961       SDValue Arg = OutVals[i];
5962       EVT ArgType = Outs[i].VT;
5963       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5964           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5965         if (++j > NumVRs) {
5966           SDValue PtrOff;
5967           // We are emitting Altivec params in order.
5968           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5969                            isPPC64, isTailCall, true, MemOpChains,
5970                            TailCallArguments, dl);
5971           ArgOffset += 16;
5972         }
5973       }
5974     }
5975   }
5976 
5977   if (!MemOpChains.empty())
5978     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5979 
5980   // On Darwin, R12 must contain the address of an indirect callee.  This does
5981   // not mean the MTCTR instruction must use R12; it's easier to model this as
5982   // an extra parameter, so do that.
5983   if (!isTailCall &&
5984       !isFunctionGlobalAddress(Callee) &&
5985       !isa<ExternalSymbolSDNode>(Callee) &&
5986       !isBLACompatibleAddress(Callee, DAG))
5987     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5988                                                    PPC::R12), Callee));
5989 
5990   // Build a sequence of copy-to-reg nodes chained together with token chain
5991   // and flag operands which copy the outgoing args into the appropriate regs.
5992   SDValue InFlag;
5993   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5994     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5995                              RegsToPass[i].second, InFlag);
5996     InFlag = Chain.getValue(1);
5997   }
5998 
5999   if (isTailCall)
6000     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6001                     TailCallArguments);
6002 
6003   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6004                     /* unused except on PPC64 ELFv1 */ false, DAG,
6005                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6006                     NumBytes, Ins, InVals, CS);
6007 }
6008 
6009 bool
6010 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6011                                   MachineFunction &MF, bool isVarArg,
6012                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6013                                   LLVMContext &Context) const {
6014   SmallVector<CCValAssign, 16> RVLocs;
6015   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6016   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6017 }
6018 
6019 SDValue
6020 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6021                                bool isVarArg,
6022                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6023                                const SmallVectorImpl<SDValue> &OutVals,
6024                                const SDLoc &dl, SelectionDAG &DAG) const {
6025 
6026   SmallVector<CCValAssign, 16> RVLocs;
6027   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6028                  *DAG.getContext());
6029   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6030 
6031   SDValue Flag;
6032   SmallVector<SDValue, 4> RetOps(1, Chain);
6033 
6034   // Copy the result values into the output registers.
6035   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6036     CCValAssign &VA = RVLocs[i];
6037     assert(VA.isRegLoc() && "Can only return in registers!");
6038 
6039     SDValue Arg = OutVals[i];
6040 
6041     switch (VA.getLocInfo()) {
6042     default: llvm_unreachable("Unknown loc info!");
6043     case CCValAssign::Full: break;
6044     case CCValAssign::AExt:
6045       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6046       break;
6047     case CCValAssign::ZExt:
6048       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6049       break;
6050     case CCValAssign::SExt:
6051       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6052       break;
6053     }
6054 
6055     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6056     Flag = Chain.getValue(1);
6057     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6058   }
6059 
6060   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6061   const MCPhysReg *I =
6062     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6063   if (I) {
6064     for (; *I; ++I) {
6065 
6066       if (PPC::G8RCRegClass.contains(*I))
6067         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6068       else if (PPC::F8RCRegClass.contains(*I))
6069         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6070       else if (PPC::CRRCRegClass.contains(*I))
6071         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6072       else if (PPC::VRRCRegClass.contains(*I))
6073         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6074       else
6075         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6076     }
6077   }
6078 
6079   RetOps[0] = Chain;  // Update chain.
6080 
6081   // Add the flag if we have it.
6082   if (Flag.getNode())
6083     RetOps.push_back(Flag);
6084 
6085   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6086 }
6087 
6088 SDValue
6089 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6090                                                 SelectionDAG &DAG) const {
6091   SDLoc dl(Op);
6092 
6093   // Get the corect type for integers.
6094   EVT IntVT = Op.getValueType();
6095 
6096   // Get the inputs.
6097   SDValue Chain = Op.getOperand(0);
6098   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6099   // Build a DYNAREAOFFSET node.
6100   SDValue Ops[2] = {Chain, FPSIdx};
6101   SDVTList VTs = DAG.getVTList(IntVT);
6102   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6103 }
6104 
6105 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6106                                              SelectionDAG &DAG) const {
6107   // When we pop the dynamic allocation we need to restore the SP link.
6108   SDLoc dl(Op);
6109 
6110   // Get the corect type for pointers.
6111   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6112 
6113   // Construct the stack pointer operand.
6114   bool isPPC64 = Subtarget.isPPC64();
6115   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6116   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6117 
6118   // Get the operands for the STACKRESTORE.
6119   SDValue Chain = Op.getOperand(0);
6120   SDValue SaveSP = Op.getOperand(1);
6121 
6122   // Load the old link SP.
6123   SDValue LoadLinkSP =
6124       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6125 
6126   // Restore the stack pointer.
6127   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6128 
6129   // Store the old link SP.
6130   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6131 }
6132 
6133 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6134   MachineFunction &MF = DAG.getMachineFunction();
6135   bool isPPC64 = Subtarget.isPPC64();
6136   EVT PtrVT = getPointerTy(MF.getDataLayout());
6137 
6138   // Get current frame pointer save index.  The users of this index will be
6139   // primarily DYNALLOC instructions.
6140   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6141   int RASI = FI->getReturnAddrSaveIndex();
6142 
6143   // If the frame pointer save index hasn't been defined yet.
6144   if (!RASI) {
6145     // Find out what the fix offset of the frame pointer save area.
6146     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6147     // Allocate the frame index for frame pointer save area.
6148     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6149     // Save the result.
6150     FI->setReturnAddrSaveIndex(RASI);
6151   }
6152   return DAG.getFrameIndex(RASI, PtrVT);
6153 }
6154 
6155 SDValue
6156 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6157   MachineFunction &MF = DAG.getMachineFunction();
6158   bool isPPC64 = Subtarget.isPPC64();
6159   EVT PtrVT = getPointerTy(MF.getDataLayout());
6160 
6161   // Get current frame pointer save index.  The users of this index will be
6162   // primarily DYNALLOC instructions.
6163   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6164   int FPSI = FI->getFramePointerSaveIndex();
6165 
6166   // If the frame pointer save index hasn't been defined yet.
6167   if (!FPSI) {
6168     // Find out what the fix offset of the frame pointer save area.
6169     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6170     // Allocate the frame index for frame pointer save area.
6171     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6172     // Save the result.
6173     FI->setFramePointerSaveIndex(FPSI);
6174   }
6175   return DAG.getFrameIndex(FPSI, PtrVT);
6176 }
6177 
6178 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6179                                                    SelectionDAG &DAG) const {
6180   // Get the inputs.
6181   SDValue Chain = Op.getOperand(0);
6182   SDValue Size  = Op.getOperand(1);
6183   SDLoc dl(Op);
6184 
6185   // Get the corect type for pointers.
6186   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6187   // Negate the size.
6188   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6189                                 DAG.getConstant(0, dl, PtrVT), Size);
6190   // Construct a node for the frame pointer save index.
6191   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6192   // Build a DYNALLOC node.
6193   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6194   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6195   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6196 }
6197 
6198 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6199                                                      SelectionDAG &DAG) const {
6200   MachineFunction &MF = DAG.getMachineFunction();
6201 
6202   bool isPPC64 = Subtarget.isPPC64();
6203   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6204 
6205   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6206   return DAG.getFrameIndex(FI, PtrVT);
6207 }
6208 
6209 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6210                                                SelectionDAG &DAG) const {
6211   SDLoc DL(Op);
6212   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6213                      DAG.getVTList(MVT::i32, MVT::Other),
6214                      Op.getOperand(0), Op.getOperand(1));
6215 }
6216 
6217 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6218                                                 SelectionDAG &DAG) const {
6219   SDLoc DL(Op);
6220   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6221                      Op.getOperand(0), Op.getOperand(1));
6222 }
6223 
6224 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6225   if (Op.getValueType().isVector())
6226     return LowerVectorLoad(Op, DAG);
6227 
6228   assert(Op.getValueType() == MVT::i1 &&
6229          "Custom lowering only for i1 loads");
6230 
6231   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6232 
6233   SDLoc dl(Op);
6234   LoadSDNode *LD = cast<LoadSDNode>(Op);
6235 
6236   SDValue Chain = LD->getChain();
6237   SDValue BasePtr = LD->getBasePtr();
6238   MachineMemOperand *MMO = LD->getMemOperand();
6239 
6240   SDValue NewLD =
6241       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6242                      BasePtr, MVT::i8, MMO);
6243   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6244 
6245   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6246   return DAG.getMergeValues(Ops, dl);
6247 }
6248 
6249 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6250   if (Op.getOperand(1).getValueType().isVector())
6251     return LowerVectorStore(Op, DAG);
6252 
6253   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6254          "Custom lowering only for i1 stores");
6255 
6256   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6257 
6258   SDLoc dl(Op);
6259   StoreSDNode *ST = cast<StoreSDNode>(Op);
6260 
6261   SDValue Chain = ST->getChain();
6262   SDValue BasePtr = ST->getBasePtr();
6263   SDValue Value = ST->getValue();
6264   MachineMemOperand *MMO = ST->getMemOperand();
6265 
6266   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6267                       Value);
6268   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6269 }
6270 
6271 // FIXME: Remove this once the ANDI glue bug is fixed:
6272 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6273   assert(Op.getValueType() == MVT::i1 &&
6274          "Custom lowering only for i1 results");
6275 
6276   SDLoc DL(Op);
6277   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6278                      Op.getOperand(0));
6279 }
6280 
6281 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6282 /// possible.
6283 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6284   // Not FP? Not a fsel.
6285   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6286       !Op.getOperand(2).getValueType().isFloatingPoint())
6287     return Op;
6288 
6289   // We might be able to do better than this under some circumstances, but in
6290   // general, fsel-based lowering of select is a finite-math-only optimization.
6291   // For more information, see section F.3 of the 2.06 ISA specification.
6292   if (!DAG.getTarget().Options.NoInfsFPMath ||
6293       !DAG.getTarget().Options.NoNaNsFPMath)
6294     return Op;
6295   // TODO: Propagate flags from the select rather than global settings.
6296   SDNodeFlags Flags;
6297   Flags.setNoInfs(true);
6298   Flags.setNoNaNs(true);
6299 
6300   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6301 
6302   EVT ResVT = Op.getValueType();
6303   EVT CmpVT = Op.getOperand(0).getValueType();
6304   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6305   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6306   SDLoc dl(Op);
6307 
6308   // If the RHS of the comparison is a 0.0, we don't need to do the
6309   // subtraction at all.
6310   SDValue Sel1;
6311   if (isFloatingPointZero(RHS))
6312     switch (CC) {
6313     default: break;       // SETUO etc aren't handled by fsel.
6314     case ISD::SETNE:
6315       std::swap(TV, FV);
6316     case ISD::SETEQ:
6317       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6318         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6319       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6320       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6321         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6322       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6323                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6324     case ISD::SETULT:
6325     case ISD::SETLT:
6326       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6327     case ISD::SETOGE:
6328     case ISD::SETGE:
6329       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6330         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6331       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6332     case ISD::SETUGT:
6333     case ISD::SETGT:
6334       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6335     case ISD::SETOLE:
6336     case ISD::SETLE:
6337       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6338         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6339       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6340                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6341     }
6342 
6343   SDValue Cmp;
6344   switch (CC) {
6345   default: break;       // SETUO etc aren't handled by fsel.
6346   case ISD::SETNE:
6347     std::swap(TV, FV);
6348   case ISD::SETEQ:
6349     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6350     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6351       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6352     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6353     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6354       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6355     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6356                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6357   case ISD::SETULT:
6358   case ISD::SETLT:
6359     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6360     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6361       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6362     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6363   case ISD::SETOGE:
6364   case ISD::SETGE:
6365     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6366     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6367       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6368     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6369   case ISD::SETUGT:
6370   case ISD::SETGT:
6371     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6372     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6373       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6374     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6375   case ISD::SETOLE:
6376   case ISD::SETLE:
6377     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6378     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6379       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6380     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6381   }
6382   return Op;
6383 }
6384 
6385 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6386                                                SelectionDAG &DAG,
6387                                                const SDLoc &dl) const {
6388   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6389   SDValue Src = Op.getOperand(0);
6390   if (Src.getValueType() == MVT::f32)
6391     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6392 
6393   SDValue Tmp;
6394   switch (Op.getSimpleValueType().SimpleTy) {
6395   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6396   case MVT::i32:
6397     Tmp = DAG.getNode(
6398         Op.getOpcode() == ISD::FP_TO_SINT
6399             ? PPCISD::FCTIWZ
6400             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6401         dl, MVT::f64, Src);
6402     break;
6403   case MVT::i64:
6404     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6405            "i64 FP_TO_UINT is supported only with FPCVT");
6406     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6407                                                         PPCISD::FCTIDUZ,
6408                       dl, MVT::f64, Src);
6409     break;
6410   }
6411 
6412   // Convert the FP value to an int value through memory.
6413   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6414     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6415   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6416   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6417   MachinePointerInfo MPI =
6418       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6419 
6420   // Emit a store to the stack slot.
6421   SDValue Chain;
6422   if (i32Stack) {
6423     MachineFunction &MF = DAG.getMachineFunction();
6424     MachineMemOperand *MMO =
6425       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6426     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6427     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6428               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6429   } else
6430     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6431 
6432   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6433   // add in a bias on big endian.
6434   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6435     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6436                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6437     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6438   }
6439 
6440   RLI.Chain = Chain;
6441   RLI.Ptr = FIPtr;
6442   RLI.MPI = MPI;
6443 }
6444 
6445 /// \brief Custom lowers floating point to integer conversions to use
6446 /// the direct move instructions available in ISA 2.07 to avoid the
6447 /// need for load/store combinations.
6448 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6449                                                     SelectionDAG &DAG,
6450                                                     const SDLoc &dl) const {
6451   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6452   SDValue Src = Op.getOperand(0);
6453 
6454   if (Src.getValueType() == MVT::f32)
6455     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6456 
6457   SDValue Tmp;
6458   switch (Op.getSimpleValueType().SimpleTy) {
6459   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6460   case MVT::i32:
6461     Tmp = DAG.getNode(
6462         Op.getOpcode() == ISD::FP_TO_SINT
6463             ? PPCISD::FCTIWZ
6464             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6465         dl, MVT::f64, Src);
6466     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6467     break;
6468   case MVT::i64:
6469     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6470            "i64 FP_TO_UINT is supported only with FPCVT");
6471     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6472                                                         PPCISD::FCTIDUZ,
6473                       dl, MVT::f64, Src);
6474     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6475     break;
6476   }
6477   return Tmp;
6478 }
6479 
6480 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6481                                           const SDLoc &dl) const {
6482   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6483     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6484 
6485   ReuseLoadInfo RLI;
6486   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6487 
6488   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6489                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6490 }
6491 
6492 // We're trying to insert a regular store, S, and then a load, L. If the
6493 // incoming value, O, is a load, we might just be able to have our load use the
6494 // address used by O. However, we don't know if anything else will store to
6495 // that address before we can load from it. To prevent this situation, we need
6496 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6497 // the same chain operand as O, we create a token factor from the chain results
6498 // of O and L, and we replace all uses of O's chain result with that token
6499 // factor (see spliceIntoChain below for this last part).
6500 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6501                                             ReuseLoadInfo &RLI,
6502                                             SelectionDAG &DAG,
6503                                             ISD::LoadExtType ET) const {
6504   SDLoc dl(Op);
6505   if (ET == ISD::NON_EXTLOAD &&
6506       (Op.getOpcode() == ISD::FP_TO_UINT ||
6507        Op.getOpcode() == ISD::FP_TO_SINT) &&
6508       isOperationLegalOrCustom(Op.getOpcode(),
6509                                Op.getOperand(0).getValueType())) {
6510 
6511     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6512     return true;
6513   }
6514 
6515   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6516   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6517       LD->isNonTemporal())
6518     return false;
6519   if (LD->getMemoryVT() != MemVT)
6520     return false;
6521 
6522   RLI.Ptr = LD->getBasePtr();
6523   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6524     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6525            "Non-pre-inc AM on PPC?");
6526     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6527                           LD->getOffset());
6528   }
6529 
6530   RLI.Chain = LD->getChain();
6531   RLI.MPI = LD->getPointerInfo();
6532   RLI.IsDereferenceable = LD->isDereferenceable();
6533   RLI.IsInvariant = LD->isInvariant();
6534   RLI.Alignment = LD->getAlignment();
6535   RLI.AAInfo = LD->getAAInfo();
6536   RLI.Ranges = LD->getRanges();
6537 
6538   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6539   return true;
6540 }
6541 
6542 // Given the head of the old chain, ResChain, insert a token factor containing
6543 // it and NewResChain, and make users of ResChain now be users of that token
6544 // factor.
6545 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6546                                         SDValue NewResChain,
6547                                         SelectionDAG &DAG) const {
6548   if (!ResChain)
6549     return;
6550 
6551   SDLoc dl(NewResChain);
6552 
6553   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6554                            NewResChain, DAG.getUNDEF(MVT::Other));
6555   assert(TF.getNode() != NewResChain.getNode() &&
6556          "A new TF really is required here");
6557 
6558   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6559   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6560 }
6561 
6562 /// \brief Analyze profitability of direct move
6563 /// prefer float load to int load plus direct move
6564 /// when there is no integer use of int load
6565 static bool directMoveIsProfitable(const SDValue &Op) {
6566   SDNode *Origin = Op.getOperand(0).getNode();
6567   if (Origin->getOpcode() != ISD::LOAD)
6568     return true;
6569 
6570   for (SDNode::use_iterator UI = Origin->use_begin(),
6571                             UE = Origin->use_end();
6572        UI != UE; ++UI) {
6573 
6574     // Only look at the users of the loaded value.
6575     if (UI.getUse().get().getResNo() != 0)
6576       continue;
6577 
6578     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6579         UI->getOpcode() != ISD::UINT_TO_FP)
6580       return true;
6581   }
6582 
6583   return false;
6584 }
6585 
6586 /// \brief Custom lowers integer to floating point conversions to use
6587 /// the direct move instructions available in ISA 2.07 to avoid the
6588 /// need for load/store combinations.
6589 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6590                                                     SelectionDAG &DAG,
6591                                                     const SDLoc &dl) const {
6592   assert((Op.getValueType() == MVT::f32 ||
6593           Op.getValueType() == MVT::f64) &&
6594          "Invalid floating point type as target of conversion");
6595   assert(Subtarget.hasFPCVT() &&
6596          "Int to FP conversions with direct moves require FPCVT");
6597   SDValue FP;
6598   SDValue Src = Op.getOperand(0);
6599   bool SinglePrec = Op.getValueType() == MVT::f32;
6600   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6601   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6602   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6603                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6604 
6605   if (WordInt) {
6606     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6607                      dl, MVT::f64, Src);
6608     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6609   }
6610   else {
6611     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6612     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6613   }
6614 
6615   return FP;
6616 }
6617 
6618 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6619                                           SelectionDAG &DAG) const {
6620   SDLoc dl(Op);
6621 
6622   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6623     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6624       return SDValue();
6625 
6626     SDValue Value = Op.getOperand(0);
6627     // The values are now known to be -1 (false) or 1 (true). To convert this
6628     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6629     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6630     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6631 
6632     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6633 
6634     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6635 
6636     if (Op.getValueType() != MVT::v4f64)
6637       Value = DAG.getNode(ISD::FP_ROUND, dl,
6638                           Op.getValueType(), Value,
6639                           DAG.getIntPtrConstant(1, dl));
6640     return Value;
6641   }
6642 
6643   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6644   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6645     return SDValue();
6646 
6647   if (Op.getOperand(0).getValueType() == MVT::i1)
6648     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6649                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6650                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6651 
6652   // If we have direct moves, we can do all the conversion, skip the store/load
6653   // however, without FPCVT we can't do most conversions.
6654   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6655       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6656     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6657 
6658   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6659          "UINT_TO_FP is supported only with FPCVT");
6660 
6661   // If we have FCFIDS, then use it when converting to single-precision.
6662   // Otherwise, convert to double-precision and then round.
6663   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6664                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6665                                                             : PPCISD::FCFIDS)
6666                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6667                                                             : PPCISD::FCFID);
6668   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6669                   ? MVT::f32
6670                   : MVT::f64;
6671 
6672   if (Op.getOperand(0).getValueType() == MVT::i64) {
6673     SDValue SINT = Op.getOperand(0);
6674     // When converting to single-precision, we actually need to convert
6675     // to double-precision first and then round to single-precision.
6676     // To avoid double-rounding effects during that operation, we have
6677     // to prepare the input operand.  Bits that might be truncated when
6678     // converting to double-precision are replaced by a bit that won't
6679     // be lost at this stage, but is below the single-precision rounding
6680     // position.
6681     //
6682     // However, if -enable-unsafe-fp-math is in effect, accept double
6683     // rounding to avoid the extra overhead.
6684     if (Op.getValueType() == MVT::f32 &&
6685         !Subtarget.hasFPCVT() &&
6686         !DAG.getTarget().Options.UnsafeFPMath) {
6687 
6688       // Twiddle input to make sure the low 11 bits are zero.  (If this
6689       // is the case, we are guaranteed the value will fit into the 53 bit
6690       // mantissa of an IEEE double-precision value without rounding.)
6691       // If any of those low 11 bits were not zero originally, make sure
6692       // bit 12 (value 2048) is set instead, so that the final rounding
6693       // to single-precision gets the correct result.
6694       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6695                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6696       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6697                           Round, DAG.getConstant(2047, dl, MVT::i64));
6698       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6699       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6700                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6701 
6702       // However, we cannot use that value unconditionally: if the magnitude
6703       // of the input value is small, the bit-twiddling we did above might
6704       // end up visibly changing the output.  Fortunately, in that case, we
6705       // don't need to twiddle bits since the original input will convert
6706       // exactly to double-precision floating-point already.  Therefore,
6707       // construct a conditional to use the original value if the top 11
6708       // bits are all sign-bit copies, and use the rounded value computed
6709       // above otherwise.
6710       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6711                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6712       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6713                          Cond, DAG.getConstant(1, dl, MVT::i64));
6714       Cond = DAG.getSetCC(dl, MVT::i32,
6715                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6716 
6717       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6718     }
6719 
6720     ReuseLoadInfo RLI;
6721     SDValue Bits;
6722 
6723     MachineFunction &MF = DAG.getMachineFunction();
6724     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6725       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6726                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6727       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6728     } else if (Subtarget.hasLFIWAX() &&
6729                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6730       MachineMemOperand *MMO =
6731         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6732                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6733       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6734       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6735                                      DAG.getVTList(MVT::f64, MVT::Other),
6736                                      Ops, MVT::i32, MMO);
6737       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6738     } else if (Subtarget.hasFPCVT() &&
6739                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6740       MachineMemOperand *MMO =
6741         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6742                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6743       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6744       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6745                                      DAG.getVTList(MVT::f64, MVT::Other),
6746                                      Ops, MVT::i32, MMO);
6747       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6748     } else if (((Subtarget.hasLFIWAX() &&
6749                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6750                 (Subtarget.hasFPCVT() &&
6751                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6752                SINT.getOperand(0).getValueType() == MVT::i32) {
6753       MachineFrameInfo &MFI = MF.getFrameInfo();
6754       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6755 
6756       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6757       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6758 
6759       SDValue Store =
6760           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6761                        MachinePointerInfo::getFixedStack(
6762                            DAG.getMachineFunction(), FrameIdx));
6763 
6764       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6765              "Expected an i32 store");
6766 
6767       RLI.Ptr = FIdx;
6768       RLI.Chain = Store;
6769       RLI.MPI =
6770           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6771       RLI.Alignment = 4;
6772 
6773       MachineMemOperand *MMO =
6774         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6775                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6776       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6777       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6778                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6779                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6780                                      Ops, MVT::i32, MMO);
6781     } else
6782       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6783 
6784     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6785 
6786     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6787       FP = DAG.getNode(ISD::FP_ROUND, dl,
6788                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6789     return FP;
6790   }
6791 
6792   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6793          "Unhandled INT_TO_FP type in custom expander!");
6794   // Since we only generate this in 64-bit mode, we can take advantage of
6795   // 64-bit registers.  In particular, sign extend the input value into the
6796   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6797   // then lfd it and fcfid it.
6798   MachineFunction &MF = DAG.getMachineFunction();
6799   MachineFrameInfo &MFI = MF.getFrameInfo();
6800   EVT PtrVT = getPointerTy(MF.getDataLayout());
6801 
6802   SDValue Ld;
6803   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6804     ReuseLoadInfo RLI;
6805     bool ReusingLoad;
6806     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6807                                             DAG))) {
6808       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6809       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6810 
6811       SDValue Store =
6812           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6813                        MachinePointerInfo::getFixedStack(
6814                            DAG.getMachineFunction(), FrameIdx));
6815 
6816       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6817              "Expected an i32 store");
6818 
6819       RLI.Ptr = FIdx;
6820       RLI.Chain = Store;
6821       RLI.MPI =
6822           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6823       RLI.Alignment = 4;
6824     }
6825 
6826     MachineMemOperand *MMO =
6827       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6828                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6829     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6830     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6831                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6832                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6833                                  Ops, MVT::i32, MMO);
6834     if (ReusingLoad)
6835       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6836   } else {
6837     assert(Subtarget.isPPC64() &&
6838            "i32->FP without LFIWAX supported only on PPC64");
6839 
6840     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6841     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6842 
6843     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6844                                 Op.getOperand(0));
6845 
6846     // STD the extended value into the stack slot.
6847     SDValue Store = DAG.getStore(
6848         DAG.getEntryNode(), dl, Ext64, FIdx,
6849         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6850 
6851     // Load the value as a double.
6852     Ld = DAG.getLoad(
6853         MVT::f64, dl, Store, FIdx,
6854         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6855   }
6856 
6857   // FCFID it and return it.
6858   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6859   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6860     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6861                      DAG.getIntPtrConstant(0, dl));
6862   return FP;
6863 }
6864 
6865 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6866                                             SelectionDAG &DAG) const {
6867   SDLoc dl(Op);
6868   /*
6869    The rounding mode is in bits 30:31 of FPSR, and has the following
6870    settings:
6871      00 Round to nearest
6872      01 Round to 0
6873      10 Round to +inf
6874      11 Round to -inf
6875 
6876   FLT_ROUNDS, on the other hand, expects the following:
6877     -1 Undefined
6878      0 Round to 0
6879      1 Round to nearest
6880      2 Round to +inf
6881      3 Round to -inf
6882 
6883   To perform the conversion, we do:
6884     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6885   */
6886 
6887   MachineFunction &MF = DAG.getMachineFunction();
6888   EVT VT = Op.getValueType();
6889   EVT PtrVT = getPointerTy(MF.getDataLayout());
6890 
6891   // Save FP Control Word to register
6892   EVT NodeTys[] = {
6893     MVT::f64,    // return register
6894     MVT::Glue    // unused in this context
6895   };
6896   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6897 
6898   // Save FP register to stack slot
6899   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
6900   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6901   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
6902                                MachinePointerInfo());
6903 
6904   // Load FP Control Word from low 32 bits of stack slot.
6905   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6906   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6907   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
6908 
6909   // Transform as necessary
6910   SDValue CWD1 =
6911     DAG.getNode(ISD::AND, dl, MVT::i32,
6912                 CWD, DAG.getConstant(3, dl, MVT::i32));
6913   SDValue CWD2 =
6914     DAG.getNode(ISD::SRL, dl, MVT::i32,
6915                 DAG.getNode(ISD::AND, dl, MVT::i32,
6916                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6917                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6918                             DAG.getConstant(3, dl, MVT::i32)),
6919                 DAG.getConstant(1, dl, MVT::i32));
6920 
6921   SDValue RetVal =
6922     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6923 
6924   return DAG.getNode((VT.getSizeInBits() < 16 ?
6925                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6926 }
6927 
6928 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6929   EVT VT = Op.getValueType();
6930   unsigned BitWidth = VT.getSizeInBits();
6931   SDLoc dl(Op);
6932   assert(Op.getNumOperands() == 3 &&
6933          VT == Op.getOperand(1).getValueType() &&
6934          "Unexpected SHL!");
6935 
6936   // Expand into a bunch of logical ops.  Note that these ops
6937   // depend on the PPC behavior for oversized shift amounts.
6938   SDValue Lo = Op.getOperand(0);
6939   SDValue Hi = Op.getOperand(1);
6940   SDValue Amt = Op.getOperand(2);
6941   EVT AmtVT = Amt.getValueType();
6942 
6943   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6944                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6945   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6946   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6947   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6948   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6949                              DAG.getConstant(-BitWidth, dl, AmtVT));
6950   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6951   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6952   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6953   SDValue OutOps[] = { OutLo, OutHi };
6954   return DAG.getMergeValues(OutOps, dl);
6955 }
6956 
6957 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6958   EVT VT = Op.getValueType();
6959   SDLoc dl(Op);
6960   unsigned BitWidth = VT.getSizeInBits();
6961   assert(Op.getNumOperands() == 3 &&
6962          VT == Op.getOperand(1).getValueType() &&
6963          "Unexpected SRL!");
6964 
6965   // Expand into a bunch of logical ops.  Note that these ops
6966   // depend on the PPC behavior for oversized shift amounts.
6967   SDValue Lo = Op.getOperand(0);
6968   SDValue Hi = Op.getOperand(1);
6969   SDValue Amt = Op.getOperand(2);
6970   EVT AmtVT = Amt.getValueType();
6971 
6972   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6973                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6974   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6975   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6976   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6977   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6978                              DAG.getConstant(-BitWidth, dl, AmtVT));
6979   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6980   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6981   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6982   SDValue OutOps[] = { OutLo, OutHi };
6983   return DAG.getMergeValues(OutOps, dl);
6984 }
6985 
6986 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6987   SDLoc dl(Op);
6988   EVT VT = Op.getValueType();
6989   unsigned BitWidth = VT.getSizeInBits();
6990   assert(Op.getNumOperands() == 3 &&
6991          VT == Op.getOperand(1).getValueType() &&
6992          "Unexpected SRA!");
6993 
6994   // Expand into a bunch of logical ops, followed by a select_cc.
6995   SDValue Lo = Op.getOperand(0);
6996   SDValue Hi = Op.getOperand(1);
6997   SDValue Amt = Op.getOperand(2);
6998   EVT AmtVT = Amt.getValueType();
6999 
7000   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7001                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7002   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7003   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7004   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7005   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7006                              DAG.getConstant(-BitWidth, dl, AmtVT));
7007   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7008   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7009   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7010                                   Tmp4, Tmp6, ISD::SETLE);
7011   SDValue OutOps[] = { OutLo, OutHi };
7012   return DAG.getMergeValues(OutOps, dl);
7013 }
7014 
7015 //===----------------------------------------------------------------------===//
7016 // Vector related lowering.
7017 //
7018 
7019 /// BuildSplatI - Build a canonical splati of Val with an element size of
7020 /// SplatSize.  Cast the result to VT.
7021 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7022                            SelectionDAG &DAG, const SDLoc &dl) {
7023   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7024 
7025   static const MVT VTys[] = { // canonical VT to use for each size.
7026     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7027   };
7028 
7029   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7030 
7031   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7032   if (Val == -1)
7033     SplatSize = 1;
7034 
7035   EVT CanonicalVT = VTys[SplatSize-1];
7036 
7037   // Build a canonical splat for this value.
7038   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7039 }
7040 
7041 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7042 /// specified intrinsic ID.
7043 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7044                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7045   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7046   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7047                      DAG.getConstant(IID, dl, MVT::i32), Op);
7048 }
7049 
7050 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7051 /// specified intrinsic ID.
7052 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7053                                 SelectionDAG &DAG, const SDLoc &dl,
7054                                 EVT DestVT = MVT::Other) {
7055   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7056   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7057                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7058 }
7059 
7060 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7061 /// specified intrinsic ID.
7062 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7063                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7064                                 EVT DestVT = MVT::Other) {
7065   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7066   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7067                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7068 }
7069 
7070 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7071 /// amount.  The result has the specified value type.
7072 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7073                            SelectionDAG &DAG, const SDLoc &dl) {
7074   // Force LHS/RHS to be the right type.
7075   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7076   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7077 
7078   int Ops[16];
7079   for (unsigned i = 0; i != 16; ++i)
7080     Ops[i] = i + Amt;
7081   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7082   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7083 }
7084 
7085 static bool isNonConstSplatBV(BuildVectorSDNode *BVN, EVT Type) {
7086   if (BVN->getValueType(0) != Type)
7087     return false;
7088   auto OpZero = BVN->getOperand(0);
7089   for (int i = 1, e = BVN->getNumOperands(); i < e; i++)
7090     if (BVN->getOperand(i) != OpZero)
7091       return false;
7092   return true;
7093 }
7094 
7095 // If this is a case we can't handle, return null and let the default
7096 // expansion code take care of it.  If we CAN select this case, and if it
7097 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7098 // this case more efficiently than a constant pool load, lower it to the
7099 // sequence of ops that should be used.
7100 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7101                                              SelectionDAG &DAG) const {
7102   SDLoc dl(Op);
7103   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7104   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7105 
7106   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7107     // We first build an i32 vector, load it into a QPX register,
7108     // then convert it to a floating-point vector and compare it
7109     // to a zero vector to get the boolean result.
7110     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7111     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7112     MachinePointerInfo PtrInfo =
7113         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7114     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7115     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7116 
7117     assert(BVN->getNumOperands() == 4 &&
7118       "BUILD_VECTOR for v4i1 does not have 4 operands");
7119 
7120     bool IsConst = true;
7121     for (unsigned i = 0; i < 4; ++i) {
7122       if (BVN->getOperand(i).isUndef()) continue;
7123       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7124         IsConst = false;
7125         break;
7126       }
7127     }
7128 
7129     if (IsConst) {
7130       Constant *One =
7131         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7132       Constant *NegOne =
7133         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7134 
7135       Constant *CV[4];
7136       for (unsigned i = 0; i < 4; ++i) {
7137         if (BVN->getOperand(i).isUndef())
7138           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7139         else if (isNullConstant(BVN->getOperand(i)))
7140           CV[i] = NegOne;
7141         else
7142           CV[i] = One;
7143       }
7144 
7145       Constant *CP = ConstantVector::get(CV);
7146       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7147                                           16 /* alignment */);
7148 
7149       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7150       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7151       return DAG.getMemIntrinsicNode(
7152           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7153           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7154     }
7155 
7156     SmallVector<SDValue, 4> Stores;
7157     for (unsigned i = 0; i < 4; ++i) {
7158       if (BVN->getOperand(i).isUndef()) continue;
7159 
7160       unsigned Offset = 4*i;
7161       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7162       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7163 
7164       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7165       if (StoreSize > 4) {
7166         Stores.push_back(
7167             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7168                               PtrInfo.getWithOffset(Offset), MVT::i32));
7169       } else {
7170         SDValue StoreValue = BVN->getOperand(i);
7171         if (StoreSize < 4)
7172           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7173 
7174         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7175                                       PtrInfo.getWithOffset(Offset)));
7176       }
7177     }
7178 
7179     SDValue StoreChain;
7180     if (!Stores.empty())
7181       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7182     else
7183       StoreChain = DAG.getEntryNode();
7184 
7185     // Now load from v4i32 into the QPX register; this will extend it to
7186     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7187     // is typed as v4f64 because the QPX register integer states are not
7188     // explicitly represented.
7189 
7190     SDValue Ops[] = {StoreChain,
7191                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7192                      FIdx};
7193     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7194 
7195     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7196       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7197     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7198       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7199       LoadedVect);
7200 
7201     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7202 
7203     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7204   }
7205 
7206   // All other QPX vectors are handled by generic code.
7207   if (Subtarget.hasQPX())
7208     return SDValue();
7209 
7210   // Check if this is a splat of a constant value.
7211   APInt APSplatBits, APSplatUndef;
7212   unsigned SplatBitSize;
7213   bool HasAnyUndefs;
7214   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7215                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7216       SplatBitSize > 32) {
7217     // We can splat a non-const value on CPU's that implement ISA 3.0
7218     // in two ways: LXVWSX (load and splat) and MTVSRWS(move and splat).
7219     auto OpZero = BVN->getOperand(0);
7220     bool CanLoadAndSplat = OpZero.getOpcode() == ISD::LOAD &&
7221       BVN->isOnlyUserOf(OpZero.getNode());
7222     if (Subtarget.isISA3_0() &&
7223         isNonConstSplatBV(BVN, MVT::v4i32) && !CanLoadAndSplat)
7224       return Op;
7225     return SDValue();
7226   }
7227 
7228   unsigned SplatBits = APSplatBits.getZExtValue();
7229   unsigned SplatUndef = APSplatUndef.getZExtValue();
7230   unsigned SplatSize = SplatBitSize / 8;
7231 
7232   // First, handle single instruction cases.
7233 
7234   // All zeros?
7235   if (SplatBits == 0) {
7236     // Canonicalize all zero vectors to be v4i32.
7237     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7238       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7239       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7240     }
7241     return Op;
7242   }
7243 
7244   // We have XXSPLTIB for constant splats one byte wide
7245   if (Subtarget.isISA3_0() && Op.getValueType() == MVT::v16i8)
7246     return Op;
7247 
7248   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7249   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7250                     (32-SplatBitSize));
7251   if (SextVal >= -16 && SextVal <= 15)
7252     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7253 
7254   // Two instruction sequences.
7255 
7256   // If this value is in the range [-32,30] and is even, use:
7257   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7258   // If this value is in the range [17,31] and is odd, use:
7259   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7260   // If this value is in the range [-31,-17] and is odd, use:
7261   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7262   // Note the last two are three-instruction sequences.
7263   if (SextVal >= -32 && SextVal <= 31) {
7264     // To avoid having these optimizations undone by constant folding,
7265     // we convert to a pseudo that will be expanded later into one of
7266     // the above forms.
7267     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7268     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7269               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7270     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7271     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7272     if (VT == Op.getValueType())
7273       return RetVal;
7274     else
7275       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7276   }
7277 
7278   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7279   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7280   // for fneg/fabs.
7281   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7282     // Make -1 and vspltisw -1:
7283     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7284 
7285     // Make the VSLW intrinsic, computing 0x8000_0000.
7286     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7287                                    OnesV, DAG, dl);
7288 
7289     // xor by OnesV to invert it.
7290     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7291     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7292   }
7293 
7294   // Check to see if this is a wide variety of vsplti*, binop self cases.
7295   static const signed char SplatCsts[] = {
7296     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7297     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7298   };
7299 
7300   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7301     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7302     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7303     int i = SplatCsts[idx];
7304 
7305     // Figure out what shift amount will be used by altivec if shifted by i in
7306     // this splat size.
7307     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7308 
7309     // vsplti + shl self.
7310     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7311       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7312       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7313         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7314         Intrinsic::ppc_altivec_vslw
7315       };
7316       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7317       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7318     }
7319 
7320     // vsplti + srl self.
7321     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7322       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7323       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7324         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7325         Intrinsic::ppc_altivec_vsrw
7326       };
7327       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7328       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7329     }
7330 
7331     // vsplti + sra self.
7332     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7333       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7334       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7335         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7336         Intrinsic::ppc_altivec_vsraw
7337       };
7338       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7339       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7340     }
7341 
7342     // vsplti + rol self.
7343     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7344                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7345       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7346       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7347         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7348         Intrinsic::ppc_altivec_vrlw
7349       };
7350       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7351       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7352     }
7353 
7354     // t = vsplti c, result = vsldoi t, t, 1
7355     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7356       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7357       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7358       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7359     }
7360     // t = vsplti c, result = vsldoi t, t, 2
7361     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7362       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7363       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7364       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7365     }
7366     // t = vsplti c, result = vsldoi t, t, 3
7367     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7368       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7369       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7370       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7371     }
7372   }
7373 
7374   return SDValue();
7375 }
7376 
7377 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7378 /// the specified operations to build the shuffle.
7379 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7380                                       SDValue RHS, SelectionDAG &DAG,
7381                                       const SDLoc &dl) {
7382   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7383   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7384   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7385 
7386   enum {
7387     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7388     OP_VMRGHW,
7389     OP_VMRGLW,
7390     OP_VSPLTISW0,
7391     OP_VSPLTISW1,
7392     OP_VSPLTISW2,
7393     OP_VSPLTISW3,
7394     OP_VSLDOI4,
7395     OP_VSLDOI8,
7396     OP_VSLDOI12
7397   };
7398 
7399   if (OpNum == OP_COPY) {
7400     if (LHSID == (1*9+2)*9+3) return LHS;
7401     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7402     return RHS;
7403   }
7404 
7405   SDValue OpLHS, OpRHS;
7406   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7407   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7408 
7409   int ShufIdxs[16];
7410   switch (OpNum) {
7411   default: llvm_unreachable("Unknown i32 permute!");
7412   case OP_VMRGHW:
7413     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7414     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7415     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7416     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7417     break;
7418   case OP_VMRGLW:
7419     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7420     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7421     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7422     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7423     break;
7424   case OP_VSPLTISW0:
7425     for (unsigned i = 0; i != 16; ++i)
7426       ShufIdxs[i] = (i&3)+0;
7427     break;
7428   case OP_VSPLTISW1:
7429     for (unsigned i = 0; i != 16; ++i)
7430       ShufIdxs[i] = (i&3)+4;
7431     break;
7432   case OP_VSPLTISW2:
7433     for (unsigned i = 0; i != 16; ++i)
7434       ShufIdxs[i] = (i&3)+8;
7435     break;
7436   case OP_VSPLTISW3:
7437     for (unsigned i = 0; i != 16; ++i)
7438       ShufIdxs[i] = (i&3)+12;
7439     break;
7440   case OP_VSLDOI4:
7441     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7442   case OP_VSLDOI8:
7443     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7444   case OP_VSLDOI12:
7445     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7446   }
7447   EVT VT = OpLHS.getValueType();
7448   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7449   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7450   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7451   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7452 }
7453 
7454 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7455 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7456 /// return the code it can be lowered into.  Worst case, it can always be
7457 /// lowered into a vperm.
7458 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7459                                                SelectionDAG &DAG) const {
7460   SDLoc dl(Op);
7461   SDValue V1 = Op.getOperand(0);
7462   SDValue V2 = Op.getOperand(1);
7463   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7464   EVT VT = Op.getValueType();
7465   bool isLittleEndian = Subtarget.isLittleEndian();
7466 
7467   unsigned ShiftElts, InsertAtByte;
7468   bool Swap;
7469   if (Subtarget.hasP9Vector() &&
7470       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7471                            isLittleEndian)) {
7472     if (Swap)
7473       std::swap(V1, V2);
7474     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7475     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7476     if (ShiftElts) {
7477       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7478                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7479       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7480                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7481       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7482     }
7483     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7484                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7485     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7486   }
7487 
7488   if (Subtarget.hasVSX()) {
7489     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7490       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7491 
7492       // If the source for the shuffle is a scalar_to_vector that came from a
7493       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7494       if (Subtarget.isISA3_0() &&
7495           ((isLittleEndian && SplatIdx == 3) ||
7496            (!isLittleEndian && SplatIdx == 0))) {
7497         SDValue Src = V1.getOperand(0);
7498         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7499             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7500             Src.getOperand(0).hasOneUse())
7501           return V1;
7502       }
7503       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7504       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7505                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7506       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7507     }
7508 
7509     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7510     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7511       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7512       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7513       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7514     }
7515 
7516   }
7517 
7518   if (Subtarget.hasQPX()) {
7519     if (VT.getVectorNumElements() != 4)
7520       return SDValue();
7521 
7522     if (V2.isUndef()) V2 = V1;
7523 
7524     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7525     if (AlignIdx != -1) {
7526       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7527                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7528     } else if (SVOp->isSplat()) {
7529       int SplatIdx = SVOp->getSplatIndex();
7530       if (SplatIdx >= 4) {
7531         std::swap(V1, V2);
7532         SplatIdx -= 4;
7533       }
7534 
7535       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7536                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7537     }
7538 
7539     // Lower this into a qvgpci/qvfperm pair.
7540 
7541     // Compute the qvgpci literal
7542     unsigned idx = 0;
7543     for (unsigned i = 0; i < 4; ++i) {
7544       int m = SVOp->getMaskElt(i);
7545       unsigned mm = m >= 0 ? (unsigned) m : i;
7546       idx |= mm << (3-i)*3;
7547     }
7548 
7549     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7550                              DAG.getConstant(idx, dl, MVT::i32));
7551     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7552   }
7553 
7554   // Cases that are handled by instructions that take permute immediates
7555   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7556   // selected by the instruction selector.
7557   if (V2.isUndef()) {
7558     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7559         PPC::isSplatShuffleMask(SVOp, 2) ||
7560         PPC::isSplatShuffleMask(SVOp, 4) ||
7561         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7562         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7563         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7564         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7565         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7566         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7567         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7568         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7569         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7570         (Subtarget.hasP8Altivec() && (
7571          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7572          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7573          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7574       return Op;
7575     }
7576   }
7577 
7578   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7579   // and produce a fixed permutation.  If any of these match, do not lower to
7580   // VPERM.
7581   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7582   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7583       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7584       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7585       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7586       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7587       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7588       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7589       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7590       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7591       (Subtarget.hasP8Altivec() && (
7592        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7593        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7594        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7595     return Op;
7596 
7597   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7598   // perfect shuffle table to emit an optimal matching sequence.
7599   ArrayRef<int> PermMask = SVOp->getMask();
7600 
7601   unsigned PFIndexes[4];
7602   bool isFourElementShuffle = true;
7603   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7604     unsigned EltNo = 8;   // Start out undef.
7605     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7606       if (PermMask[i*4+j] < 0)
7607         continue;   // Undef, ignore it.
7608 
7609       unsigned ByteSource = PermMask[i*4+j];
7610       if ((ByteSource & 3) != j) {
7611         isFourElementShuffle = false;
7612         break;
7613       }
7614 
7615       if (EltNo == 8) {
7616         EltNo = ByteSource/4;
7617       } else if (EltNo != ByteSource/4) {
7618         isFourElementShuffle = false;
7619         break;
7620       }
7621     }
7622     PFIndexes[i] = EltNo;
7623   }
7624 
7625   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7626   // perfect shuffle vector to determine if it is cost effective to do this as
7627   // discrete instructions, or whether we should use a vperm.
7628   // For now, we skip this for little endian until such time as we have a
7629   // little-endian perfect shuffle table.
7630   if (isFourElementShuffle && !isLittleEndian) {
7631     // Compute the index in the perfect shuffle table.
7632     unsigned PFTableIndex =
7633       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7634 
7635     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7636     unsigned Cost  = (PFEntry >> 30);
7637 
7638     // Determining when to avoid vperm is tricky.  Many things affect the cost
7639     // of vperm, particularly how many times the perm mask needs to be computed.
7640     // For example, if the perm mask can be hoisted out of a loop or is already
7641     // used (perhaps because there are multiple permutes with the same shuffle
7642     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7643     // the loop requires an extra register.
7644     //
7645     // As a compromise, we only emit discrete instructions if the shuffle can be
7646     // generated in 3 or fewer operations.  When we have loop information
7647     // available, if this block is within a loop, we should avoid using vperm
7648     // for 3-operation perms and use a constant pool load instead.
7649     if (Cost < 3)
7650       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7651   }
7652 
7653   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7654   // vector that will get spilled to the constant pool.
7655   if (V2.isUndef()) V2 = V1;
7656 
7657   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7658   // that it is in input element units, not in bytes.  Convert now.
7659 
7660   // For little endian, the order of the input vectors is reversed, and
7661   // the permutation mask is complemented with respect to 31.  This is
7662   // necessary to produce proper semantics with the big-endian-biased vperm
7663   // instruction.
7664   EVT EltVT = V1.getValueType().getVectorElementType();
7665   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7666 
7667   SmallVector<SDValue, 16> ResultMask;
7668   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7669     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7670 
7671     for (unsigned j = 0; j != BytesPerElement; ++j)
7672       if (isLittleEndian)
7673         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7674                                              dl, MVT::i32));
7675       else
7676         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7677                                              MVT::i32));
7678   }
7679 
7680   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7681   if (isLittleEndian)
7682     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7683                        V2, V1, VPermMask);
7684   else
7685     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7686                        V1, V2, VPermMask);
7687 }
7688 
7689 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7690 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7691 /// information about the intrinsic.
7692 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7693                                  bool &isDot, const PPCSubtarget &Subtarget) {
7694   unsigned IntrinsicID =
7695     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7696   CompareOpc = -1;
7697   isDot = false;
7698   switch (IntrinsicID) {
7699   default: return false;
7700     // Comparison predicates.
7701   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7702   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7703   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7704   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7705   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7706   case Intrinsic::ppc_altivec_vcmpequd_p:
7707     if (Subtarget.hasP8Altivec()) {
7708       CompareOpc = 199;
7709       isDot = 1;
7710     } else
7711       return false;
7712 
7713     break;
7714   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7715   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7716   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7717   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7718   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7719   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7720     if (Subtarget.hasP8Altivec()) {
7721       CompareOpc = 967;
7722       isDot = 1;
7723     } else
7724       return false;
7725 
7726     break;
7727   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7728   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7729   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7730   case Intrinsic::ppc_altivec_vcmpgtud_p:
7731     if (Subtarget.hasP8Altivec()) {
7732       CompareOpc = 711;
7733       isDot = 1;
7734     } else
7735       return false;
7736 
7737     break;
7738     // VSX predicate comparisons use the same infrastructure
7739   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7740   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7741   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7742   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7743   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7744   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7745     if (Subtarget.hasVSX()) {
7746       switch (IntrinsicID) {
7747       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7748       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7749       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7750       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7751       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7752       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7753       }
7754       isDot = 1;
7755     }
7756     else
7757       return false;
7758 
7759     break;
7760 
7761     // Normal Comparisons.
7762   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7763   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7764   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7765   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7766   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7767   case Intrinsic::ppc_altivec_vcmpequd:
7768     if (Subtarget.hasP8Altivec()) {
7769       CompareOpc = 199;
7770       isDot = 0;
7771     } else
7772       return false;
7773 
7774     break;
7775   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7776   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7777   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7778   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7779   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7780   case Intrinsic::ppc_altivec_vcmpgtsd:
7781     if (Subtarget.hasP8Altivec()) {
7782       CompareOpc = 967;
7783       isDot = 0;
7784     } else
7785       return false;
7786 
7787     break;
7788   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7789   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7790   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7791   case Intrinsic::ppc_altivec_vcmpgtud:
7792     if (Subtarget.hasP8Altivec()) {
7793       CompareOpc = 711;
7794       isDot = 0;
7795     } else
7796       return false;
7797 
7798     break;
7799   }
7800   return true;
7801 }
7802 
7803 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7804 /// lower, do it, otherwise return null.
7805 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7806                                                    SelectionDAG &DAG) const {
7807   unsigned IntrinsicID =
7808     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7809 
7810   if (IntrinsicID == Intrinsic::thread_pointer) {
7811     // Reads the thread pointer register, used for __builtin_thread_pointer.
7812     bool is64bit = Subtarget.isPPC64();
7813     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7814                            is64bit ? MVT::i64 : MVT::i32);
7815   }
7816 
7817   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7818   // opcode number of the comparison.
7819   SDLoc dl(Op);
7820   int CompareOpc;
7821   bool isDot;
7822   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7823     return SDValue();    // Don't custom lower most intrinsics.
7824 
7825   // If this is a non-dot comparison, make the VCMP node and we are done.
7826   if (!isDot) {
7827     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7828                               Op.getOperand(1), Op.getOperand(2),
7829                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7830     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7831   }
7832 
7833   // Create the PPCISD altivec 'dot' comparison node.
7834   SDValue Ops[] = {
7835     Op.getOperand(2),  // LHS
7836     Op.getOperand(3),  // RHS
7837     DAG.getConstant(CompareOpc, dl, MVT::i32)
7838   };
7839   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7840   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7841 
7842   // Now that we have the comparison, emit a copy from the CR to a GPR.
7843   // This is flagged to the above dot comparison.
7844   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7845                                 DAG.getRegister(PPC::CR6, MVT::i32),
7846                                 CompNode.getValue(1));
7847 
7848   // Unpack the result based on how the target uses it.
7849   unsigned BitNo;   // Bit # of CR6.
7850   bool InvertBit;   // Invert result?
7851   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7852   default:  // Can't happen, don't crash on invalid number though.
7853   case 0:   // Return the value of the EQ bit of CR6.
7854     BitNo = 0; InvertBit = false;
7855     break;
7856   case 1:   // Return the inverted value of the EQ bit of CR6.
7857     BitNo = 0; InvertBit = true;
7858     break;
7859   case 2:   // Return the value of the LT bit of CR6.
7860     BitNo = 2; InvertBit = false;
7861     break;
7862   case 3:   // Return the inverted value of the LT bit of CR6.
7863     BitNo = 2; InvertBit = true;
7864     break;
7865   }
7866 
7867   // Shift the bit into the low position.
7868   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7869                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7870   // Isolate the bit.
7871   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7872                       DAG.getConstant(1, dl, MVT::i32));
7873 
7874   // If we are supposed to, toggle the bit.
7875   if (InvertBit)
7876     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7877                         DAG.getConstant(1, dl, MVT::i32));
7878   return Flags;
7879 }
7880 
7881 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7882                                                   SelectionDAG &DAG) const {
7883   SDLoc dl(Op);
7884   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7885   // instructions), but for smaller types, we need to first extend up to v2i32
7886   // before doing going farther.
7887   if (Op.getValueType() == MVT::v2i64) {
7888     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7889     if (ExtVT != MVT::v2i32) {
7890       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7891       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7892                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7893                                         ExtVT.getVectorElementType(), 4)));
7894       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7895       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7896                        DAG.getValueType(MVT::v2i32));
7897     }
7898 
7899     return Op;
7900   }
7901 
7902   return SDValue();
7903 }
7904 
7905 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7906                                                    SelectionDAG &DAG) const {
7907   SDLoc dl(Op);
7908   // Create a stack slot that is 16-byte aligned.
7909   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7910   int FrameIdx = MFI.CreateStackObject(16, 16, false);
7911   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7912   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7913 
7914   // Store the input value into Value#0 of the stack slot.
7915   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7916                                MachinePointerInfo());
7917   // Load it out.
7918   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
7919 }
7920 
7921 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7922                                                   SelectionDAG &DAG) const {
7923   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7924          "Should only be called for ISD::INSERT_VECTOR_ELT");
7925   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7926   // We have legal lowering for constant indices but not for variable ones.
7927   if (C)
7928     return Op;
7929   return SDValue();
7930 }
7931 
7932 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7933                                                    SelectionDAG &DAG) const {
7934   SDLoc dl(Op);
7935   SDNode *N = Op.getNode();
7936 
7937   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7938          "Unknown extract_vector_elt type");
7939 
7940   SDValue Value = N->getOperand(0);
7941 
7942   // The first part of this is like the store lowering except that we don't
7943   // need to track the chain.
7944 
7945   // The values are now known to be -1 (false) or 1 (true). To convert this
7946   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7947   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7948   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7949 
7950   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7951   // understand how to form the extending load.
7952   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7953 
7954   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7955 
7956   // Now convert to an integer and store.
7957   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7958     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7959     Value);
7960 
7961   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7962   int FrameIdx = MFI.CreateStackObject(16, 16, false);
7963   MachinePointerInfo PtrInfo =
7964       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7965   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7966   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7967 
7968   SDValue StoreChain = DAG.getEntryNode();
7969   SDValue Ops[] = {StoreChain,
7970                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7971                    Value, FIdx};
7972   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7973 
7974   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7975     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7976 
7977   // Extract the value requested.
7978   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7979   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7980   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7981 
7982   SDValue IntVal =
7983       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
7984 
7985   if (!Subtarget.useCRBits())
7986     return IntVal;
7987 
7988   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7989 }
7990 
7991 /// Lowering for QPX v4i1 loads
7992 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7993                                            SelectionDAG &DAG) const {
7994   SDLoc dl(Op);
7995   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7996   SDValue LoadChain = LN->getChain();
7997   SDValue BasePtr = LN->getBasePtr();
7998 
7999   if (Op.getValueType() == MVT::v4f64 ||
8000       Op.getValueType() == MVT::v4f32) {
8001     EVT MemVT = LN->getMemoryVT();
8002     unsigned Alignment = LN->getAlignment();
8003 
8004     // If this load is properly aligned, then it is legal.
8005     if (Alignment >= MemVT.getStoreSize())
8006       return Op;
8007 
8008     EVT ScalarVT = Op.getValueType().getScalarType(),
8009         ScalarMemVT = MemVT.getScalarType();
8010     unsigned Stride = ScalarMemVT.getStoreSize();
8011 
8012     SDValue Vals[4], LoadChains[4];
8013     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8014       SDValue Load;
8015       if (ScalarVT != ScalarMemVT)
8016         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8017                               BasePtr,
8018                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8019                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8020                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8021       else
8022         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8023                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8024                            MinAlign(Alignment, Idx * Stride),
8025                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8026 
8027       if (Idx == 0 && LN->isIndexed()) {
8028         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8029                "Unknown addressing mode on vector load");
8030         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8031                                   LN->getAddressingMode());
8032       }
8033 
8034       Vals[Idx] = Load;
8035       LoadChains[Idx] = Load.getValue(1);
8036 
8037       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8038                             DAG.getConstant(Stride, dl,
8039                                             BasePtr.getValueType()));
8040     }
8041 
8042     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8043     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8044 
8045     if (LN->isIndexed()) {
8046       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8047       return DAG.getMergeValues(RetOps, dl);
8048     }
8049 
8050     SDValue RetOps[] = { Value, TF };
8051     return DAG.getMergeValues(RetOps, dl);
8052   }
8053 
8054   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8055   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8056 
8057   // To lower v4i1 from a byte array, we load the byte elements of the
8058   // vector and then reuse the BUILD_VECTOR logic.
8059 
8060   SDValue VectElmts[4], VectElmtChains[4];
8061   for (unsigned i = 0; i < 4; ++i) {
8062     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8063     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8064 
8065     VectElmts[i] = DAG.getExtLoad(
8066         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8067         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8068         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8069     VectElmtChains[i] = VectElmts[i].getValue(1);
8070   }
8071 
8072   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8073   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8074 
8075   SDValue RVals[] = { Value, LoadChain };
8076   return DAG.getMergeValues(RVals, dl);
8077 }
8078 
8079 /// Lowering for QPX v4i1 stores
8080 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8081                                             SelectionDAG &DAG) const {
8082   SDLoc dl(Op);
8083   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8084   SDValue StoreChain = SN->getChain();
8085   SDValue BasePtr = SN->getBasePtr();
8086   SDValue Value = SN->getValue();
8087 
8088   if (Value.getValueType() == MVT::v4f64 ||
8089       Value.getValueType() == MVT::v4f32) {
8090     EVT MemVT = SN->getMemoryVT();
8091     unsigned Alignment = SN->getAlignment();
8092 
8093     // If this store is properly aligned, then it is legal.
8094     if (Alignment >= MemVT.getStoreSize())
8095       return Op;
8096 
8097     EVT ScalarVT = Value.getValueType().getScalarType(),
8098         ScalarMemVT = MemVT.getScalarType();
8099     unsigned Stride = ScalarMemVT.getStoreSize();
8100 
8101     SDValue Stores[4];
8102     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8103       SDValue Ex = DAG.getNode(
8104           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8105           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8106       SDValue Store;
8107       if (ScalarVT != ScalarMemVT)
8108         Store =
8109             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8110                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8111                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8112                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8113       else
8114         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8115                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8116                              MinAlign(Alignment, Idx * Stride),
8117                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8118 
8119       if (Idx == 0 && SN->isIndexed()) {
8120         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8121                "Unknown addressing mode on vector store");
8122         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8123                                     SN->getAddressingMode());
8124       }
8125 
8126       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8127                             DAG.getConstant(Stride, dl,
8128                                             BasePtr.getValueType()));
8129       Stores[Idx] = Store;
8130     }
8131 
8132     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8133 
8134     if (SN->isIndexed()) {
8135       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8136       return DAG.getMergeValues(RetOps, dl);
8137     }
8138 
8139     return TF;
8140   }
8141 
8142   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8143   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8144 
8145   // The values are now known to be -1 (false) or 1 (true). To convert this
8146   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8147   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8148   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8149 
8150   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8151   // understand how to form the extending load.
8152   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8153 
8154   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8155 
8156   // Now convert to an integer and store.
8157   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8158     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8159     Value);
8160 
8161   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8162   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8163   MachinePointerInfo PtrInfo =
8164       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8165   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8166   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8167 
8168   SDValue Ops[] = {StoreChain,
8169                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8170                    Value, FIdx};
8171   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8172 
8173   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8174     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8175 
8176   // Move data into the byte array.
8177   SDValue Loads[4], LoadChains[4];
8178   for (unsigned i = 0; i < 4; ++i) {
8179     unsigned Offset = 4*i;
8180     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8181     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8182 
8183     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8184                            PtrInfo.getWithOffset(Offset));
8185     LoadChains[i] = Loads[i].getValue(1);
8186   }
8187 
8188   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8189 
8190   SDValue Stores[4];
8191   for (unsigned i = 0; i < 4; ++i) {
8192     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8193     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8194 
8195     Stores[i] = DAG.getTruncStore(
8196         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8197         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8198         SN->getAAInfo());
8199   }
8200 
8201   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8202 
8203   return StoreChain;
8204 }
8205 
8206 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8207   SDLoc dl(Op);
8208   if (Op.getValueType() == MVT::v4i32) {
8209     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8210 
8211     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8212     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8213 
8214     SDValue RHSSwap =   // = vrlw RHS, 16
8215       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8216 
8217     // Shrinkify inputs to v8i16.
8218     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8219     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8220     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8221 
8222     // Low parts multiplied together, generating 32-bit results (we ignore the
8223     // top parts).
8224     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8225                                         LHS, RHS, DAG, dl, MVT::v4i32);
8226 
8227     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8228                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8229     // Shift the high parts up 16 bits.
8230     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8231                               Neg16, DAG, dl);
8232     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8233   } else if (Op.getValueType() == MVT::v8i16) {
8234     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8235 
8236     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8237 
8238     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8239                             LHS, RHS, Zero, DAG, dl);
8240   } else if (Op.getValueType() == MVT::v16i8) {
8241     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8242     bool isLittleEndian = Subtarget.isLittleEndian();
8243 
8244     // Multiply the even 8-bit parts, producing 16-bit sums.
8245     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8246                                            LHS, RHS, DAG, dl, MVT::v8i16);
8247     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8248 
8249     // Multiply the odd 8-bit parts, producing 16-bit sums.
8250     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8251                                           LHS, RHS, DAG, dl, MVT::v8i16);
8252     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8253 
8254     // Merge the results together.  Because vmuleub and vmuloub are
8255     // instructions with a big-endian bias, we must reverse the
8256     // element numbering and reverse the meaning of "odd" and "even"
8257     // when generating little endian code.
8258     int Ops[16];
8259     for (unsigned i = 0; i != 8; ++i) {
8260       if (isLittleEndian) {
8261         Ops[i*2  ] = 2*i;
8262         Ops[i*2+1] = 2*i+16;
8263       } else {
8264         Ops[i*2  ] = 2*i+1;
8265         Ops[i*2+1] = 2*i+1+16;
8266       }
8267     }
8268     if (isLittleEndian)
8269       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8270     else
8271       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8272   } else {
8273     llvm_unreachable("Unknown mul to lower!");
8274   }
8275 }
8276 
8277 /// LowerOperation - Provide custom lowering hooks for some operations.
8278 ///
8279 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8280   switch (Op.getOpcode()) {
8281   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8282   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8283   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8284   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8285   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8286   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8287   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8288   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8289   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8290   case ISD::VASTART:
8291     return LowerVASTART(Op, DAG);
8292 
8293   case ISD::VAARG:
8294     return LowerVAARG(Op, DAG);
8295 
8296   case ISD::VACOPY:
8297     return LowerVACOPY(Op, DAG);
8298 
8299   case ISD::STACKRESTORE:
8300     return LowerSTACKRESTORE(Op, DAG);
8301 
8302   case ISD::DYNAMIC_STACKALLOC:
8303     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8304 
8305   case ISD::GET_DYNAMIC_AREA_OFFSET:
8306     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8307 
8308   case ISD::EH_DWARF_CFA:
8309     return LowerEH_DWARF_CFA(Op, DAG);
8310 
8311   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8312   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8313 
8314   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8315   case ISD::STORE:              return LowerSTORE(Op, DAG);
8316   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8317   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8318   case ISD::FP_TO_UINT:
8319   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8320                                                       SDLoc(Op));
8321   case ISD::UINT_TO_FP:
8322   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8323   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8324 
8325   // Lower 64-bit shifts.
8326   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8327   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8328   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8329 
8330   // Vector-related lowering.
8331   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8332   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8333   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8334   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8335   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8336   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8337   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8338   case ISD::MUL:                return LowerMUL(Op, DAG);
8339 
8340   // For counter-based loop handling.
8341   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8342 
8343   // Frame & Return address.
8344   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8345   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8346   }
8347 }
8348 
8349 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8350                                            SmallVectorImpl<SDValue>&Results,
8351                                            SelectionDAG &DAG) const {
8352   SDLoc dl(N);
8353   switch (N->getOpcode()) {
8354   default:
8355     llvm_unreachable("Do not know how to custom type legalize this operation!");
8356   case ISD::READCYCLECOUNTER: {
8357     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8358     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8359 
8360     Results.push_back(RTB);
8361     Results.push_back(RTB.getValue(1));
8362     Results.push_back(RTB.getValue(2));
8363     break;
8364   }
8365   case ISD::INTRINSIC_W_CHAIN: {
8366     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8367         Intrinsic::ppc_is_decremented_ctr_nonzero)
8368       break;
8369 
8370     assert(N->getValueType(0) == MVT::i1 &&
8371            "Unexpected result type for CTR decrement intrinsic");
8372     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8373                                  N->getValueType(0));
8374     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8375     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8376                                  N->getOperand(1));
8377 
8378     Results.push_back(NewInt);
8379     Results.push_back(NewInt.getValue(1));
8380     break;
8381   }
8382   case ISD::VAARG: {
8383     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8384       return;
8385 
8386     EVT VT = N->getValueType(0);
8387 
8388     if (VT == MVT::i64) {
8389       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8390 
8391       Results.push_back(NewNode);
8392       Results.push_back(NewNode.getValue(1));
8393     }
8394     return;
8395   }
8396   case ISD::FP_ROUND_INREG: {
8397     assert(N->getValueType(0) == MVT::ppcf128);
8398     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8399     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8400                              MVT::f64, N->getOperand(0),
8401                              DAG.getIntPtrConstant(0, dl));
8402     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8403                              MVT::f64, N->getOperand(0),
8404                              DAG.getIntPtrConstant(1, dl));
8405 
8406     // Add the two halves of the long double in round-to-zero mode.
8407     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8408 
8409     // We know the low half is about to be thrown away, so just use something
8410     // convenient.
8411     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8412                                 FPreg, FPreg));
8413     return;
8414   }
8415   case ISD::FP_TO_SINT:
8416   case ISD::FP_TO_UINT:
8417     // LowerFP_TO_INT() can only handle f32 and f64.
8418     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8419       return;
8420     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8421     return;
8422   }
8423 }
8424 
8425 //===----------------------------------------------------------------------===//
8426 //  Other Lowering Code
8427 //===----------------------------------------------------------------------===//
8428 
8429 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8430   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8431   Function *Func = Intrinsic::getDeclaration(M, Id);
8432   return Builder.CreateCall(Func, {});
8433 }
8434 
8435 // The mappings for emitLeading/TrailingFence is taken from
8436 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8437 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8438                                          AtomicOrdering Ord, bool IsStore,
8439                                          bool IsLoad) const {
8440   if (Ord == AtomicOrdering::SequentiallyConsistent)
8441     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8442   if (isReleaseOrStronger(Ord))
8443     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8444   return nullptr;
8445 }
8446 
8447 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8448                                           AtomicOrdering Ord, bool IsStore,
8449                                           bool IsLoad) const {
8450   if (IsLoad && isAcquireOrStronger(Ord))
8451     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8452   // FIXME: this is too conservative, a dependent branch + isync is enough.
8453   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8454   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8455   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8456   return nullptr;
8457 }
8458 
8459 MachineBasicBlock *
8460 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8461                                     unsigned AtomicSize,
8462                                     unsigned BinOpcode,
8463                                     unsigned CmpOpcode,
8464                                     unsigned CmpPred) const {
8465   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8466   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8467 
8468   auto LoadMnemonic = PPC::LDARX;
8469   auto StoreMnemonic = PPC::STDCX;
8470   switch (AtomicSize) {
8471   default:
8472     llvm_unreachable("Unexpected size of atomic entity");
8473   case 1:
8474     LoadMnemonic = PPC::LBARX;
8475     StoreMnemonic = PPC::STBCX;
8476     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8477     break;
8478   case 2:
8479     LoadMnemonic = PPC::LHARX;
8480     StoreMnemonic = PPC::STHCX;
8481     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8482     break;
8483   case 4:
8484     LoadMnemonic = PPC::LWARX;
8485     StoreMnemonic = PPC::STWCX;
8486     break;
8487   case 8:
8488     LoadMnemonic = PPC::LDARX;
8489     StoreMnemonic = PPC::STDCX;
8490     break;
8491   }
8492 
8493   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8494   MachineFunction *F = BB->getParent();
8495   MachineFunction::iterator It = ++BB->getIterator();
8496 
8497   unsigned dest = MI.getOperand(0).getReg();
8498   unsigned ptrA = MI.getOperand(1).getReg();
8499   unsigned ptrB = MI.getOperand(2).getReg();
8500   unsigned incr = MI.getOperand(3).getReg();
8501   DebugLoc dl = MI.getDebugLoc();
8502 
8503   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8504   MachineBasicBlock *loop2MBB =
8505     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8506   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8507   F->insert(It, loopMBB);
8508   if (CmpOpcode)
8509     F->insert(It, loop2MBB);
8510   F->insert(It, exitMBB);
8511   exitMBB->splice(exitMBB->begin(), BB,
8512                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8513   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8514 
8515   MachineRegisterInfo &RegInfo = F->getRegInfo();
8516   unsigned TmpReg = (!BinOpcode) ? incr :
8517     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8518                                            : &PPC::GPRCRegClass);
8519 
8520   //  thisMBB:
8521   //   ...
8522   //   fallthrough --> loopMBB
8523   BB->addSuccessor(loopMBB);
8524 
8525   //  loopMBB:
8526   //   l[wd]arx dest, ptr
8527   //   add r0, dest, incr
8528   //   st[wd]cx. r0, ptr
8529   //   bne- loopMBB
8530   //   fallthrough --> exitMBB
8531 
8532   // For max/min...
8533   //  loopMBB:
8534   //   l[wd]arx dest, ptr
8535   //   cmpl?[wd] incr, dest
8536   //   bgt exitMBB
8537   //  loop2MBB:
8538   //   st[wd]cx. dest, ptr
8539   //   bne- loopMBB
8540   //   fallthrough --> exitMBB
8541 
8542   BB = loopMBB;
8543   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8544     .addReg(ptrA).addReg(ptrB);
8545   if (BinOpcode)
8546     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8547   if (CmpOpcode) {
8548     // Signed comparisons of byte or halfword values must be sign-extended.
8549     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8550       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8551       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8552               ExtReg).addReg(dest);
8553       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8554         .addReg(incr).addReg(ExtReg);
8555     } else
8556       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8557         .addReg(incr).addReg(dest);
8558 
8559     BuildMI(BB, dl, TII->get(PPC::BCC))
8560       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8561     BB->addSuccessor(loop2MBB);
8562     BB->addSuccessor(exitMBB);
8563     BB = loop2MBB;
8564   }
8565   BuildMI(BB, dl, TII->get(StoreMnemonic))
8566     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8567   BuildMI(BB, dl, TII->get(PPC::BCC))
8568     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8569   BB->addSuccessor(loopMBB);
8570   BB->addSuccessor(exitMBB);
8571 
8572   //  exitMBB:
8573   //   ...
8574   BB = exitMBB;
8575   return BB;
8576 }
8577 
8578 MachineBasicBlock *
8579 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8580                                             MachineBasicBlock *BB,
8581                                             bool is8bit, // operation
8582                                             unsigned BinOpcode,
8583                                             unsigned CmpOpcode,
8584                                             unsigned CmpPred) const {
8585   // If we support part-word atomic mnemonics, just use them
8586   if (Subtarget.hasPartwordAtomics())
8587     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8588                             CmpOpcode, CmpPred);
8589 
8590   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8591   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8592   // In 64 bit mode we have to use 64 bits for addresses, even though the
8593   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8594   // registers without caring whether they're 32 or 64, but here we're
8595   // doing actual arithmetic on the addresses.
8596   bool is64bit = Subtarget.isPPC64();
8597   bool isLittleEndian = Subtarget.isLittleEndian();
8598   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8599 
8600   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8601   MachineFunction *F = BB->getParent();
8602   MachineFunction::iterator It = ++BB->getIterator();
8603 
8604   unsigned dest = MI.getOperand(0).getReg();
8605   unsigned ptrA = MI.getOperand(1).getReg();
8606   unsigned ptrB = MI.getOperand(2).getReg();
8607   unsigned incr = MI.getOperand(3).getReg();
8608   DebugLoc dl = MI.getDebugLoc();
8609 
8610   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8611   MachineBasicBlock *loop2MBB =
8612     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8613   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8614   F->insert(It, loopMBB);
8615   if (CmpOpcode)
8616     F->insert(It, loop2MBB);
8617   F->insert(It, exitMBB);
8618   exitMBB->splice(exitMBB->begin(), BB,
8619                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8620   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8621 
8622   MachineRegisterInfo &RegInfo = F->getRegInfo();
8623   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8624                                           : &PPC::GPRCRegClass;
8625   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8626   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8627   unsigned ShiftReg =
8628     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8629   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8630   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8631   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8632   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8633   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8634   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8635   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8636   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8637   unsigned Ptr1Reg;
8638   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8639 
8640   //  thisMBB:
8641   //   ...
8642   //   fallthrough --> loopMBB
8643   BB->addSuccessor(loopMBB);
8644 
8645   // The 4-byte load must be aligned, while a char or short may be
8646   // anywhere in the word.  Hence all this nasty bookkeeping code.
8647   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8648   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8649   //   xori shift, shift1, 24 [16]
8650   //   rlwinm ptr, ptr1, 0, 0, 29
8651   //   slw incr2, incr, shift
8652   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8653   //   slw mask, mask2, shift
8654   //  loopMBB:
8655   //   lwarx tmpDest, ptr
8656   //   add tmp, tmpDest, incr2
8657   //   andc tmp2, tmpDest, mask
8658   //   and tmp3, tmp, mask
8659   //   or tmp4, tmp3, tmp2
8660   //   stwcx. tmp4, ptr
8661   //   bne- loopMBB
8662   //   fallthrough --> exitMBB
8663   //   srw dest, tmpDest, shift
8664   if (ptrA != ZeroReg) {
8665     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8666     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8667       .addReg(ptrA).addReg(ptrB);
8668   } else {
8669     Ptr1Reg = ptrB;
8670   }
8671   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8672       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8673   if (!isLittleEndian)
8674     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8675         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8676   if (is64bit)
8677     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8678       .addReg(Ptr1Reg).addImm(0).addImm(61);
8679   else
8680     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8681       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8682   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8683       .addReg(incr).addReg(ShiftReg);
8684   if (is8bit)
8685     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8686   else {
8687     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8688     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8689   }
8690   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8691       .addReg(Mask2Reg).addReg(ShiftReg);
8692 
8693   BB = loopMBB;
8694   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8695     .addReg(ZeroReg).addReg(PtrReg);
8696   if (BinOpcode)
8697     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8698       .addReg(Incr2Reg).addReg(TmpDestReg);
8699   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8700     .addReg(TmpDestReg).addReg(MaskReg);
8701   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8702     .addReg(TmpReg).addReg(MaskReg);
8703   if (CmpOpcode) {
8704     // For unsigned comparisons, we can directly compare the shifted values.
8705     // For signed comparisons we shift and sign extend.
8706     unsigned SReg = RegInfo.createVirtualRegister(RC);
8707     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
8708       .addReg(TmpDestReg).addReg(MaskReg);
8709     unsigned ValueReg = SReg;
8710     unsigned CmpReg = Incr2Reg;
8711     if (CmpOpcode == PPC::CMPW) {
8712       ValueReg = RegInfo.createVirtualRegister(RC);
8713       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
8714         .addReg(SReg).addReg(ShiftReg);
8715       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
8716       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
8717         .addReg(ValueReg);
8718       ValueReg = ValueSReg;
8719       CmpReg = incr;
8720     }
8721     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8722       .addReg(CmpReg).addReg(ValueReg);
8723     BuildMI(BB, dl, TII->get(PPC::BCC))
8724       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8725     BB->addSuccessor(loop2MBB);
8726     BB->addSuccessor(exitMBB);
8727     BB = loop2MBB;
8728   }
8729   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8730     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8731   BuildMI(BB, dl, TII->get(PPC::STWCX))
8732     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8733   BuildMI(BB, dl, TII->get(PPC::BCC))
8734     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8735   BB->addSuccessor(loopMBB);
8736   BB->addSuccessor(exitMBB);
8737 
8738   //  exitMBB:
8739   //   ...
8740   BB = exitMBB;
8741   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8742     .addReg(ShiftReg);
8743   return BB;
8744 }
8745 
8746 llvm::MachineBasicBlock *
8747 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8748                                     MachineBasicBlock *MBB) const {
8749   DebugLoc DL = MI.getDebugLoc();
8750   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8751 
8752   MachineFunction *MF = MBB->getParent();
8753   MachineRegisterInfo &MRI = MF->getRegInfo();
8754 
8755   const BasicBlock *BB = MBB->getBasicBlock();
8756   MachineFunction::iterator I = ++MBB->getIterator();
8757 
8758   // Memory Reference
8759   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8760   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8761 
8762   unsigned DstReg = MI.getOperand(0).getReg();
8763   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8764   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8765   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8766   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8767 
8768   MVT PVT = getPointerTy(MF->getDataLayout());
8769   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8770          "Invalid Pointer Size!");
8771   // For v = setjmp(buf), we generate
8772   //
8773   // thisMBB:
8774   //  SjLjSetup mainMBB
8775   //  bl mainMBB
8776   //  v_restore = 1
8777   //  b sinkMBB
8778   //
8779   // mainMBB:
8780   //  buf[LabelOffset] = LR
8781   //  v_main = 0
8782   //
8783   // sinkMBB:
8784   //  v = phi(main, restore)
8785   //
8786 
8787   MachineBasicBlock *thisMBB = MBB;
8788   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8789   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8790   MF->insert(I, mainMBB);
8791   MF->insert(I, sinkMBB);
8792 
8793   MachineInstrBuilder MIB;
8794 
8795   // Transfer the remainder of BB and its successor edges to sinkMBB.
8796   sinkMBB->splice(sinkMBB->begin(), MBB,
8797                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8798   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8799 
8800   // Note that the structure of the jmp_buf used here is not compatible
8801   // with that used by libc, and is not designed to be. Specifically, it
8802   // stores only those 'reserved' registers that LLVM does not otherwise
8803   // understand how to spill. Also, by convention, by the time this
8804   // intrinsic is called, Clang has already stored the frame address in the
8805   // first slot of the buffer and stack address in the third. Following the
8806   // X86 target code, we'll store the jump address in the second slot. We also
8807   // need to save the TOC pointer (R2) to handle jumps between shared
8808   // libraries, and that will be stored in the fourth slot. The thread
8809   // identifier (R13) is not affected.
8810 
8811   // thisMBB:
8812   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8813   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8814   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8815 
8816   // Prepare IP either in reg.
8817   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8818   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8819   unsigned BufReg = MI.getOperand(1).getReg();
8820 
8821   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8822     setUsesTOCBasePtr(*MBB->getParent());
8823     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8824             .addReg(PPC::X2)
8825             .addImm(TOCOffset)
8826             .addReg(BufReg);
8827     MIB.setMemRefs(MMOBegin, MMOEnd);
8828   }
8829 
8830   // Naked functions never have a base pointer, and so we use r1. For all
8831   // other functions, this decision must be delayed until during PEI.
8832   unsigned BaseReg;
8833   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8834     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8835   else
8836     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8837 
8838   MIB = BuildMI(*thisMBB, MI, DL,
8839                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8840             .addReg(BaseReg)
8841             .addImm(BPOffset)
8842             .addReg(BufReg);
8843   MIB.setMemRefs(MMOBegin, MMOEnd);
8844 
8845   // Setup
8846   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8847   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8848   MIB.addRegMask(TRI->getNoPreservedMask());
8849 
8850   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8851 
8852   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8853           .addMBB(mainMBB);
8854   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8855 
8856   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8857   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8858 
8859   // mainMBB:
8860   //  mainDstReg = 0
8861   MIB =
8862       BuildMI(mainMBB, DL,
8863               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8864 
8865   // Store IP
8866   if (Subtarget.isPPC64()) {
8867     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8868             .addReg(LabelReg)
8869             .addImm(LabelOffset)
8870             .addReg(BufReg);
8871   } else {
8872     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8873             .addReg(LabelReg)
8874             .addImm(LabelOffset)
8875             .addReg(BufReg);
8876   }
8877 
8878   MIB.setMemRefs(MMOBegin, MMOEnd);
8879 
8880   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8881   mainMBB->addSuccessor(sinkMBB);
8882 
8883   // sinkMBB:
8884   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8885           TII->get(PPC::PHI), DstReg)
8886     .addReg(mainDstReg).addMBB(mainMBB)
8887     .addReg(restoreDstReg).addMBB(thisMBB);
8888 
8889   MI.eraseFromParent();
8890   return sinkMBB;
8891 }
8892 
8893 MachineBasicBlock *
8894 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8895                                      MachineBasicBlock *MBB) const {
8896   DebugLoc DL = MI.getDebugLoc();
8897   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8898 
8899   MachineFunction *MF = MBB->getParent();
8900   MachineRegisterInfo &MRI = MF->getRegInfo();
8901 
8902   // Memory Reference
8903   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8904   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8905 
8906   MVT PVT = getPointerTy(MF->getDataLayout());
8907   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8908          "Invalid Pointer Size!");
8909 
8910   const TargetRegisterClass *RC =
8911     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8912   unsigned Tmp = MRI.createVirtualRegister(RC);
8913   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8914   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8915   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8916   unsigned BP =
8917       (PVT == MVT::i64)
8918           ? PPC::X30
8919           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
8920                                                               : PPC::R30);
8921 
8922   MachineInstrBuilder MIB;
8923 
8924   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8925   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8926   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8927   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8928 
8929   unsigned BufReg = MI.getOperand(0).getReg();
8930 
8931   // Reload FP (the jumped-to function may not have had a
8932   // frame pointer, and if so, then its r31 will be restored
8933   // as necessary).
8934   if (PVT == MVT::i64) {
8935     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8936             .addImm(0)
8937             .addReg(BufReg);
8938   } else {
8939     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8940             .addImm(0)
8941             .addReg(BufReg);
8942   }
8943   MIB.setMemRefs(MMOBegin, MMOEnd);
8944 
8945   // Reload IP
8946   if (PVT == MVT::i64) {
8947     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8948             .addImm(LabelOffset)
8949             .addReg(BufReg);
8950   } else {
8951     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8952             .addImm(LabelOffset)
8953             .addReg(BufReg);
8954   }
8955   MIB.setMemRefs(MMOBegin, MMOEnd);
8956 
8957   // Reload SP
8958   if (PVT == MVT::i64) {
8959     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8960             .addImm(SPOffset)
8961             .addReg(BufReg);
8962   } else {
8963     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8964             .addImm(SPOffset)
8965             .addReg(BufReg);
8966   }
8967   MIB.setMemRefs(MMOBegin, MMOEnd);
8968 
8969   // Reload BP
8970   if (PVT == MVT::i64) {
8971     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8972             .addImm(BPOffset)
8973             .addReg(BufReg);
8974   } else {
8975     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8976             .addImm(BPOffset)
8977             .addReg(BufReg);
8978   }
8979   MIB.setMemRefs(MMOBegin, MMOEnd);
8980 
8981   // Reload TOC
8982   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8983     setUsesTOCBasePtr(*MBB->getParent());
8984     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8985             .addImm(TOCOffset)
8986             .addReg(BufReg);
8987 
8988     MIB.setMemRefs(MMOBegin, MMOEnd);
8989   }
8990 
8991   // Jump
8992   BuildMI(*MBB, MI, DL,
8993           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8994   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8995 
8996   MI.eraseFromParent();
8997   return MBB;
8998 }
8999 
9000 MachineBasicBlock *
9001 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9002                                                MachineBasicBlock *BB) const {
9003   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9004       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9005     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9006         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9007       // Call lowering should have added an r2 operand to indicate a dependence
9008       // on the TOC base pointer value. It can't however, because there is no
9009       // way to mark the dependence as implicit there, and so the stackmap code
9010       // will confuse it with a regular operand. Instead, add the dependence
9011       // here.
9012       setUsesTOCBasePtr(*BB->getParent());
9013       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9014     }
9015 
9016     return emitPatchPoint(MI, BB);
9017   }
9018 
9019   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9020       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9021     return emitEHSjLjSetJmp(MI, BB);
9022   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9023              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9024     return emitEHSjLjLongJmp(MI, BB);
9025   }
9026 
9027   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9028 
9029   // To "insert" these instructions we actually have to insert their
9030   // control-flow patterns.
9031   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9032   MachineFunction::iterator It = ++BB->getIterator();
9033 
9034   MachineFunction *F = BB->getParent();
9035 
9036   if (Subtarget.hasISEL() &&
9037       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9038        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9039        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
9040     SmallVector<MachineOperand, 2> Cond;
9041     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9042         MI.getOpcode() == PPC::SELECT_CC_I8)
9043       Cond.push_back(MI.getOperand(4));
9044     else
9045       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9046     Cond.push_back(MI.getOperand(1));
9047 
9048     DebugLoc dl = MI.getDebugLoc();
9049     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9050                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9051   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9052              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9053              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9054              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9055              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9056              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9057              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9058              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9059              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9060              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9061              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9062              MI.getOpcode() == PPC::SELECT_I4 ||
9063              MI.getOpcode() == PPC::SELECT_I8 ||
9064              MI.getOpcode() == PPC::SELECT_F4 ||
9065              MI.getOpcode() == PPC::SELECT_F8 ||
9066              MI.getOpcode() == PPC::SELECT_QFRC ||
9067              MI.getOpcode() == PPC::SELECT_QSRC ||
9068              MI.getOpcode() == PPC::SELECT_QBRC ||
9069              MI.getOpcode() == PPC::SELECT_VRRC ||
9070              MI.getOpcode() == PPC::SELECT_VSFRC ||
9071              MI.getOpcode() == PPC::SELECT_VSSRC ||
9072              MI.getOpcode() == PPC::SELECT_VSRC) {
9073     // The incoming instruction knows the destination vreg to set, the
9074     // condition code register to branch on, the true/false values to
9075     // select between, and a branch opcode to use.
9076 
9077     //  thisMBB:
9078     //  ...
9079     //   TrueVal = ...
9080     //   cmpTY ccX, r1, r2
9081     //   bCC copy1MBB
9082     //   fallthrough --> copy0MBB
9083     MachineBasicBlock *thisMBB = BB;
9084     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9085     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9086     DebugLoc dl = MI.getDebugLoc();
9087     F->insert(It, copy0MBB);
9088     F->insert(It, sinkMBB);
9089 
9090     // Transfer the remainder of BB and its successor edges to sinkMBB.
9091     sinkMBB->splice(sinkMBB->begin(), BB,
9092                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9093     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9094 
9095     // Next, add the true and fallthrough blocks as its successors.
9096     BB->addSuccessor(copy0MBB);
9097     BB->addSuccessor(sinkMBB);
9098 
9099     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9100         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9101         MI.getOpcode() == PPC::SELECT_QFRC ||
9102         MI.getOpcode() == PPC::SELECT_QSRC ||
9103         MI.getOpcode() == PPC::SELECT_QBRC ||
9104         MI.getOpcode() == PPC::SELECT_VRRC ||
9105         MI.getOpcode() == PPC::SELECT_VSFRC ||
9106         MI.getOpcode() == PPC::SELECT_VSSRC ||
9107         MI.getOpcode() == PPC::SELECT_VSRC) {
9108       BuildMI(BB, dl, TII->get(PPC::BC))
9109           .addReg(MI.getOperand(1).getReg())
9110           .addMBB(sinkMBB);
9111     } else {
9112       unsigned SelectPred = MI.getOperand(4).getImm();
9113       BuildMI(BB, dl, TII->get(PPC::BCC))
9114           .addImm(SelectPred)
9115           .addReg(MI.getOperand(1).getReg())
9116           .addMBB(sinkMBB);
9117     }
9118 
9119     //  copy0MBB:
9120     //   %FalseValue = ...
9121     //   # fallthrough to sinkMBB
9122     BB = copy0MBB;
9123 
9124     // Update machine-CFG edges
9125     BB->addSuccessor(sinkMBB);
9126 
9127     //  sinkMBB:
9128     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9129     //  ...
9130     BB = sinkMBB;
9131     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9132         .addReg(MI.getOperand(3).getReg())
9133         .addMBB(copy0MBB)
9134         .addReg(MI.getOperand(2).getReg())
9135         .addMBB(thisMBB);
9136   } else if (MI.getOpcode() == PPC::ReadTB) {
9137     // To read the 64-bit time-base register on a 32-bit target, we read the
9138     // two halves. Should the counter have wrapped while it was being read, we
9139     // need to try again.
9140     // ...
9141     // readLoop:
9142     // mfspr Rx,TBU # load from TBU
9143     // mfspr Ry,TB  # load from TB
9144     // mfspr Rz,TBU # load from TBU
9145     // cmpw crX,Rx,Rz # check if 'old'='new'
9146     // bne readLoop   # branch if they're not equal
9147     // ...
9148 
9149     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9150     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9151     DebugLoc dl = MI.getDebugLoc();
9152     F->insert(It, readMBB);
9153     F->insert(It, sinkMBB);
9154 
9155     // Transfer the remainder of BB and its successor edges to sinkMBB.
9156     sinkMBB->splice(sinkMBB->begin(), BB,
9157                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9158     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9159 
9160     BB->addSuccessor(readMBB);
9161     BB = readMBB;
9162 
9163     MachineRegisterInfo &RegInfo = F->getRegInfo();
9164     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9165     unsigned LoReg = MI.getOperand(0).getReg();
9166     unsigned HiReg = MI.getOperand(1).getReg();
9167 
9168     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9169     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9170     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9171 
9172     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9173 
9174     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9175       .addReg(HiReg).addReg(ReadAgainReg);
9176     BuildMI(BB, dl, TII->get(PPC::BCC))
9177       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9178 
9179     BB->addSuccessor(readMBB);
9180     BB->addSuccessor(sinkMBB);
9181   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9182     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9183   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9184     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9185   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9186     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9187   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9188     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9189 
9190   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9191     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9192   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9193     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9194   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9195     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9196   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9197     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9198 
9199   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9200     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9201   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9202     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9203   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9204     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9205   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9206     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9207 
9208   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9209     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9210   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9211     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9212   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9213     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9214   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9215     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9216 
9217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9218     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9219   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9220     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9221   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9222     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9223   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9224     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9225 
9226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9227     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9228   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9229     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9230   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9231     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9232   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9233     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9234 
9235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9236     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9237   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9238     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9239   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9240     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9241   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9242     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9243 
9244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9245     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9246   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9247     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9248   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9249     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9250   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9251     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9252 
9253   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9254     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9255   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9256     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9257   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9258     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9259   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9260     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9261 
9262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9263     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9264   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9265     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9266   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9267     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9268   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9269     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9270 
9271   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9272     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9273   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9274     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9275   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9276     BB = EmitAtomicBinary(MI, BB, 4, 0);
9277   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9278     BB = EmitAtomicBinary(MI, BB, 8, 0);
9279 
9280   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9281            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9282            (Subtarget.hasPartwordAtomics() &&
9283             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9284            (Subtarget.hasPartwordAtomics() &&
9285             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9286     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9287 
9288     auto LoadMnemonic = PPC::LDARX;
9289     auto StoreMnemonic = PPC::STDCX;
9290     switch (MI.getOpcode()) {
9291     default:
9292       llvm_unreachable("Compare and swap of unknown size");
9293     case PPC::ATOMIC_CMP_SWAP_I8:
9294       LoadMnemonic = PPC::LBARX;
9295       StoreMnemonic = PPC::STBCX;
9296       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9297       break;
9298     case PPC::ATOMIC_CMP_SWAP_I16:
9299       LoadMnemonic = PPC::LHARX;
9300       StoreMnemonic = PPC::STHCX;
9301       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9302       break;
9303     case PPC::ATOMIC_CMP_SWAP_I32:
9304       LoadMnemonic = PPC::LWARX;
9305       StoreMnemonic = PPC::STWCX;
9306       break;
9307     case PPC::ATOMIC_CMP_SWAP_I64:
9308       LoadMnemonic = PPC::LDARX;
9309       StoreMnemonic = PPC::STDCX;
9310       break;
9311     }
9312     unsigned dest = MI.getOperand(0).getReg();
9313     unsigned ptrA = MI.getOperand(1).getReg();
9314     unsigned ptrB = MI.getOperand(2).getReg();
9315     unsigned oldval = MI.getOperand(3).getReg();
9316     unsigned newval = MI.getOperand(4).getReg();
9317     DebugLoc dl = MI.getDebugLoc();
9318 
9319     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9320     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9321     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9322     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9323     F->insert(It, loop1MBB);
9324     F->insert(It, loop2MBB);
9325     F->insert(It, midMBB);
9326     F->insert(It, exitMBB);
9327     exitMBB->splice(exitMBB->begin(), BB,
9328                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9329     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9330 
9331     //  thisMBB:
9332     //   ...
9333     //   fallthrough --> loopMBB
9334     BB->addSuccessor(loop1MBB);
9335 
9336     // loop1MBB:
9337     //   l[bhwd]arx dest, ptr
9338     //   cmp[wd] dest, oldval
9339     //   bne- midMBB
9340     // loop2MBB:
9341     //   st[bhwd]cx. newval, ptr
9342     //   bne- loopMBB
9343     //   b exitBB
9344     // midMBB:
9345     //   st[bhwd]cx. dest, ptr
9346     // exitBB:
9347     BB = loop1MBB;
9348     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9349       .addReg(ptrA).addReg(ptrB);
9350     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9351       .addReg(oldval).addReg(dest);
9352     BuildMI(BB, dl, TII->get(PPC::BCC))
9353       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9354     BB->addSuccessor(loop2MBB);
9355     BB->addSuccessor(midMBB);
9356 
9357     BB = loop2MBB;
9358     BuildMI(BB, dl, TII->get(StoreMnemonic))
9359       .addReg(newval).addReg(ptrA).addReg(ptrB);
9360     BuildMI(BB, dl, TII->get(PPC::BCC))
9361       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9362     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9363     BB->addSuccessor(loop1MBB);
9364     BB->addSuccessor(exitMBB);
9365 
9366     BB = midMBB;
9367     BuildMI(BB, dl, TII->get(StoreMnemonic))
9368       .addReg(dest).addReg(ptrA).addReg(ptrB);
9369     BB->addSuccessor(exitMBB);
9370 
9371     //  exitMBB:
9372     //   ...
9373     BB = exitMBB;
9374   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9375              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9376     // We must use 64-bit registers for addresses when targeting 64-bit,
9377     // since we're actually doing arithmetic on them.  Other registers
9378     // can be 32-bit.
9379     bool is64bit = Subtarget.isPPC64();
9380     bool isLittleEndian = Subtarget.isLittleEndian();
9381     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9382 
9383     unsigned dest = MI.getOperand(0).getReg();
9384     unsigned ptrA = MI.getOperand(1).getReg();
9385     unsigned ptrB = MI.getOperand(2).getReg();
9386     unsigned oldval = MI.getOperand(3).getReg();
9387     unsigned newval = MI.getOperand(4).getReg();
9388     DebugLoc dl = MI.getDebugLoc();
9389 
9390     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9391     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9392     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9393     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9394     F->insert(It, loop1MBB);
9395     F->insert(It, loop2MBB);
9396     F->insert(It, midMBB);
9397     F->insert(It, exitMBB);
9398     exitMBB->splice(exitMBB->begin(), BB,
9399                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9400     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9401 
9402     MachineRegisterInfo &RegInfo = F->getRegInfo();
9403     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9404                                             : &PPC::GPRCRegClass;
9405     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9406     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9407     unsigned ShiftReg =
9408       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9409     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9410     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9411     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9412     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9413     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9414     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9415     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9416     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9417     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9418     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9419     unsigned Ptr1Reg;
9420     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9421     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9422     //  thisMBB:
9423     //   ...
9424     //   fallthrough --> loopMBB
9425     BB->addSuccessor(loop1MBB);
9426 
9427     // The 4-byte load must be aligned, while a char or short may be
9428     // anywhere in the word.  Hence all this nasty bookkeeping code.
9429     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9430     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9431     //   xori shift, shift1, 24 [16]
9432     //   rlwinm ptr, ptr1, 0, 0, 29
9433     //   slw newval2, newval, shift
9434     //   slw oldval2, oldval,shift
9435     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9436     //   slw mask, mask2, shift
9437     //   and newval3, newval2, mask
9438     //   and oldval3, oldval2, mask
9439     // loop1MBB:
9440     //   lwarx tmpDest, ptr
9441     //   and tmp, tmpDest, mask
9442     //   cmpw tmp, oldval3
9443     //   bne- midMBB
9444     // loop2MBB:
9445     //   andc tmp2, tmpDest, mask
9446     //   or tmp4, tmp2, newval3
9447     //   stwcx. tmp4, ptr
9448     //   bne- loop1MBB
9449     //   b exitBB
9450     // midMBB:
9451     //   stwcx. tmpDest, ptr
9452     // exitBB:
9453     //   srw dest, tmpDest, shift
9454     if (ptrA != ZeroReg) {
9455       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9456       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9457         .addReg(ptrA).addReg(ptrB);
9458     } else {
9459       Ptr1Reg = ptrB;
9460     }
9461     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9462         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9463     if (!isLittleEndian)
9464       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9465           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9466     if (is64bit)
9467       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9468         .addReg(Ptr1Reg).addImm(0).addImm(61);
9469     else
9470       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9471         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9472     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9473         .addReg(newval).addReg(ShiftReg);
9474     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9475         .addReg(oldval).addReg(ShiftReg);
9476     if (is8bit)
9477       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9478     else {
9479       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9480       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9481         .addReg(Mask3Reg).addImm(65535);
9482     }
9483     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9484         .addReg(Mask2Reg).addReg(ShiftReg);
9485     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9486         .addReg(NewVal2Reg).addReg(MaskReg);
9487     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9488         .addReg(OldVal2Reg).addReg(MaskReg);
9489 
9490     BB = loop1MBB;
9491     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9492         .addReg(ZeroReg).addReg(PtrReg);
9493     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9494         .addReg(TmpDestReg).addReg(MaskReg);
9495     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9496         .addReg(TmpReg).addReg(OldVal3Reg);
9497     BuildMI(BB, dl, TII->get(PPC::BCC))
9498         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9499     BB->addSuccessor(loop2MBB);
9500     BB->addSuccessor(midMBB);
9501 
9502     BB = loop2MBB;
9503     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9504         .addReg(TmpDestReg).addReg(MaskReg);
9505     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9506         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9507     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9508         .addReg(ZeroReg).addReg(PtrReg);
9509     BuildMI(BB, dl, TII->get(PPC::BCC))
9510       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9511     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9512     BB->addSuccessor(loop1MBB);
9513     BB->addSuccessor(exitMBB);
9514 
9515     BB = midMBB;
9516     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9517       .addReg(ZeroReg).addReg(PtrReg);
9518     BB->addSuccessor(exitMBB);
9519 
9520     //  exitMBB:
9521     //   ...
9522     BB = exitMBB;
9523     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9524       .addReg(ShiftReg);
9525   } else if (MI.getOpcode() == PPC::FADDrtz) {
9526     // This pseudo performs an FADD with rounding mode temporarily forced
9527     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9528     // is not modeled at the SelectionDAG level.
9529     unsigned Dest = MI.getOperand(0).getReg();
9530     unsigned Src1 = MI.getOperand(1).getReg();
9531     unsigned Src2 = MI.getOperand(2).getReg();
9532     DebugLoc dl = MI.getDebugLoc();
9533 
9534     MachineRegisterInfo &RegInfo = F->getRegInfo();
9535     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9536 
9537     // Save FPSCR value.
9538     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9539 
9540     // Set rounding mode to round-to-zero.
9541     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9542     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9543 
9544     // Perform addition.
9545     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9546 
9547     // Restore FPSCR value.
9548     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9549   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9550              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9551              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9552              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9553     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9554                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9555                           ? PPC::ANDIo8
9556                           : PPC::ANDIo;
9557     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9558                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9559 
9560     MachineRegisterInfo &RegInfo = F->getRegInfo();
9561     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9562                                                   &PPC::GPRCRegClass :
9563                                                   &PPC::G8RCRegClass);
9564 
9565     DebugLoc dl = MI.getDebugLoc();
9566     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9567         .addReg(MI.getOperand(1).getReg())
9568         .addImm(1);
9569     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9570             MI.getOperand(0).getReg())
9571         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9572   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9573     DebugLoc Dl = MI.getDebugLoc();
9574     MachineRegisterInfo &RegInfo = F->getRegInfo();
9575     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9576     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9577     return BB;
9578   } else {
9579     llvm_unreachable("Unexpected instr type to insert");
9580   }
9581 
9582   MI.eraseFromParent(); // The pseudo instruction is gone now.
9583   return BB;
9584 }
9585 
9586 //===----------------------------------------------------------------------===//
9587 // Target Optimization Hooks
9588 //===----------------------------------------------------------------------===//
9589 
9590 static std::string getRecipOp(const char *Base, EVT VT) {
9591   std::string RecipOp(Base);
9592   if (VT.getScalarType() == MVT::f64)
9593     RecipOp += "d";
9594   else
9595     RecipOp += "f";
9596 
9597   if (VT.isVector())
9598     RecipOp = "vec-" + RecipOp;
9599 
9600   return RecipOp;
9601 }
9602 
9603 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9604                                             DAGCombinerInfo &DCI,
9605                                             unsigned &RefinementSteps,
9606                                             bool &UseOneConstNR) const {
9607   EVT VT = Operand.getValueType();
9608   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9609       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9610       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9611       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9612       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9613       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9614     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9615     std::string RecipOp = getRecipOp("sqrt", VT);
9616     if (!Recips.isEnabled(RecipOp))
9617       return SDValue();
9618 
9619     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9620     UseOneConstNR = true;
9621     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9622   }
9623   return SDValue();
9624 }
9625 
9626 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9627                                             DAGCombinerInfo &DCI,
9628                                             unsigned &RefinementSteps) const {
9629   EVT VT = Operand.getValueType();
9630   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9631       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9632       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9633       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9634       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9635       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9636     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9637     std::string RecipOp = getRecipOp("div", VT);
9638     if (!Recips.isEnabled(RecipOp))
9639       return SDValue();
9640 
9641     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9642     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9643   }
9644   return SDValue();
9645 }
9646 
9647 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9648   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9649   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9650   // enabled for division), this functionality is redundant with the default
9651   // combiner logic (once the division -> reciprocal/multiply transformation
9652   // has taken place). As a result, this matters more for older cores than for
9653   // newer ones.
9654 
9655   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9656   // reciprocal if there are two or more FDIVs (for embedded cores with only
9657   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9658   switch (Subtarget.getDarwinDirective()) {
9659   default:
9660     return 3;
9661   case PPC::DIR_440:
9662   case PPC::DIR_A2:
9663   case PPC::DIR_E500mc:
9664   case PPC::DIR_E5500:
9665     return 2;
9666   }
9667 }
9668 
9669 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9670 // collapsed, and so we need to look through chains of them.
9671 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9672                                      int64_t& Offset, SelectionDAG &DAG) {
9673   if (DAG.isBaseWithConstantOffset(Loc)) {
9674     Base = Loc.getOperand(0);
9675     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9676 
9677     // The base might itself be a base plus an offset, and if so, accumulate
9678     // that as well.
9679     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9680   }
9681 }
9682 
9683 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9684                             unsigned Bytes, int Dist,
9685                             SelectionDAG &DAG) {
9686   if (VT.getSizeInBits() / 8 != Bytes)
9687     return false;
9688 
9689   SDValue BaseLoc = Base->getBasePtr();
9690   if (Loc.getOpcode() == ISD::FrameIndex) {
9691     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9692       return false;
9693     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9694     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9695     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9696     int FS  = MFI.getObjectSize(FI);
9697     int BFS = MFI.getObjectSize(BFI);
9698     if (FS != BFS || FS != (int)Bytes) return false;
9699     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9700   }
9701 
9702   SDValue Base1 = Loc, Base2 = BaseLoc;
9703   int64_t Offset1 = 0, Offset2 = 0;
9704   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9705   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9706   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9707     return true;
9708 
9709   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9710   const GlobalValue *GV1 = nullptr;
9711   const GlobalValue *GV2 = nullptr;
9712   Offset1 = 0;
9713   Offset2 = 0;
9714   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9715   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9716   if (isGA1 && isGA2 && GV1 == GV2)
9717     return Offset1 == (Offset2 + Dist*Bytes);
9718   return false;
9719 }
9720 
9721 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9722 // not enforce equality of the chain operands.
9723 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9724                             unsigned Bytes, int Dist,
9725                             SelectionDAG &DAG) {
9726   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9727     EVT VT = LS->getMemoryVT();
9728     SDValue Loc = LS->getBasePtr();
9729     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9730   }
9731 
9732   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9733     EVT VT;
9734     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9735     default: return false;
9736     case Intrinsic::ppc_qpx_qvlfd:
9737     case Intrinsic::ppc_qpx_qvlfda:
9738       VT = MVT::v4f64;
9739       break;
9740     case Intrinsic::ppc_qpx_qvlfs:
9741     case Intrinsic::ppc_qpx_qvlfsa:
9742       VT = MVT::v4f32;
9743       break;
9744     case Intrinsic::ppc_qpx_qvlfcd:
9745     case Intrinsic::ppc_qpx_qvlfcda:
9746       VT = MVT::v2f64;
9747       break;
9748     case Intrinsic::ppc_qpx_qvlfcs:
9749     case Intrinsic::ppc_qpx_qvlfcsa:
9750       VT = MVT::v2f32;
9751       break;
9752     case Intrinsic::ppc_qpx_qvlfiwa:
9753     case Intrinsic::ppc_qpx_qvlfiwz:
9754     case Intrinsic::ppc_altivec_lvx:
9755     case Intrinsic::ppc_altivec_lvxl:
9756     case Intrinsic::ppc_vsx_lxvw4x:
9757       VT = MVT::v4i32;
9758       break;
9759     case Intrinsic::ppc_vsx_lxvd2x:
9760       VT = MVT::v2f64;
9761       break;
9762     case Intrinsic::ppc_altivec_lvebx:
9763       VT = MVT::i8;
9764       break;
9765     case Intrinsic::ppc_altivec_lvehx:
9766       VT = MVT::i16;
9767       break;
9768     case Intrinsic::ppc_altivec_lvewx:
9769       VT = MVT::i32;
9770       break;
9771     }
9772 
9773     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9774   }
9775 
9776   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9777     EVT VT;
9778     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9779     default: return false;
9780     case Intrinsic::ppc_qpx_qvstfd:
9781     case Intrinsic::ppc_qpx_qvstfda:
9782       VT = MVT::v4f64;
9783       break;
9784     case Intrinsic::ppc_qpx_qvstfs:
9785     case Intrinsic::ppc_qpx_qvstfsa:
9786       VT = MVT::v4f32;
9787       break;
9788     case Intrinsic::ppc_qpx_qvstfcd:
9789     case Intrinsic::ppc_qpx_qvstfcda:
9790       VT = MVT::v2f64;
9791       break;
9792     case Intrinsic::ppc_qpx_qvstfcs:
9793     case Intrinsic::ppc_qpx_qvstfcsa:
9794       VT = MVT::v2f32;
9795       break;
9796     case Intrinsic::ppc_qpx_qvstfiw:
9797     case Intrinsic::ppc_qpx_qvstfiwa:
9798     case Intrinsic::ppc_altivec_stvx:
9799     case Intrinsic::ppc_altivec_stvxl:
9800     case Intrinsic::ppc_vsx_stxvw4x:
9801       VT = MVT::v4i32;
9802       break;
9803     case Intrinsic::ppc_vsx_stxvd2x:
9804       VT = MVT::v2f64;
9805       break;
9806     case Intrinsic::ppc_altivec_stvebx:
9807       VT = MVT::i8;
9808       break;
9809     case Intrinsic::ppc_altivec_stvehx:
9810       VT = MVT::i16;
9811       break;
9812     case Intrinsic::ppc_altivec_stvewx:
9813       VT = MVT::i32;
9814       break;
9815     }
9816 
9817     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9818   }
9819 
9820   return false;
9821 }
9822 
9823 // Return true is there is a nearyby consecutive load to the one provided
9824 // (regardless of alignment). We search up and down the chain, looking though
9825 // token factors and other loads (but nothing else). As a result, a true result
9826 // indicates that it is safe to create a new consecutive load adjacent to the
9827 // load provided.
9828 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9829   SDValue Chain = LD->getChain();
9830   EVT VT = LD->getMemoryVT();
9831 
9832   SmallSet<SDNode *, 16> LoadRoots;
9833   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9834   SmallSet<SDNode *, 16> Visited;
9835 
9836   // First, search up the chain, branching to follow all token-factor operands.
9837   // If we find a consecutive load, then we're done, otherwise, record all
9838   // nodes just above the top-level loads and token factors.
9839   while (!Queue.empty()) {
9840     SDNode *ChainNext = Queue.pop_back_val();
9841     if (!Visited.insert(ChainNext).second)
9842       continue;
9843 
9844     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9845       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9846         return true;
9847 
9848       if (!Visited.count(ChainLD->getChain().getNode()))
9849         Queue.push_back(ChainLD->getChain().getNode());
9850     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9851       for (const SDUse &O : ChainNext->ops())
9852         if (!Visited.count(O.getNode()))
9853           Queue.push_back(O.getNode());
9854     } else
9855       LoadRoots.insert(ChainNext);
9856   }
9857 
9858   // Second, search down the chain, starting from the top-level nodes recorded
9859   // in the first phase. These top-level nodes are the nodes just above all
9860   // loads and token factors. Starting with their uses, recursively look though
9861   // all loads (just the chain uses) and token factors to find a consecutive
9862   // load.
9863   Visited.clear();
9864   Queue.clear();
9865 
9866   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9867        IE = LoadRoots.end(); I != IE; ++I) {
9868     Queue.push_back(*I);
9869 
9870     while (!Queue.empty()) {
9871       SDNode *LoadRoot = Queue.pop_back_val();
9872       if (!Visited.insert(LoadRoot).second)
9873         continue;
9874 
9875       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9876         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9877           return true;
9878 
9879       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9880            UE = LoadRoot->use_end(); UI != UE; ++UI)
9881         if (((isa<MemSDNode>(*UI) &&
9882             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9883             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9884           Queue.push_back(*UI);
9885     }
9886   }
9887 
9888   return false;
9889 }
9890 
9891 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9892                                                   DAGCombinerInfo &DCI) const {
9893   SelectionDAG &DAG = DCI.DAG;
9894   SDLoc dl(N);
9895 
9896   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9897   // If we're tracking CR bits, we need to be careful that we don't have:
9898   //   trunc(binary-ops(zext(x), zext(y)))
9899   // or
9900   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9901   // such that we're unnecessarily moving things into GPRs when it would be
9902   // better to keep them in CR bits.
9903 
9904   // Note that trunc here can be an actual i1 trunc, or can be the effective
9905   // truncation that comes from a setcc or select_cc.
9906   if (N->getOpcode() == ISD::TRUNCATE &&
9907       N->getValueType(0) != MVT::i1)
9908     return SDValue();
9909 
9910   if (N->getOperand(0).getValueType() != MVT::i32 &&
9911       N->getOperand(0).getValueType() != MVT::i64)
9912     return SDValue();
9913 
9914   if (N->getOpcode() == ISD::SETCC ||
9915       N->getOpcode() == ISD::SELECT_CC) {
9916     // If we're looking at a comparison, then we need to make sure that the
9917     // high bits (all except for the first) don't matter the result.
9918     ISD::CondCode CC =
9919       cast<CondCodeSDNode>(N->getOperand(
9920         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9921     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9922 
9923     if (ISD::isSignedIntSetCC(CC)) {
9924       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9925           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9926         return SDValue();
9927     } else if (ISD::isUnsignedIntSetCC(CC)) {
9928       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9929                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9930           !DAG.MaskedValueIsZero(N->getOperand(1),
9931                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9932         return SDValue();
9933     } else {
9934       // This is neither a signed nor an unsigned comparison, just make sure
9935       // that the high bits are equal.
9936       APInt Op1Zero, Op1One;
9937       APInt Op2Zero, Op2One;
9938       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9939       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9940 
9941       // We don't really care about what is known about the first bit (if
9942       // anything), so clear it in all masks prior to comparing them.
9943       Op1Zero.clearBit(0); Op1One.clearBit(0);
9944       Op2Zero.clearBit(0); Op2One.clearBit(0);
9945 
9946       if (Op1Zero != Op2Zero || Op1One != Op2One)
9947         return SDValue();
9948     }
9949   }
9950 
9951   // We now know that the higher-order bits are irrelevant, we just need to
9952   // make sure that all of the intermediate operations are bit operations, and
9953   // all inputs are extensions.
9954   if (N->getOperand(0).getOpcode() != ISD::AND &&
9955       N->getOperand(0).getOpcode() != ISD::OR  &&
9956       N->getOperand(0).getOpcode() != ISD::XOR &&
9957       N->getOperand(0).getOpcode() != ISD::SELECT &&
9958       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9959       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9960       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9961       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9962       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9963     return SDValue();
9964 
9965   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9966       N->getOperand(1).getOpcode() != ISD::AND &&
9967       N->getOperand(1).getOpcode() != ISD::OR  &&
9968       N->getOperand(1).getOpcode() != ISD::XOR &&
9969       N->getOperand(1).getOpcode() != ISD::SELECT &&
9970       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9971       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9972       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9973       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9974       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9975     return SDValue();
9976 
9977   SmallVector<SDValue, 4> Inputs;
9978   SmallVector<SDValue, 8> BinOps, PromOps;
9979   SmallPtrSet<SDNode *, 16> Visited;
9980 
9981   for (unsigned i = 0; i < 2; ++i) {
9982     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9983           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9984           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9985           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9986         isa<ConstantSDNode>(N->getOperand(i)))
9987       Inputs.push_back(N->getOperand(i));
9988     else
9989       BinOps.push_back(N->getOperand(i));
9990 
9991     if (N->getOpcode() == ISD::TRUNCATE)
9992       break;
9993   }
9994 
9995   // Visit all inputs, collect all binary operations (and, or, xor and
9996   // select) that are all fed by extensions.
9997   while (!BinOps.empty()) {
9998     SDValue BinOp = BinOps.back();
9999     BinOps.pop_back();
10000 
10001     if (!Visited.insert(BinOp.getNode()).second)
10002       continue;
10003 
10004     PromOps.push_back(BinOp);
10005 
10006     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10007       // The condition of the select is not promoted.
10008       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10009         continue;
10010       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10011         continue;
10012 
10013       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10014             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10015             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10016            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10017           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10018         Inputs.push_back(BinOp.getOperand(i));
10019       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10020                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10021                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10022                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10023                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10024                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10025                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10026                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10027                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10028         BinOps.push_back(BinOp.getOperand(i));
10029       } else {
10030         // We have an input that is not an extension or another binary
10031         // operation; we'll abort this transformation.
10032         return SDValue();
10033       }
10034     }
10035   }
10036 
10037   // Make sure that this is a self-contained cluster of operations (which
10038   // is not quite the same thing as saying that everything has only one
10039   // use).
10040   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10041     if (isa<ConstantSDNode>(Inputs[i]))
10042       continue;
10043 
10044     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10045                               UE = Inputs[i].getNode()->use_end();
10046          UI != UE; ++UI) {
10047       SDNode *User = *UI;
10048       if (User != N && !Visited.count(User))
10049         return SDValue();
10050 
10051       // Make sure that we're not going to promote the non-output-value
10052       // operand(s) or SELECT or SELECT_CC.
10053       // FIXME: Although we could sometimes handle this, and it does occur in
10054       // practice that one of the condition inputs to the select is also one of
10055       // the outputs, we currently can't deal with this.
10056       if (User->getOpcode() == ISD::SELECT) {
10057         if (User->getOperand(0) == Inputs[i])
10058           return SDValue();
10059       } else if (User->getOpcode() == ISD::SELECT_CC) {
10060         if (User->getOperand(0) == Inputs[i] ||
10061             User->getOperand(1) == Inputs[i])
10062           return SDValue();
10063       }
10064     }
10065   }
10066 
10067   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10068     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10069                               UE = PromOps[i].getNode()->use_end();
10070          UI != UE; ++UI) {
10071       SDNode *User = *UI;
10072       if (User != N && !Visited.count(User))
10073         return SDValue();
10074 
10075       // Make sure that we're not going to promote the non-output-value
10076       // operand(s) or SELECT or SELECT_CC.
10077       // FIXME: Although we could sometimes handle this, and it does occur in
10078       // practice that one of the condition inputs to the select is also one of
10079       // the outputs, we currently can't deal with this.
10080       if (User->getOpcode() == ISD::SELECT) {
10081         if (User->getOperand(0) == PromOps[i])
10082           return SDValue();
10083       } else if (User->getOpcode() == ISD::SELECT_CC) {
10084         if (User->getOperand(0) == PromOps[i] ||
10085             User->getOperand(1) == PromOps[i])
10086           return SDValue();
10087       }
10088     }
10089   }
10090 
10091   // Replace all inputs with the extension operand.
10092   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10093     // Constants may have users outside the cluster of to-be-promoted nodes,
10094     // and so we need to replace those as we do the promotions.
10095     if (isa<ConstantSDNode>(Inputs[i]))
10096       continue;
10097     else
10098       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10099   }
10100 
10101   std::list<HandleSDNode> PromOpHandles;
10102   for (auto &PromOp : PromOps)
10103     PromOpHandles.emplace_back(PromOp);
10104 
10105   // Replace all operations (these are all the same, but have a different
10106   // (i1) return type). DAG.getNode will validate that the types of
10107   // a binary operator match, so go through the list in reverse so that
10108   // we've likely promoted both operands first. Any intermediate truncations or
10109   // extensions disappear.
10110   while (!PromOpHandles.empty()) {
10111     SDValue PromOp = PromOpHandles.back().getValue();
10112     PromOpHandles.pop_back();
10113 
10114     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10115         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10116         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10117         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10118       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10119           PromOp.getOperand(0).getValueType() != MVT::i1) {
10120         // The operand is not yet ready (see comment below).
10121         PromOpHandles.emplace_front(PromOp);
10122         continue;
10123       }
10124 
10125       SDValue RepValue = PromOp.getOperand(0);
10126       if (isa<ConstantSDNode>(RepValue))
10127         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10128 
10129       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10130       continue;
10131     }
10132 
10133     unsigned C;
10134     switch (PromOp.getOpcode()) {
10135     default:             C = 0; break;
10136     case ISD::SELECT:    C = 1; break;
10137     case ISD::SELECT_CC: C = 2; break;
10138     }
10139 
10140     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10141          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10142         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10143          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10144       // The to-be-promoted operands of this node have not yet been
10145       // promoted (this should be rare because we're going through the
10146       // list backward, but if one of the operands has several users in
10147       // this cluster of to-be-promoted nodes, it is possible).
10148       PromOpHandles.emplace_front(PromOp);
10149       continue;
10150     }
10151 
10152     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10153                                 PromOp.getNode()->op_end());
10154 
10155     // If there are any constant inputs, make sure they're replaced now.
10156     for (unsigned i = 0; i < 2; ++i)
10157       if (isa<ConstantSDNode>(Ops[C+i]))
10158         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10159 
10160     DAG.ReplaceAllUsesOfValueWith(PromOp,
10161       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10162   }
10163 
10164   // Now we're left with the initial truncation itself.
10165   if (N->getOpcode() == ISD::TRUNCATE)
10166     return N->getOperand(0);
10167 
10168   // Otherwise, this is a comparison. The operands to be compared have just
10169   // changed type (to i1), but everything else is the same.
10170   return SDValue(N, 0);
10171 }
10172 
10173 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10174                                                   DAGCombinerInfo &DCI) const {
10175   SelectionDAG &DAG = DCI.DAG;
10176   SDLoc dl(N);
10177 
10178   // If we're tracking CR bits, we need to be careful that we don't have:
10179   //   zext(binary-ops(trunc(x), trunc(y)))
10180   // or
10181   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10182   // such that we're unnecessarily moving things into CR bits that can more
10183   // efficiently stay in GPRs. Note that if we're not certain that the high
10184   // bits are set as required by the final extension, we still may need to do
10185   // some masking to get the proper behavior.
10186 
10187   // This same functionality is important on PPC64 when dealing with
10188   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10189   // the return values of functions. Because it is so similar, it is handled
10190   // here as well.
10191 
10192   if (N->getValueType(0) != MVT::i32 &&
10193       N->getValueType(0) != MVT::i64)
10194     return SDValue();
10195 
10196   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10197         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10198     return SDValue();
10199 
10200   if (N->getOperand(0).getOpcode() != ISD::AND &&
10201       N->getOperand(0).getOpcode() != ISD::OR  &&
10202       N->getOperand(0).getOpcode() != ISD::XOR &&
10203       N->getOperand(0).getOpcode() != ISD::SELECT &&
10204       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10205     return SDValue();
10206 
10207   SmallVector<SDValue, 4> Inputs;
10208   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10209   SmallPtrSet<SDNode *, 16> Visited;
10210 
10211   // Visit all inputs, collect all binary operations (and, or, xor and
10212   // select) that are all fed by truncations.
10213   while (!BinOps.empty()) {
10214     SDValue BinOp = BinOps.back();
10215     BinOps.pop_back();
10216 
10217     if (!Visited.insert(BinOp.getNode()).second)
10218       continue;
10219 
10220     PromOps.push_back(BinOp);
10221 
10222     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10223       // The condition of the select is not promoted.
10224       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10225         continue;
10226       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10227         continue;
10228 
10229       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10230           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10231         Inputs.push_back(BinOp.getOperand(i));
10232       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10233                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10234                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10235                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10236                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10237         BinOps.push_back(BinOp.getOperand(i));
10238       } else {
10239         // We have an input that is not a truncation or another binary
10240         // operation; we'll abort this transformation.
10241         return SDValue();
10242       }
10243     }
10244   }
10245 
10246   // The operands of a select that must be truncated when the select is
10247   // promoted because the operand is actually part of the to-be-promoted set.
10248   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10249 
10250   // Make sure that this is a self-contained cluster of operations (which
10251   // is not quite the same thing as saying that everything has only one
10252   // use).
10253   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10254     if (isa<ConstantSDNode>(Inputs[i]))
10255       continue;
10256 
10257     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10258                               UE = Inputs[i].getNode()->use_end();
10259          UI != UE; ++UI) {
10260       SDNode *User = *UI;
10261       if (User != N && !Visited.count(User))
10262         return SDValue();
10263 
10264       // If we're going to promote the non-output-value operand(s) or SELECT or
10265       // SELECT_CC, record them for truncation.
10266       if (User->getOpcode() == ISD::SELECT) {
10267         if (User->getOperand(0) == Inputs[i])
10268           SelectTruncOp[0].insert(std::make_pair(User,
10269                                     User->getOperand(0).getValueType()));
10270       } else if (User->getOpcode() == ISD::SELECT_CC) {
10271         if (User->getOperand(0) == Inputs[i])
10272           SelectTruncOp[0].insert(std::make_pair(User,
10273                                     User->getOperand(0).getValueType()));
10274         if (User->getOperand(1) == Inputs[i])
10275           SelectTruncOp[1].insert(std::make_pair(User,
10276                                     User->getOperand(1).getValueType()));
10277       }
10278     }
10279   }
10280 
10281   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10282     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10283                               UE = PromOps[i].getNode()->use_end();
10284          UI != UE; ++UI) {
10285       SDNode *User = *UI;
10286       if (User != N && !Visited.count(User))
10287         return SDValue();
10288 
10289       // If we're going to promote the non-output-value operand(s) or SELECT or
10290       // SELECT_CC, record them for truncation.
10291       if (User->getOpcode() == ISD::SELECT) {
10292         if (User->getOperand(0) == PromOps[i])
10293           SelectTruncOp[0].insert(std::make_pair(User,
10294                                     User->getOperand(0).getValueType()));
10295       } else if (User->getOpcode() == ISD::SELECT_CC) {
10296         if (User->getOperand(0) == PromOps[i])
10297           SelectTruncOp[0].insert(std::make_pair(User,
10298                                     User->getOperand(0).getValueType()));
10299         if (User->getOperand(1) == PromOps[i])
10300           SelectTruncOp[1].insert(std::make_pair(User,
10301                                     User->getOperand(1).getValueType()));
10302       }
10303     }
10304   }
10305 
10306   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10307   bool ReallyNeedsExt = false;
10308   if (N->getOpcode() != ISD::ANY_EXTEND) {
10309     // If all of the inputs are not already sign/zero extended, then
10310     // we'll still need to do that at the end.
10311     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10312       if (isa<ConstantSDNode>(Inputs[i]))
10313         continue;
10314 
10315       unsigned OpBits =
10316         Inputs[i].getOperand(0).getValueSizeInBits();
10317       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10318 
10319       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10320            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10321                                   APInt::getHighBitsSet(OpBits,
10322                                                         OpBits-PromBits))) ||
10323           (N->getOpcode() == ISD::SIGN_EXTEND &&
10324            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10325              (OpBits-(PromBits-1)))) {
10326         ReallyNeedsExt = true;
10327         break;
10328       }
10329     }
10330   }
10331 
10332   // Replace all inputs, either with the truncation operand, or a
10333   // truncation or extension to the final output type.
10334   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10335     // Constant inputs need to be replaced with the to-be-promoted nodes that
10336     // use them because they might have users outside of the cluster of
10337     // promoted nodes.
10338     if (isa<ConstantSDNode>(Inputs[i]))
10339       continue;
10340 
10341     SDValue InSrc = Inputs[i].getOperand(0);
10342     if (Inputs[i].getValueType() == N->getValueType(0))
10343       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10344     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10345       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10346         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10347     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10348       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10349         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10350     else
10351       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10352         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10353   }
10354 
10355   std::list<HandleSDNode> PromOpHandles;
10356   for (auto &PromOp : PromOps)
10357     PromOpHandles.emplace_back(PromOp);
10358 
10359   // Replace all operations (these are all the same, but have a different
10360   // (promoted) return type). DAG.getNode will validate that the types of
10361   // a binary operator match, so go through the list in reverse so that
10362   // we've likely promoted both operands first.
10363   while (!PromOpHandles.empty()) {
10364     SDValue PromOp = PromOpHandles.back().getValue();
10365     PromOpHandles.pop_back();
10366 
10367     unsigned C;
10368     switch (PromOp.getOpcode()) {
10369     default:             C = 0; break;
10370     case ISD::SELECT:    C = 1; break;
10371     case ISD::SELECT_CC: C = 2; break;
10372     }
10373 
10374     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10375          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10376         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10377          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10378       // The to-be-promoted operands of this node have not yet been
10379       // promoted (this should be rare because we're going through the
10380       // list backward, but if one of the operands has several users in
10381       // this cluster of to-be-promoted nodes, it is possible).
10382       PromOpHandles.emplace_front(PromOp);
10383       continue;
10384     }
10385 
10386     // For SELECT and SELECT_CC nodes, we do a similar check for any
10387     // to-be-promoted comparison inputs.
10388     if (PromOp.getOpcode() == ISD::SELECT ||
10389         PromOp.getOpcode() == ISD::SELECT_CC) {
10390       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10391            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10392           (SelectTruncOp[1].count(PromOp.getNode()) &&
10393            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10394         PromOpHandles.emplace_front(PromOp);
10395         continue;
10396       }
10397     }
10398 
10399     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10400                                 PromOp.getNode()->op_end());
10401 
10402     // If this node has constant inputs, then they'll need to be promoted here.
10403     for (unsigned i = 0; i < 2; ++i) {
10404       if (!isa<ConstantSDNode>(Ops[C+i]))
10405         continue;
10406       if (Ops[C+i].getValueType() == N->getValueType(0))
10407         continue;
10408 
10409       if (N->getOpcode() == ISD::SIGN_EXTEND)
10410         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10411       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10412         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10413       else
10414         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10415     }
10416 
10417     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10418     // truncate them again to the original value type.
10419     if (PromOp.getOpcode() == ISD::SELECT ||
10420         PromOp.getOpcode() == ISD::SELECT_CC) {
10421       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10422       if (SI0 != SelectTruncOp[0].end())
10423         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10424       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10425       if (SI1 != SelectTruncOp[1].end())
10426         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10427     }
10428 
10429     DAG.ReplaceAllUsesOfValueWith(PromOp,
10430       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10431   }
10432 
10433   // Now we're left with the initial extension itself.
10434   if (!ReallyNeedsExt)
10435     return N->getOperand(0);
10436 
10437   // To zero extend, just mask off everything except for the first bit (in the
10438   // i1 case).
10439   if (N->getOpcode() == ISD::ZERO_EXTEND)
10440     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10441                        DAG.getConstant(APInt::getLowBitsSet(
10442                                          N->getValueSizeInBits(0), PromBits),
10443                                        dl, N->getValueType(0)));
10444 
10445   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10446          "Invalid extension type");
10447   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10448   SDValue ShiftCst =
10449       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10450   return DAG.getNode(
10451       ISD::SRA, dl, N->getValueType(0),
10452       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10453       ShiftCst);
10454 }
10455 
10456 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10457                                                  DAGCombinerInfo &DCI) const {
10458   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10459          "Should be called with a BUILD_VECTOR node");
10460 
10461   SelectionDAG &DAG = DCI.DAG;
10462   SDLoc dl(N);
10463   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10464     return SDValue();
10465 
10466   // Looking for:
10467   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10468   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10469       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10470     return SDValue();
10471   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10472       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10473     return SDValue();
10474   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10475     return SDValue();
10476 
10477   SDValue Ext1 = N->getOperand(0).getOperand(0);
10478   SDValue Ext2 = N->getOperand(1).getOperand(0);
10479   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10480      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10481     return SDValue();
10482 
10483   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10484   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10485   if (!Ext1Op || !Ext2Op)
10486     return SDValue();
10487   if (Ext1.getValueType() != MVT::i32 ||
10488       Ext2.getValueType() != MVT::i32)
10489   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10490     return SDValue();
10491 
10492   int FirstElem = Ext1Op->getZExtValue();
10493   int SecondElem = Ext2Op->getZExtValue();
10494   int SubvecIdx;
10495   if (FirstElem == 0 && SecondElem == 1)
10496     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10497   else if (FirstElem == 2 && SecondElem == 3)
10498     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10499   else
10500     return SDValue();
10501 
10502   SDValue SrcVec = Ext1.getOperand(0);
10503   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10504     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10505   return DAG.getNode(NodeType, dl, MVT::v2f64,
10506                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10507 }
10508 
10509 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10510                                               DAGCombinerInfo &DCI) const {
10511   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10512           N->getOpcode() == ISD::UINT_TO_FP) &&
10513          "Need an int -> FP conversion node here");
10514 
10515   if (!Subtarget.has64BitSupport())
10516     return SDValue();
10517 
10518   SelectionDAG &DAG = DCI.DAG;
10519   SDLoc dl(N);
10520   SDValue Op(N, 0);
10521 
10522   // Don't handle ppc_fp128 here or i1 conversions.
10523   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10524     return SDValue();
10525   if (Op.getOperand(0).getValueType() == MVT::i1)
10526     return SDValue();
10527 
10528   // For i32 intermediate values, unfortunately, the conversion functions
10529   // leave the upper 32 bits of the value are undefined. Within the set of
10530   // scalar instructions, we have no method for zero- or sign-extending the
10531   // value. Thus, we cannot handle i32 intermediate values here.
10532   if (Op.getOperand(0).getValueType() == MVT::i32)
10533     return SDValue();
10534 
10535   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10536          "UINT_TO_FP is supported only with FPCVT");
10537 
10538   // If we have FCFIDS, then use it when converting to single-precision.
10539   // Otherwise, convert to double-precision and then round.
10540   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10541                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10542                                                             : PPCISD::FCFIDS)
10543                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10544                                                             : PPCISD::FCFID);
10545   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10546                   ? MVT::f32
10547                   : MVT::f64;
10548 
10549   // If we're converting from a float, to an int, and back to a float again,
10550   // then we don't need the store/load pair at all.
10551   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10552        Subtarget.hasFPCVT()) ||
10553       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10554     SDValue Src = Op.getOperand(0).getOperand(0);
10555     if (Src.getValueType() == MVT::f32) {
10556       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10557       DCI.AddToWorklist(Src.getNode());
10558     } else if (Src.getValueType() != MVT::f64) {
10559       // Make sure that we don't pick up a ppc_fp128 source value.
10560       return SDValue();
10561     }
10562 
10563     unsigned FCTOp =
10564       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10565                                                         PPCISD::FCTIDUZ;
10566 
10567     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10568     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10569 
10570     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10571       FP = DAG.getNode(ISD::FP_ROUND, dl,
10572                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10573       DCI.AddToWorklist(FP.getNode());
10574     }
10575 
10576     return FP;
10577   }
10578 
10579   return SDValue();
10580 }
10581 
10582 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10583 // builtins) into loads with swaps.
10584 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10585                                               DAGCombinerInfo &DCI) const {
10586   SelectionDAG &DAG = DCI.DAG;
10587   SDLoc dl(N);
10588   SDValue Chain;
10589   SDValue Base;
10590   MachineMemOperand *MMO;
10591 
10592   switch (N->getOpcode()) {
10593   default:
10594     llvm_unreachable("Unexpected opcode for little endian VSX load");
10595   case ISD::LOAD: {
10596     LoadSDNode *LD = cast<LoadSDNode>(N);
10597     Chain = LD->getChain();
10598     Base = LD->getBasePtr();
10599     MMO = LD->getMemOperand();
10600     // If the MMO suggests this isn't a load of a full vector, leave
10601     // things alone.  For a built-in, we have to make the change for
10602     // correctness, so if there is a size problem that will be a bug.
10603     if (MMO->getSize() < 16)
10604       return SDValue();
10605     break;
10606   }
10607   case ISD::INTRINSIC_W_CHAIN: {
10608     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10609     Chain = Intrin->getChain();
10610     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10611     // us what we want. Get operand 2 instead.
10612     Base = Intrin->getOperand(2);
10613     MMO = Intrin->getMemOperand();
10614     break;
10615   }
10616   }
10617 
10618   MVT VecTy = N->getValueType(0).getSimpleVT();
10619   SDValue LoadOps[] = { Chain, Base };
10620   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10621                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10622                                          LoadOps, MVT::v2f64, MMO);
10623 
10624   DCI.AddToWorklist(Load.getNode());
10625   Chain = Load.getValue(1);
10626   SDValue Swap = DAG.getNode(
10627       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10628   DCI.AddToWorklist(Swap.getNode());
10629 
10630   // Add a bitcast if the resulting load type doesn't match v2f64.
10631   if (VecTy != MVT::v2f64) {
10632     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10633     DCI.AddToWorklist(N.getNode());
10634     // Package {bitcast value, swap's chain} to match Load's shape.
10635     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10636                        N, Swap.getValue(1));
10637   }
10638 
10639   return Swap;
10640 }
10641 
10642 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10643 // builtins) into stores with swaps.
10644 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10645                                                DAGCombinerInfo &DCI) const {
10646   SelectionDAG &DAG = DCI.DAG;
10647   SDLoc dl(N);
10648   SDValue Chain;
10649   SDValue Base;
10650   unsigned SrcOpnd;
10651   MachineMemOperand *MMO;
10652 
10653   switch (N->getOpcode()) {
10654   default:
10655     llvm_unreachable("Unexpected opcode for little endian VSX store");
10656   case ISD::STORE: {
10657     StoreSDNode *ST = cast<StoreSDNode>(N);
10658     Chain = ST->getChain();
10659     Base = ST->getBasePtr();
10660     MMO = ST->getMemOperand();
10661     SrcOpnd = 1;
10662     // If the MMO suggests this isn't a store of a full vector, leave
10663     // things alone.  For a built-in, we have to make the change for
10664     // correctness, so if there is a size problem that will be a bug.
10665     if (MMO->getSize() < 16)
10666       return SDValue();
10667     break;
10668   }
10669   case ISD::INTRINSIC_VOID: {
10670     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10671     Chain = Intrin->getChain();
10672     // Intrin->getBasePtr() oddly does not get what we want.
10673     Base = Intrin->getOperand(3);
10674     MMO = Intrin->getMemOperand();
10675     SrcOpnd = 2;
10676     break;
10677   }
10678   }
10679 
10680   SDValue Src = N->getOperand(SrcOpnd);
10681   MVT VecTy = Src.getValueType().getSimpleVT();
10682 
10683   // All stores are done as v2f64 and possible bit cast.
10684   if (VecTy != MVT::v2f64) {
10685     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10686     DCI.AddToWorklist(Src.getNode());
10687   }
10688 
10689   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10690                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10691   DCI.AddToWorklist(Swap.getNode());
10692   Chain = Swap.getValue(1);
10693   SDValue StoreOps[] = { Chain, Swap, Base };
10694   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10695                                           DAG.getVTList(MVT::Other),
10696                                           StoreOps, VecTy, MMO);
10697   DCI.AddToWorklist(Store.getNode());
10698   return Store;
10699 }
10700 
10701 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10702                                              DAGCombinerInfo &DCI) const {
10703   SelectionDAG &DAG = DCI.DAG;
10704   SDLoc dl(N);
10705   switch (N->getOpcode()) {
10706   default: break;
10707   case PPCISD::SHL:
10708     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10709         return N->getOperand(0);
10710     break;
10711   case PPCISD::SRL:
10712     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10713         return N->getOperand(0);
10714     break;
10715   case PPCISD::SRA:
10716     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10717       if (C->isNullValue() ||   //  0 >>s V -> 0.
10718           C->isAllOnesValue())    // -1 >>s V -> -1.
10719         return N->getOperand(0);
10720     }
10721     break;
10722   case ISD::SIGN_EXTEND:
10723   case ISD::ZERO_EXTEND:
10724   case ISD::ANY_EXTEND:
10725     return DAGCombineExtBoolTrunc(N, DCI);
10726   case ISD::TRUNCATE:
10727   case ISD::SETCC:
10728   case ISD::SELECT_CC:
10729     return DAGCombineTruncBoolExt(N, DCI);
10730   case ISD::SINT_TO_FP:
10731   case ISD::UINT_TO_FP:
10732     return combineFPToIntToFP(N, DCI);
10733   case ISD::STORE: {
10734     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10735     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10736         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10737         N->getOperand(1).getValueType() == MVT::i32 &&
10738         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10739       SDValue Val = N->getOperand(1).getOperand(0);
10740       if (Val.getValueType() == MVT::f32) {
10741         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10742         DCI.AddToWorklist(Val.getNode());
10743       }
10744       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10745       DCI.AddToWorklist(Val.getNode());
10746 
10747       SDValue Ops[] = {
10748         N->getOperand(0), Val, N->getOperand(2),
10749         DAG.getValueType(N->getOperand(1).getValueType())
10750       };
10751 
10752       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10753               DAG.getVTList(MVT::Other), Ops,
10754               cast<StoreSDNode>(N)->getMemoryVT(),
10755               cast<StoreSDNode>(N)->getMemOperand());
10756       DCI.AddToWorklist(Val.getNode());
10757       return Val;
10758     }
10759 
10760     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10761     if (cast<StoreSDNode>(N)->isUnindexed() &&
10762         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10763         N->getOperand(1).getNode()->hasOneUse() &&
10764         (N->getOperand(1).getValueType() == MVT::i32 ||
10765          N->getOperand(1).getValueType() == MVT::i16 ||
10766          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10767           N->getOperand(1).getValueType() == MVT::i64))) {
10768       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10769       // Do an any-extend to 32-bits if this is a half-word input.
10770       if (BSwapOp.getValueType() == MVT::i16)
10771         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10772 
10773       SDValue Ops[] = {
10774         N->getOperand(0), BSwapOp, N->getOperand(2),
10775         DAG.getValueType(N->getOperand(1).getValueType())
10776       };
10777       return
10778         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10779                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10780                                 cast<StoreSDNode>(N)->getMemOperand());
10781     }
10782 
10783     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10784     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
10785     EVT VT = N->getOperand(1).getValueType();
10786     if (VT.isSimple()) {
10787       MVT StoreVT = VT.getSimpleVT();
10788       if (Subtarget.needsSwapsForVSXMemOps() &&
10789           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10790            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10791         return expandVSXStoreForLE(N, DCI);
10792     }
10793     break;
10794   }
10795   case ISD::LOAD: {
10796     LoadSDNode *LD = cast<LoadSDNode>(N);
10797     EVT VT = LD->getValueType(0);
10798 
10799     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10800     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
10801     if (VT.isSimple()) {
10802       MVT LoadVT = VT.getSimpleVT();
10803       if (Subtarget.needsSwapsForVSXMemOps() &&
10804           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10805            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10806         return expandVSXLoadForLE(N, DCI);
10807     }
10808 
10809     // We sometimes end up with a 64-bit integer load, from which we extract
10810     // two single-precision floating-point numbers. This happens with
10811     // std::complex<float>, and other similar structures, because of the way we
10812     // canonicalize structure copies. However, if we lack direct moves,
10813     // then the final bitcasts from the extracted integer values to the
10814     // floating-point numbers turn into store/load pairs. Even with direct moves,
10815     // just loading the two floating-point numbers is likely better.
10816     auto ReplaceTwoFloatLoad = [&]() {
10817       if (VT != MVT::i64)
10818         return false;
10819 
10820       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10821           LD->isVolatile())
10822         return false;
10823 
10824       //  We're looking for a sequence like this:
10825       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10826       //      t16: i64 = srl t13, Constant:i32<32>
10827       //    t17: i32 = truncate t16
10828       //  t18: f32 = bitcast t17
10829       //    t19: i32 = truncate t13
10830       //  t20: f32 = bitcast t19
10831 
10832       if (!LD->hasNUsesOfValue(2, 0))
10833         return false;
10834 
10835       auto UI = LD->use_begin();
10836       while (UI.getUse().getResNo() != 0) ++UI;
10837       SDNode *Trunc = *UI++;
10838       while (UI.getUse().getResNo() != 0) ++UI;
10839       SDNode *RightShift = *UI;
10840       if (Trunc->getOpcode() != ISD::TRUNCATE)
10841         std::swap(Trunc, RightShift);
10842 
10843       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10844           Trunc->getValueType(0) != MVT::i32 ||
10845           !Trunc->hasOneUse())
10846         return false;
10847       if (RightShift->getOpcode() != ISD::SRL ||
10848           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10849           RightShift->getConstantOperandVal(1) != 32 ||
10850           !RightShift->hasOneUse())
10851         return false;
10852 
10853       SDNode *Trunc2 = *RightShift->use_begin();
10854       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10855           Trunc2->getValueType(0) != MVT::i32 ||
10856           !Trunc2->hasOneUse())
10857         return false;
10858 
10859       SDNode *Bitcast = *Trunc->use_begin();
10860       SDNode *Bitcast2 = *Trunc2->use_begin();
10861 
10862       if (Bitcast->getOpcode() != ISD::BITCAST ||
10863           Bitcast->getValueType(0) != MVT::f32)
10864         return false;
10865       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10866           Bitcast2->getValueType(0) != MVT::f32)
10867         return false;
10868 
10869       if (Subtarget.isLittleEndian())
10870         std::swap(Bitcast, Bitcast2);
10871 
10872       // Bitcast has the second float (in memory-layout order) and Bitcast2
10873       // has the first one.
10874 
10875       SDValue BasePtr = LD->getBasePtr();
10876       if (LD->isIndexed()) {
10877         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10878                "Non-pre-inc AM on PPC?");
10879         BasePtr =
10880           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10881                       LD->getOffset());
10882       }
10883 
10884       auto MMOFlags =
10885           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
10886       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10887                                       LD->getPointerInfo(), LD->getAlignment(),
10888                                       MMOFlags, LD->getAAInfo());
10889       SDValue AddPtr =
10890         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10891                     BasePtr, DAG.getIntPtrConstant(4, dl));
10892       SDValue FloatLoad2 = DAG.getLoad(
10893           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10894           LD->getPointerInfo().getWithOffset(4),
10895           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
10896 
10897       if (LD->isIndexed()) {
10898         // Note that DAGCombine should re-form any pre-increment load(s) from
10899         // what is produced here if that makes sense.
10900         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10901       }
10902 
10903       DCI.CombineTo(Bitcast2, FloatLoad);
10904       DCI.CombineTo(Bitcast, FloatLoad2);
10905 
10906       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10907                                     SDValue(FloatLoad2.getNode(), 1));
10908       return true;
10909     };
10910 
10911     if (ReplaceTwoFloatLoad())
10912       return SDValue(N, 0);
10913 
10914     EVT MemVT = LD->getMemoryVT();
10915     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10916     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10917     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10918     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10919     if (LD->isUnindexed() && VT.isVector() &&
10920         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10921           // P8 and later hardware should just use LOAD.
10922           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10923                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10924          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10925           LD->getAlignment() >= ScalarABIAlignment)) &&
10926         LD->getAlignment() < ABIAlignment) {
10927       // This is a type-legal unaligned Altivec or QPX load.
10928       SDValue Chain = LD->getChain();
10929       SDValue Ptr = LD->getBasePtr();
10930       bool isLittleEndian = Subtarget.isLittleEndian();
10931 
10932       // This implements the loading of unaligned vectors as described in
10933       // the venerable Apple Velocity Engine overview. Specifically:
10934       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10935       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10936       //
10937       // The general idea is to expand a sequence of one or more unaligned
10938       // loads into an alignment-based permutation-control instruction (lvsl
10939       // or lvsr), a series of regular vector loads (which always truncate
10940       // their input address to an aligned address), and a series of
10941       // permutations.  The results of these permutations are the requested
10942       // loaded values.  The trick is that the last "extra" load is not taken
10943       // from the address you might suspect (sizeof(vector) bytes after the
10944       // last requested load), but rather sizeof(vector) - 1 bytes after the
10945       // last requested vector. The point of this is to avoid a page fault if
10946       // the base address happened to be aligned. This works because if the
10947       // base address is aligned, then adding less than a full vector length
10948       // will cause the last vector in the sequence to be (re)loaded.
10949       // Otherwise, the next vector will be fetched as you might suspect was
10950       // necessary.
10951 
10952       // We might be able to reuse the permutation generation from
10953       // a different base address offset from this one by an aligned amount.
10954       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10955       // optimization later.
10956       Intrinsic::ID Intr, IntrLD, IntrPerm;
10957       MVT PermCntlTy, PermTy, LDTy;
10958       if (Subtarget.hasAltivec()) {
10959         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10960                                  Intrinsic::ppc_altivec_lvsl;
10961         IntrLD = Intrinsic::ppc_altivec_lvx;
10962         IntrPerm = Intrinsic::ppc_altivec_vperm;
10963         PermCntlTy = MVT::v16i8;
10964         PermTy = MVT::v4i32;
10965         LDTy = MVT::v4i32;
10966       } else {
10967         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10968                                        Intrinsic::ppc_qpx_qvlpcls;
10969         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10970                                        Intrinsic::ppc_qpx_qvlfs;
10971         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10972         PermCntlTy = MVT::v4f64;
10973         PermTy = MVT::v4f64;
10974         LDTy = MemVT.getSimpleVT();
10975       }
10976 
10977       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10978 
10979       // Create the new MMO for the new base load. It is like the original MMO,
10980       // but represents an area in memory almost twice the vector size centered
10981       // on the original address. If the address is unaligned, we might start
10982       // reading up to (sizeof(vector)-1) bytes below the address of the
10983       // original unaligned load.
10984       MachineFunction &MF = DAG.getMachineFunction();
10985       MachineMemOperand *BaseMMO =
10986         MF.getMachineMemOperand(LD->getMemOperand(),
10987                                 -(long)MemVT.getStoreSize()+1,
10988                                 2*MemVT.getStoreSize()-1);
10989 
10990       // Create the new base load.
10991       SDValue LDXIntID =
10992           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10993       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10994       SDValue BaseLoad =
10995         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10996                                 DAG.getVTList(PermTy, MVT::Other),
10997                                 BaseLoadOps, LDTy, BaseMMO);
10998 
10999       // Note that the value of IncOffset (which is provided to the next
11000       // load's pointer info offset value, and thus used to calculate the
11001       // alignment), and the value of IncValue (which is actually used to
11002       // increment the pointer value) are different! This is because we
11003       // require the next load to appear to be aligned, even though it
11004       // is actually offset from the base pointer by a lesser amount.
11005       int IncOffset = VT.getSizeInBits() / 8;
11006       int IncValue = IncOffset;
11007 
11008       // Walk (both up and down) the chain looking for another load at the real
11009       // (aligned) offset (the alignment of the other load does not matter in
11010       // this case). If found, then do not use the offset reduction trick, as
11011       // that will prevent the loads from being later combined (as they would
11012       // otherwise be duplicates).
11013       if (!findConsecutiveLoad(LD, DAG))
11014         --IncValue;
11015 
11016       SDValue Increment =
11017           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11018       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11019 
11020       MachineMemOperand *ExtraMMO =
11021         MF.getMachineMemOperand(LD->getMemOperand(),
11022                                 1, 2*MemVT.getStoreSize()-1);
11023       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11024       SDValue ExtraLoad =
11025         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11026                                 DAG.getVTList(PermTy, MVT::Other),
11027                                 ExtraLoadOps, LDTy, ExtraMMO);
11028 
11029       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11030         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11031 
11032       // Because vperm has a big-endian bias, we must reverse the order
11033       // of the input vectors and complement the permute control vector
11034       // when generating little endian code.  We have already handled the
11035       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11036       // and ExtraLoad here.
11037       SDValue Perm;
11038       if (isLittleEndian)
11039         Perm = BuildIntrinsicOp(IntrPerm,
11040                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11041       else
11042         Perm = BuildIntrinsicOp(IntrPerm,
11043                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11044 
11045       if (VT != PermTy)
11046         Perm = Subtarget.hasAltivec() ?
11047                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11048                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11049                                DAG.getTargetConstant(1, dl, MVT::i64));
11050                                // second argument is 1 because this rounding
11051                                // is always exact.
11052 
11053       // The output of the permutation is our loaded result, the TokenFactor is
11054       // our new chain.
11055       DCI.CombineTo(N, Perm, TF);
11056       return SDValue(N, 0);
11057     }
11058     }
11059     break;
11060     case ISD::INTRINSIC_WO_CHAIN: {
11061       bool isLittleEndian = Subtarget.isLittleEndian();
11062       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11063       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11064                                            : Intrinsic::ppc_altivec_lvsl);
11065       if ((IID == Intr ||
11066            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11067            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11068         N->getOperand(1)->getOpcode() == ISD::ADD) {
11069         SDValue Add = N->getOperand(1);
11070 
11071         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11072                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11073 
11074         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11075                                   APInt::getAllOnesValue(Bits /* alignment */)
11076                                       .zext(Add.getScalarValueSizeInBits()))) {
11077           SDNode *BasePtr = Add->getOperand(0).getNode();
11078           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11079                                     UE = BasePtr->use_end();
11080                UI != UE; ++UI) {
11081             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11082                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11083               // We've found another LVSL/LVSR, and this address is an aligned
11084               // multiple of that one. The results will be the same, so use the
11085               // one we've just found instead.
11086 
11087               return SDValue(*UI, 0);
11088             }
11089           }
11090         }
11091 
11092         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11093           SDNode *BasePtr = Add->getOperand(0).getNode();
11094           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11095                UE = BasePtr->use_end(); UI != UE; ++UI) {
11096             if (UI->getOpcode() == ISD::ADD &&
11097                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11098                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11099                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11100                 (1ULL << Bits) == 0) {
11101               SDNode *OtherAdd = *UI;
11102               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11103                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11104                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11105                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11106                   return SDValue(*VI, 0);
11107                 }
11108               }
11109             }
11110           }
11111         }
11112       }
11113     }
11114 
11115     break;
11116   case ISD::INTRINSIC_W_CHAIN: {
11117     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11118     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11119     if (Subtarget.needsSwapsForVSXMemOps()) {
11120       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11121       default:
11122         break;
11123       case Intrinsic::ppc_vsx_lxvw4x:
11124       case Intrinsic::ppc_vsx_lxvd2x:
11125         return expandVSXLoadForLE(N, DCI);
11126       }
11127     }
11128     break;
11129   }
11130   case ISD::INTRINSIC_VOID: {
11131     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11132     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11133     if (Subtarget.needsSwapsForVSXMemOps()) {
11134       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11135       default:
11136         break;
11137       case Intrinsic::ppc_vsx_stxvw4x:
11138       case Intrinsic::ppc_vsx_stxvd2x:
11139         return expandVSXStoreForLE(N, DCI);
11140       }
11141     }
11142     break;
11143   }
11144   case ISD::BSWAP:
11145     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11146     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11147         N->getOperand(0).hasOneUse() &&
11148         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11149          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11150           N->getValueType(0) == MVT::i64))) {
11151       SDValue Load = N->getOperand(0);
11152       LoadSDNode *LD = cast<LoadSDNode>(Load);
11153       // Create the byte-swapping load.
11154       SDValue Ops[] = {
11155         LD->getChain(),    // Chain
11156         LD->getBasePtr(),  // Ptr
11157         DAG.getValueType(N->getValueType(0)) // VT
11158       };
11159       SDValue BSLoad =
11160         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11161                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11162                                               MVT::i64 : MVT::i32, MVT::Other),
11163                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11164 
11165       // If this is an i16 load, insert the truncate.
11166       SDValue ResVal = BSLoad;
11167       if (N->getValueType(0) == MVT::i16)
11168         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11169 
11170       // First, combine the bswap away.  This makes the value produced by the
11171       // load dead.
11172       DCI.CombineTo(N, ResVal);
11173 
11174       // Next, combine the load away, we give it a bogus result value but a real
11175       // chain result.  The result value is dead because the bswap is dead.
11176       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11177 
11178       // Return N so it doesn't get rechecked!
11179       return SDValue(N, 0);
11180     }
11181 
11182     break;
11183   case PPCISD::VCMP: {
11184     // If a VCMPo node already exists with exactly the same operands as this
11185     // node, use its result instead of this node (VCMPo computes both a CR6 and
11186     // a normal output).
11187     //
11188     if (!N->getOperand(0).hasOneUse() &&
11189         !N->getOperand(1).hasOneUse() &&
11190         !N->getOperand(2).hasOneUse()) {
11191 
11192       // Scan all of the users of the LHS, looking for VCMPo's that match.
11193       SDNode *VCMPoNode = nullptr;
11194 
11195       SDNode *LHSN = N->getOperand(0).getNode();
11196       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11197            UI != E; ++UI)
11198         if (UI->getOpcode() == PPCISD::VCMPo &&
11199             UI->getOperand(1) == N->getOperand(1) &&
11200             UI->getOperand(2) == N->getOperand(2) &&
11201             UI->getOperand(0) == N->getOperand(0)) {
11202           VCMPoNode = *UI;
11203           break;
11204         }
11205 
11206       // If there is no VCMPo node, or if the flag value has a single use, don't
11207       // transform this.
11208       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11209         break;
11210 
11211       // Look at the (necessarily single) use of the flag value.  If it has a
11212       // chain, this transformation is more complex.  Note that multiple things
11213       // could use the value result, which we should ignore.
11214       SDNode *FlagUser = nullptr;
11215       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11216            FlagUser == nullptr; ++UI) {
11217         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11218         SDNode *User = *UI;
11219         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11220           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11221             FlagUser = User;
11222             break;
11223           }
11224         }
11225       }
11226 
11227       // If the user is a MFOCRF instruction, we know this is safe.
11228       // Otherwise we give up for right now.
11229       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11230         return SDValue(VCMPoNode, 0);
11231     }
11232     break;
11233   }
11234   case ISD::BRCOND: {
11235     SDValue Cond = N->getOperand(1);
11236     SDValue Target = N->getOperand(2);
11237 
11238     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11239         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11240           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11241 
11242       // We now need to make the intrinsic dead (it cannot be instruction
11243       // selected).
11244       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11245       assert(Cond.getNode()->hasOneUse() &&
11246              "Counter decrement has more than one use");
11247 
11248       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11249                          N->getOperand(0), Target);
11250     }
11251   }
11252   break;
11253   case ISD::BR_CC: {
11254     // If this is a branch on an altivec predicate comparison, lower this so
11255     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11256     // lowering is done pre-legalize, because the legalizer lowers the predicate
11257     // compare down to code that is difficult to reassemble.
11258     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11259     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11260 
11261     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11262     // value. If so, pass-through the AND to get to the intrinsic.
11263     if (LHS.getOpcode() == ISD::AND &&
11264         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11265         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11266           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11267         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11268         !isNullConstant(LHS.getOperand(1)))
11269       LHS = LHS.getOperand(0);
11270 
11271     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11272         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11273           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11274         isa<ConstantSDNode>(RHS)) {
11275       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11276              "Counter decrement comparison is not EQ or NE");
11277 
11278       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11279       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11280                     (CC == ISD::SETNE && !Val);
11281 
11282       // We now need to make the intrinsic dead (it cannot be instruction
11283       // selected).
11284       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11285       assert(LHS.getNode()->hasOneUse() &&
11286              "Counter decrement has more than one use");
11287 
11288       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11289                          N->getOperand(0), N->getOperand(4));
11290     }
11291 
11292     int CompareOpc;
11293     bool isDot;
11294 
11295     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11296         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11297         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11298       assert(isDot && "Can't compare against a vector result!");
11299 
11300       // If this is a comparison against something other than 0/1, then we know
11301       // that the condition is never/always true.
11302       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11303       if (Val != 0 && Val != 1) {
11304         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11305           return N->getOperand(0);
11306         // Always !=, turn it into an unconditional branch.
11307         return DAG.getNode(ISD::BR, dl, MVT::Other,
11308                            N->getOperand(0), N->getOperand(4));
11309       }
11310 
11311       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11312 
11313       // Create the PPCISD altivec 'dot' comparison node.
11314       SDValue Ops[] = {
11315         LHS.getOperand(2),  // LHS of compare
11316         LHS.getOperand(3),  // RHS of compare
11317         DAG.getConstant(CompareOpc, dl, MVT::i32)
11318       };
11319       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11320       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11321 
11322       // Unpack the result based on how the target uses it.
11323       PPC::Predicate CompOpc;
11324       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11325       default:  // Can't happen, don't crash on invalid number though.
11326       case 0:   // Branch on the value of the EQ bit of CR6.
11327         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11328         break;
11329       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11330         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11331         break;
11332       case 2:   // Branch on the value of the LT bit of CR6.
11333         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11334         break;
11335       case 3:   // Branch on the inverted value of the LT bit of CR6.
11336         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11337         break;
11338       }
11339 
11340       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11341                          DAG.getConstant(CompOpc, dl, MVT::i32),
11342                          DAG.getRegister(PPC::CR6, MVT::i32),
11343                          N->getOperand(4), CompNode.getValue(1));
11344     }
11345     break;
11346   }
11347   case ISD::BUILD_VECTOR:
11348     return DAGCombineBuildVector(N, DCI);
11349   }
11350 
11351   return SDValue();
11352 }
11353 
11354 SDValue
11355 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11356                                   SelectionDAG &DAG,
11357                                   std::vector<SDNode *> *Created) const {
11358   // fold (sdiv X, pow2)
11359   EVT VT = N->getValueType(0);
11360   if (VT == MVT::i64 && !Subtarget.isPPC64())
11361     return SDValue();
11362   if ((VT != MVT::i32 && VT != MVT::i64) ||
11363       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11364     return SDValue();
11365 
11366   SDLoc DL(N);
11367   SDValue N0 = N->getOperand(0);
11368 
11369   bool IsNegPow2 = (-Divisor).isPowerOf2();
11370   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11371   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11372 
11373   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11374   if (Created)
11375     Created->push_back(Op.getNode());
11376 
11377   if (IsNegPow2) {
11378     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11379     if (Created)
11380       Created->push_back(Op.getNode());
11381   }
11382 
11383   return Op;
11384 }
11385 
11386 //===----------------------------------------------------------------------===//
11387 // Inline Assembly Support
11388 //===----------------------------------------------------------------------===//
11389 
11390 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11391                                                       APInt &KnownZero,
11392                                                       APInt &KnownOne,
11393                                                       const SelectionDAG &DAG,
11394                                                       unsigned Depth) const {
11395   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11396   switch (Op.getOpcode()) {
11397   default: break;
11398   case PPCISD::LBRX: {
11399     // lhbrx is known to have the top bits cleared out.
11400     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11401       KnownZero = 0xFFFF0000;
11402     break;
11403   }
11404   case ISD::INTRINSIC_WO_CHAIN: {
11405     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11406     default: break;
11407     case Intrinsic::ppc_altivec_vcmpbfp_p:
11408     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11409     case Intrinsic::ppc_altivec_vcmpequb_p:
11410     case Intrinsic::ppc_altivec_vcmpequh_p:
11411     case Intrinsic::ppc_altivec_vcmpequw_p:
11412     case Intrinsic::ppc_altivec_vcmpequd_p:
11413     case Intrinsic::ppc_altivec_vcmpgefp_p:
11414     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11415     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11416     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11417     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11418     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11419     case Intrinsic::ppc_altivec_vcmpgtub_p:
11420     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11421     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11422     case Intrinsic::ppc_altivec_vcmpgtud_p:
11423       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11424       break;
11425     }
11426   }
11427   }
11428 }
11429 
11430 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11431   switch (Subtarget.getDarwinDirective()) {
11432   default: break;
11433   case PPC::DIR_970:
11434   case PPC::DIR_PWR4:
11435   case PPC::DIR_PWR5:
11436   case PPC::DIR_PWR5X:
11437   case PPC::DIR_PWR6:
11438   case PPC::DIR_PWR6X:
11439   case PPC::DIR_PWR7:
11440   case PPC::DIR_PWR8:
11441   case PPC::DIR_PWR9: {
11442     if (!ML)
11443       break;
11444 
11445     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11446 
11447     // For small loops (between 5 and 8 instructions), align to a 32-byte
11448     // boundary so that the entire loop fits in one instruction-cache line.
11449     uint64_t LoopSize = 0;
11450     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11451       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11452         LoopSize += TII->getInstSizeInBytes(*J);
11453         if (LoopSize > 32)
11454           break;
11455       }
11456 
11457     if (LoopSize > 16 && LoopSize <= 32)
11458       return 5;
11459 
11460     break;
11461   }
11462   }
11463 
11464   return TargetLowering::getPrefLoopAlignment(ML);
11465 }
11466 
11467 /// getConstraintType - Given a constraint, return the type of
11468 /// constraint it is for this target.
11469 PPCTargetLowering::ConstraintType
11470 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11471   if (Constraint.size() == 1) {
11472     switch (Constraint[0]) {
11473     default: break;
11474     case 'b':
11475     case 'r':
11476     case 'f':
11477     case 'd':
11478     case 'v':
11479     case 'y':
11480       return C_RegisterClass;
11481     case 'Z':
11482       // FIXME: While Z does indicate a memory constraint, it specifically
11483       // indicates an r+r address (used in conjunction with the 'y' modifier
11484       // in the replacement string). Currently, we're forcing the base
11485       // register to be r0 in the asm printer (which is interpreted as zero)
11486       // and forming the complete address in the second register. This is
11487       // suboptimal.
11488       return C_Memory;
11489     }
11490   } else if (Constraint == "wc") { // individual CR bits.
11491     return C_RegisterClass;
11492   } else if (Constraint == "wa" || Constraint == "wd" ||
11493              Constraint == "wf" || Constraint == "ws") {
11494     return C_RegisterClass; // VSX registers.
11495   }
11496   return TargetLowering::getConstraintType(Constraint);
11497 }
11498 
11499 /// Examine constraint type and operand type and determine a weight value.
11500 /// This object must already have been set up with the operand type
11501 /// and the current alternative constraint selected.
11502 TargetLowering::ConstraintWeight
11503 PPCTargetLowering::getSingleConstraintMatchWeight(
11504     AsmOperandInfo &info, const char *constraint) const {
11505   ConstraintWeight weight = CW_Invalid;
11506   Value *CallOperandVal = info.CallOperandVal;
11507     // If we don't have a value, we can't do a match,
11508     // but allow it at the lowest weight.
11509   if (!CallOperandVal)
11510     return CW_Default;
11511   Type *type = CallOperandVal->getType();
11512 
11513   // Look at the constraint type.
11514   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11515     return CW_Register; // an individual CR bit.
11516   else if ((StringRef(constraint) == "wa" ||
11517             StringRef(constraint) == "wd" ||
11518             StringRef(constraint) == "wf") &&
11519            type->isVectorTy())
11520     return CW_Register;
11521   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11522     return CW_Register;
11523 
11524   switch (*constraint) {
11525   default:
11526     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11527     break;
11528   case 'b':
11529     if (type->isIntegerTy())
11530       weight = CW_Register;
11531     break;
11532   case 'f':
11533     if (type->isFloatTy())
11534       weight = CW_Register;
11535     break;
11536   case 'd':
11537     if (type->isDoubleTy())
11538       weight = CW_Register;
11539     break;
11540   case 'v':
11541     if (type->isVectorTy())
11542       weight = CW_Register;
11543     break;
11544   case 'y':
11545     weight = CW_Register;
11546     break;
11547   case 'Z':
11548     weight = CW_Memory;
11549     break;
11550   }
11551   return weight;
11552 }
11553 
11554 std::pair<unsigned, const TargetRegisterClass *>
11555 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11556                                                 StringRef Constraint,
11557                                                 MVT VT) const {
11558   if (Constraint.size() == 1) {
11559     // GCC RS6000 Constraint Letters
11560     switch (Constraint[0]) {
11561     case 'b':   // R1-R31
11562       if (VT == MVT::i64 && Subtarget.isPPC64())
11563         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11564       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11565     case 'r':   // R0-R31
11566       if (VT == MVT::i64 && Subtarget.isPPC64())
11567         return std::make_pair(0U, &PPC::G8RCRegClass);
11568       return std::make_pair(0U, &PPC::GPRCRegClass);
11569     // 'd' and 'f' constraints are both defined to be "the floating point
11570     // registers", where one is for 32-bit and the other for 64-bit. We don't
11571     // really care overly much here so just give them all the same reg classes.
11572     case 'd':
11573     case 'f':
11574       if (VT == MVT::f32 || VT == MVT::i32)
11575         return std::make_pair(0U, &PPC::F4RCRegClass);
11576       if (VT == MVT::f64 || VT == MVT::i64)
11577         return std::make_pair(0U, &PPC::F8RCRegClass);
11578       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11579         return std::make_pair(0U, &PPC::QFRCRegClass);
11580       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11581         return std::make_pair(0U, &PPC::QSRCRegClass);
11582       break;
11583     case 'v':
11584       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11585         return std::make_pair(0U, &PPC::QFRCRegClass);
11586       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11587         return std::make_pair(0U, &PPC::QSRCRegClass);
11588       if (Subtarget.hasAltivec())
11589         return std::make_pair(0U, &PPC::VRRCRegClass);
11590     case 'y':   // crrc
11591       return std::make_pair(0U, &PPC::CRRCRegClass);
11592     }
11593   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11594     // An individual CR bit.
11595     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11596   } else if ((Constraint == "wa" || Constraint == "wd" ||
11597              Constraint == "wf") && Subtarget.hasVSX()) {
11598     return std::make_pair(0U, &PPC::VSRCRegClass);
11599   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11600     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11601       return std::make_pair(0U, &PPC::VSSRCRegClass);
11602     else
11603       return std::make_pair(0U, &PPC::VSFRCRegClass);
11604   }
11605 
11606   std::pair<unsigned, const TargetRegisterClass *> R =
11607       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11608 
11609   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11610   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11611   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11612   // register.
11613   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11614   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11615   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11616       PPC::GPRCRegClass.contains(R.first))
11617     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11618                             PPC::sub_32, &PPC::G8RCRegClass),
11619                           &PPC::G8RCRegClass);
11620 
11621   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11622   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11623     R.first = PPC::CR0;
11624     R.second = &PPC::CRRCRegClass;
11625   }
11626 
11627   return R;
11628 }
11629 
11630 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11631 /// vector.  If it is invalid, don't add anything to Ops.
11632 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11633                                                      std::string &Constraint,
11634                                                      std::vector<SDValue>&Ops,
11635                                                      SelectionDAG &DAG) const {
11636   SDValue Result;
11637 
11638   // Only support length 1 constraints.
11639   if (Constraint.length() > 1) return;
11640 
11641   char Letter = Constraint[0];
11642   switch (Letter) {
11643   default: break;
11644   case 'I':
11645   case 'J':
11646   case 'K':
11647   case 'L':
11648   case 'M':
11649   case 'N':
11650   case 'O':
11651   case 'P': {
11652     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11653     if (!CST) return; // Must be an immediate to match.
11654     SDLoc dl(Op);
11655     int64_t Value = CST->getSExtValue();
11656     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11657                          // numbers are printed as such.
11658     switch (Letter) {
11659     default: llvm_unreachable("Unknown constraint letter!");
11660     case 'I':  // "I" is a signed 16-bit constant.
11661       if (isInt<16>(Value))
11662         Result = DAG.getTargetConstant(Value, dl, TCVT);
11663       break;
11664     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11665       if (isShiftedUInt<16, 16>(Value))
11666         Result = DAG.getTargetConstant(Value, dl, TCVT);
11667       break;
11668     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11669       if (isShiftedInt<16, 16>(Value))
11670         Result = DAG.getTargetConstant(Value, dl, TCVT);
11671       break;
11672     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11673       if (isUInt<16>(Value))
11674         Result = DAG.getTargetConstant(Value, dl, TCVT);
11675       break;
11676     case 'M':  // "M" is a constant that is greater than 31.
11677       if (Value > 31)
11678         Result = DAG.getTargetConstant(Value, dl, TCVT);
11679       break;
11680     case 'N':  // "N" is a positive constant that is an exact power of two.
11681       if (Value > 0 && isPowerOf2_64(Value))
11682         Result = DAG.getTargetConstant(Value, dl, TCVT);
11683       break;
11684     case 'O':  // "O" is the constant zero.
11685       if (Value == 0)
11686         Result = DAG.getTargetConstant(Value, dl, TCVT);
11687       break;
11688     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11689       if (isInt<16>(-Value))
11690         Result = DAG.getTargetConstant(Value, dl, TCVT);
11691       break;
11692     }
11693     break;
11694   }
11695   }
11696 
11697   if (Result.getNode()) {
11698     Ops.push_back(Result);
11699     return;
11700   }
11701 
11702   // Handle standard constraint letters.
11703   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11704 }
11705 
11706 // isLegalAddressingMode - Return true if the addressing mode represented
11707 // by AM is legal for this target, for a load/store of the specified type.
11708 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11709                                               const AddrMode &AM, Type *Ty,
11710                                               unsigned AS) const {
11711   // PPC does not allow r+i addressing modes for vectors!
11712   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11713     return false;
11714 
11715   // PPC allows a sign-extended 16-bit immediate field.
11716   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11717     return false;
11718 
11719   // No global is ever allowed as a base.
11720   if (AM.BaseGV)
11721     return false;
11722 
11723   // PPC only support r+r,
11724   switch (AM.Scale) {
11725   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11726     break;
11727   case 1:
11728     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11729       return false;
11730     // Otherwise we have r+r or r+i.
11731     break;
11732   case 2:
11733     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11734       return false;
11735     // Allow 2*r as r+r.
11736     break;
11737   default:
11738     // No other scales are supported.
11739     return false;
11740   }
11741 
11742   return true;
11743 }
11744 
11745 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11746                                            SelectionDAG &DAG) const {
11747   MachineFunction &MF = DAG.getMachineFunction();
11748   MachineFrameInfo &MFI = MF.getFrameInfo();
11749   MFI.setReturnAddressIsTaken(true);
11750 
11751   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11752     return SDValue();
11753 
11754   SDLoc dl(Op);
11755   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11756 
11757   // Make sure the function does not optimize away the store of the RA to
11758   // the stack.
11759   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11760   FuncInfo->setLRStoreRequired();
11761   bool isPPC64 = Subtarget.isPPC64();
11762   auto PtrVT = getPointerTy(MF.getDataLayout());
11763 
11764   if (Depth > 0) {
11765     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11766     SDValue Offset =
11767         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11768                         isPPC64 ? MVT::i64 : MVT::i32);
11769     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11770                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11771                        MachinePointerInfo());
11772   }
11773 
11774   // Just load the return address off the stack.
11775   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11776   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11777                      MachinePointerInfo());
11778 }
11779 
11780 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11781                                           SelectionDAG &DAG) const {
11782   SDLoc dl(Op);
11783   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11784 
11785   MachineFunction &MF = DAG.getMachineFunction();
11786   MachineFrameInfo &MFI = MF.getFrameInfo();
11787   MFI.setFrameAddressIsTaken(true);
11788 
11789   EVT PtrVT = getPointerTy(MF.getDataLayout());
11790   bool isPPC64 = PtrVT == MVT::i64;
11791 
11792   // Naked functions never have a frame pointer, and so we use r1. For all
11793   // other functions, this decision must be delayed until during PEI.
11794   unsigned FrameReg;
11795   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11796     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11797   else
11798     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11799 
11800   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11801                                          PtrVT);
11802   while (Depth--)
11803     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11804                             FrameAddr, MachinePointerInfo());
11805   return FrameAddr;
11806 }
11807 
11808 // FIXME? Maybe this could be a TableGen attribute on some registers and
11809 // this table could be generated automatically from RegInfo.
11810 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11811                                               SelectionDAG &DAG) const {
11812   bool isPPC64 = Subtarget.isPPC64();
11813   bool isDarwinABI = Subtarget.isDarwinABI();
11814 
11815   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11816       (!isPPC64 && VT != MVT::i32))
11817     report_fatal_error("Invalid register global variable type");
11818 
11819   bool is64Bit = isPPC64 && VT == MVT::i64;
11820   unsigned Reg = StringSwitch<unsigned>(RegName)
11821                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11822                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11823                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11824                                   (is64Bit ? PPC::X13 : PPC::R13))
11825                    .Default(0);
11826 
11827   if (Reg)
11828     return Reg;
11829   report_fatal_error("Invalid register name global variable");
11830 }
11831 
11832 bool
11833 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11834   // The PowerPC target isn't yet aware of offsets.
11835   return false;
11836 }
11837 
11838 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11839                                            const CallInst &I,
11840                                            unsigned Intrinsic) const {
11841 
11842   switch (Intrinsic) {
11843   case Intrinsic::ppc_qpx_qvlfd:
11844   case Intrinsic::ppc_qpx_qvlfs:
11845   case Intrinsic::ppc_qpx_qvlfcd:
11846   case Intrinsic::ppc_qpx_qvlfcs:
11847   case Intrinsic::ppc_qpx_qvlfiwa:
11848   case Intrinsic::ppc_qpx_qvlfiwz:
11849   case Intrinsic::ppc_altivec_lvx:
11850   case Intrinsic::ppc_altivec_lvxl:
11851   case Intrinsic::ppc_altivec_lvebx:
11852   case Intrinsic::ppc_altivec_lvehx:
11853   case Intrinsic::ppc_altivec_lvewx:
11854   case Intrinsic::ppc_vsx_lxvd2x:
11855   case Intrinsic::ppc_vsx_lxvw4x: {
11856     EVT VT;
11857     switch (Intrinsic) {
11858     case Intrinsic::ppc_altivec_lvebx:
11859       VT = MVT::i8;
11860       break;
11861     case Intrinsic::ppc_altivec_lvehx:
11862       VT = MVT::i16;
11863       break;
11864     case Intrinsic::ppc_altivec_lvewx:
11865       VT = MVT::i32;
11866       break;
11867     case Intrinsic::ppc_vsx_lxvd2x:
11868       VT = MVT::v2f64;
11869       break;
11870     case Intrinsic::ppc_qpx_qvlfd:
11871       VT = MVT::v4f64;
11872       break;
11873     case Intrinsic::ppc_qpx_qvlfs:
11874       VT = MVT::v4f32;
11875       break;
11876     case Intrinsic::ppc_qpx_qvlfcd:
11877       VT = MVT::v2f64;
11878       break;
11879     case Intrinsic::ppc_qpx_qvlfcs:
11880       VT = MVT::v2f32;
11881       break;
11882     default:
11883       VT = MVT::v4i32;
11884       break;
11885     }
11886 
11887     Info.opc = ISD::INTRINSIC_W_CHAIN;
11888     Info.memVT = VT;
11889     Info.ptrVal = I.getArgOperand(0);
11890     Info.offset = -VT.getStoreSize()+1;
11891     Info.size = 2*VT.getStoreSize()-1;
11892     Info.align = 1;
11893     Info.vol = false;
11894     Info.readMem = true;
11895     Info.writeMem = false;
11896     return true;
11897   }
11898   case Intrinsic::ppc_qpx_qvlfda:
11899   case Intrinsic::ppc_qpx_qvlfsa:
11900   case Intrinsic::ppc_qpx_qvlfcda:
11901   case Intrinsic::ppc_qpx_qvlfcsa:
11902   case Intrinsic::ppc_qpx_qvlfiwaa:
11903   case Intrinsic::ppc_qpx_qvlfiwza: {
11904     EVT VT;
11905     switch (Intrinsic) {
11906     case Intrinsic::ppc_qpx_qvlfda:
11907       VT = MVT::v4f64;
11908       break;
11909     case Intrinsic::ppc_qpx_qvlfsa:
11910       VT = MVT::v4f32;
11911       break;
11912     case Intrinsic::ppc_qpx_qvlfcda:
11913       VT = MVT::v2f64;
11914       break;
11915     case Intrinsic::ppc_qpx_qvlfcsa:
11916       VT = MVT::v2f32;
11917       break;
11918     default:
11919       VT = MVT::v4i32;
11920       break;
11921     }
11922 
11923     Info.opc = ISD::INTRINSIC_W_CHAIN;
11924     Info.memVT = VT;
11925     Info.ptrVal = I.getArgOperand(0);
11926     Info.offset = 0;
11927     Info.size = VT.getStoreSize();
11928     Info.align = 1;
11929     Info.vol = false;
11930     Info.readMem = true;
11931     Info.writeMem = false;
11932     return true;
11933   }
11934   case Intrinsic::ppc_qpx_qvstfd:
11935   case Intrinsic::ppc_qpx_qvstfs:
11936   case Intrinsic::ppc_qpx_qvstfcd:
11937   case Intrinsic::ppc_qpx_qvstfcs:
11938   case Intrinsic::ppc_qpx_qvstfiw:
11939   case Intrinsic::ppc_altivec_stvx:
11940   case Intrinsic::ppc_altivec_stvxl:
11941   case Intrinsic::ppc_altivec_stvebx:
11942   case Intrinsic::ppc_altivec_stvehx:
11943   case Intrinsic::ppc_altivec_stvewx:
11944   case Intrinsic::ppc_vsx_stxvd2x:
11945   case Intrinsic::ppc_vsx_stxvw4x: {
11946     EVT VT;
11947     switch (Intrinsic) {
11948     case Intrinsic::ppc_altivec_stvebx:
11949       VT = MVT::i8;
11950       break;
11951     case Intrinsic::ppc_altivec_stvehx:
11952       VT = MVT::i16;
11953       break;
11954     case Intrinsic::ppc_altivec_stvewx:
11955       VT = MVT::i32;
11956       break;
11957     case Intrinsic::ppc_vsx_stxvd2x:
11958       VT = MVT::v2f64;
11959       break;
11960     case Intrinsic::ppc_qpx_qvstfd:
11961       VT = MVT::v4f64;
11962       break;
11963     case Intrinsic::ppc_qpx_qvstfs:
11964       VT = MVT::v4f32;
11965       break;
11966     case Intrinsic::ppc_qpx_qvstfcd:
11967       VT = MVT::v2f64;
11968       break;
11969     case Intrinsic::ppc_qpx_qvstfcs:
11970       VT = MVT::v2f32;
11971       break;
11972     default:
11973       VT = MVT::v4i32;
11974       break;
11975     }
11976 
11977     Info.opc = ISD::INTRINSIC_VOID;
11978     Info.memVT = VT;
11979     Info.ptrVal = I.getArgOperand(1);
11980     Info.offset = -VT.getStoreSize()+1;
11981     Info.size = 2*VT.getStoreSize()-1;
11982     Info.align = 1;
11983     Info.vol = false;
11984     Info.readMem = false;
11985     Info.writeMem = true;
11986     return true;
11987   }
11988   case Intrinsic::ppc_qpx_qvstfda:
11989   case Intrinsic::ppc_qpx_qvstfsa:
11990   case Intrinsic::ppc_qpx_qvstfcda:
11991   case Intrinsic::ppc_qpx_qvstfcsa:
11992   case Intrinsic::ppc_qpx_qvstfiwa: {
11993     EVT VT;
11994     switch (Intrinsic) {
11995     case Intrinsic::ppc_qpx_qvstfda:
11996       VT = MVT::v4f64;
11997       break;
11998     case Intrinsic::ppc_qpx_qvstfsa:
11999       VT = MVT::v4f32;
12000       break;
12001     case Intrinsic::ppc_qpx_qvstfcda:
12002       VT = MVT::v2f64;
12003       break;
12004     case Intrinsic::ppc_qpx_qvstfcsa:
12005       VT = MVT::v2f32;
12006       break;
12007     default:
12008       VT = MVT::v4i32;
12009       break;
12010     }
12011 
12012     Info.opc = ISD::INTRINSIC_VOID;
12013     Info.memVT = VT;
12014     Info.ptrVal = I.getArgOperand(1);
12015     Info.offset = 0;
12016     Info.size = VT.getStoreSize();
12017     Info.align = 1;
12018     Info.vol = false;
12019     Info.readMem = false;
12020     Info.writeMem = true;
12021     return true;
12022   }
12023   default:
12024     break;
12025   }
12026 
12027   return false;
12028 }
12029 
12030 /// getOptimalMemOpType - Returns the target specific optimal type for load
12031 /// and store operations as a result of memset, memcpy, and memmove
12032 /// lowering. If DstAlign is zero that means it's safe to destination
12033 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12034 /// means there isn't a need to check it against alignment requirement,
12035 /// probably because the source does not need to be loaded. If 'IsMemset' is
12036 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12037 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12038 /// source is constant so it does not need to be loaded.
12039 /// It returns EVT::Other if the type should be determined using generic
12040 /// target-independent logic.
12041 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12042                                            unsigned DstAlign, unsigned SrcAlign,
12043                                            bool IsMemset, bool ZeroMemset,
12044                                            bool MemcpyStrSrc,
12045                                            MachineFunction &MF) const {
12046   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12047     const Function *F = MF.getFunction();
12048     // When expanding a memset, require at least two QPX instructions to cover
12049     // the cost of loading the value to be stored from the constant pool.
12050     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12051        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12052         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12053       return MVT::v4f64;
12054     }
12055 
12056     // We should use Altivec/VSX loads and stores when available. For unaligned
12057     // addresses, unaligned VSX loads are only fast starting with the P8.
12058     if (Subtarget.hasAltivec() && Size >= 16 &&
12059         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12060          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12061       return MVT::v4i32;
12062   }
12063 
12064   if (Subtarget.isPPC64()) {
12065     return MVT::i64;
12066   }
12067 
12068   return MVT::i32;
12069 }
12070 
12071 /// \brief Returns true if it is beneficial to convert a load of a constant
12072 /// to just the constant itself.
12073 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12074                                                           Type *Ty) const {
12075   assert(Ty->isIntegerTy());
12076 
12077   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12078   return !(BitSize == 0 || BitSize > 64);
12079 }
12080 
12081 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12082   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12083     return false;
12084   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12085   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12086   return NumBits1 == 64 && NumBits2 == 32;
12087 }
12088 
12089 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12090   if (!VT1.isInteger() || !VT2.isInteger())
12091     return false;
12092   unsigned NumBits1 = VT1.getSizeInBits();
12093   unsigned NumBits2 = VT2.getSizeInBits();
12094   return NumBits1 == 64 && NumBits2 == 32;
12095 }
12096 
12097 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12098   // Generally speaking, zexts are not free, but they are free when they can be
12099   // folded with other operations.
12100   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12101     EVT MemVT = LD->getMemoryVT();
12102     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12103          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12104         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12105          LD->getExtensionType() == ISD::ZEXTLOAD))
12106       return true;
12107   }
12108 
12109   // FIXME: Add other cases...
12110   //  - 32-bit shifts with a zext to i64
12111   //  - zext after ctlz, bswap, etc.
12112   //  - zext after and by a constant mask
12113 
12114   return TargetLowering::isZExtFree(Val, VT2);
12115 }
12116 
12117 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12118   assert(VT.isFloatingPoint());
12119   return true;
12120 }
12121 
12122 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12123   return isInt<16>(Imm) || isUInt<16>(Imm);
12124 }
12125 
12126 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12127   return isInt<16>(Imm) || isUInt<16>(Imm);
12128 }
12129 
12130 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12131                                                        unsigned,
12132                                                        unsigned,
12133                                                        bool *Fast) const {
12134   if (DisablePPCUnaligned)
12135     return false;
12136 
12137   // PowerPC supports unaligned memory access for simple non-vector types.
12138   // Although accessing unaligned addresses is not as efficient as accessing
12139   // aligned addresses, it is generally more efficient than manual expansion,
12140   // and generally only traps for software emulation when crossing page
12141   // boundaries.
12142 
12143   if (!VT.isSimple())
12144     return false;
12145 
12146   if (VT.getSimpleVT().isVector()) {
12147     if (Subtarget.hasVSX()) {
12148       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12149           VT != MVT::v4f32 && VT != MVT::v4i32)
12150         return false;
12151     } else {
12152       return false;
12153     }
12154   }
12155 
12156   if (VT == MVT::ppcf128)
12157     return false;
12158 
12159   if (Fast)
12160     *Fast = true;
12161 
12162   return true;
12163 }
12164 
12165 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12166   VT = VT.getScalarType();
12167 
12168   if (!VT.isSimple())
12169     return false;
12170 
12171   switch (VT.getSimpleVT().SimpleTy) {
12172   case MVT::f32:
12173   case MVT::f64:
12174     return true;
12175   default:
12176     break;
12177   }
12178 
12179   return false;
12180 }
12181 
12182 const MCPhysReg *
12183 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12184   // LR is a callee-save register, but we must treat it as clobbered by any call
12185   // site. Hence we include LR in the scratch registers, which are in turn added
12186   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12187   // to CTR, which is used by any indirect call.
12188   static const MCPhysReg ScratchRegs[] = {
12189     PPC::X12, PPC::LR8, PPC::CTR8, 0
12190   };
12191 
12192   return ScratchRegs;
12193 }
12194 
12195 unsigned PPCTargetLowering::getExceptionPointerRegister(
12196     const Constant *PersonalityFn) const {
12197   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12198 }
12199 
12200 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12201     const Constant *PersonalityFn) const {
12202   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12203 }
12204 
12205 bool
12206 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12207                      EVT VT , unsigned DefinedValues) const {
12208   if (VT == MVT::v2i64)
12209     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12210 
12211   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12212     return true;
12213 
12214   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12215 }
12216 
12217 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12218   if (DisableILPPref || Subtarget.enableMachineScheduler())
12219     return TargetLowering::getSchedulingPreference(N);
12220 
12221   return Sched::ILP;
12222 }
12223 
12224 // Create a fast isel object.
12225 FastISel *
12226 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12227                                   const TargetLibraryInfo *LibInfo) const {
12228   return PPC::createFastISel(FuncInfo, LibInfo);
12229 }
12230 
12231 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12232   if (Subtarget.isDarwinABI()) return;
12233   if (!Subtarget.isPPC64()) return;
12234 
12235   // Update IsSplitCSR in PPCFunctionInfo
12236   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12237   PFI->setIsSplitCSR(true);
12238 }
12239 
12240 void PPCTargetLowering::insertCopiesSplitCSR(
12241   MachineBasicBlock *Entry,
12242   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12243   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12244   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12245   if (!IStart)
12246     return;
12247 
12248   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12249   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12250   MachineBasicBlock::iterator MBBI = Entry->begin();
12251   for (const MCPhysReg *I = IStart; *I; ++I) {
12252     const TargetRegisterClass *RC = nullptr;
12253     if (PPC::G8RCRegClass.contains(*I))
12254       RC = &PPC::G8RCRegClass;
12255     else if (PPC::F8RCRegClass.contains(*I))
12256       RC = &PPC::F8RCRegClass;
12257     else if (PPC::CRRCRegClass.contains(*I))
12258       RC = &PPC::CRRCRegClass;
12259     else if (PPC::VRRCRegClass.contains(*I))
12260       RC = &PPC::VRRCRegClass;
12261     else
12262       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12263 
12264     unsigned NewVR = MRI->createVirtualRegister(RC);
12265     // Create copy from CSR to a virtual register.
12266     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12267     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12268     // nounwind. If we want to generalize this later, we may need to emit
12269     // CFI pseudo-instructions.
12270     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12271              Attribute::NoUnwind) &&
12272            "Function should be nounwind in insertCopiesSplitCSR!");
12273     Entry->addLiveIn(*I);
12274     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12275       .addReg(*I);
12276 
12277     // Insert the copy-back instructions right before the terminator
12278     for (auto *Exit : Exits)
12279       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12280               TII->get(TargetOpcode::COPY), *I)
12281         .addReg(NewVR);
12282   }
12283 }
12284 
12285 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12286 bool PPCTargetLowering::useLoadStackGuardNode() const {
12287   if (!Subtarget.isTargetLinux())
12288     return TargetLowering::useLoadStackGuardNode();
12289   return true;
12290 }
12291 
12292 // Override to disable global variable loading on Linux.
12293 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12294   if (!Subtarget.isTargetLinux())
12295     return TargetLowering::insertSSPDeclarations(M);
12296 }
12297