1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallSite.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/Constant.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/IR/DataLayout.h"
63 #include "llvm/IR/DebugLoc.h"
64 #include "llvm/IR/DerivedTypes.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicsPowerPC.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/MC/MCContext.h"
76 #include "llvm/MC/MCExpr.h"
77 #include "llvm/MC/MCRegisterInfo.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
122 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
125 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
126 
127 STATISTIC(NumTailCalls, "Number of tail calls");
128 STATISTIC(NumSiblingCalls, "Number of sibling calls");
129 
130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
131 
132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
133 
134 // FIXME: Remove this once the bug has been fixed!
135 extern cl::opt<bool> ANDIGlueBug;
136 
137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
138                                      const PPCSubtarget &STI)
139     : TargetLowering(TM), Subtarget(STI) {
140   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
141   // arguments are at least 4/8 bytes aligned.
142   bool isPPC64 = Subtarget.isPPC64();
143   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
144 
145   // Set up the register classes.
146   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
147   if (!useSoftFloat()) {
148     if (hasSPE()) {
149       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
150       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
151     } else {
152       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
153       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
154     }
155   }
156 
157   // Match BITREVERSE to customized fast code sequence in the td file.
158   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
159   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
160 
161   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
162   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
163 
164   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
165   for (MVT VT : MVT::integer_valuetypes()) {
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
168   }
169 
170   if (Subtarget.isISA3_0()) {
171     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
172     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
174     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
175   } else {
176     // No extending loads from f16 or HW conversions back and forth.
177     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
178     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
179     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
180     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
181     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
182     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
183     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
184     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
185   }
186 
187   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
188 
189   // PowerPC has pre-inc load and store's.
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
200   if (!Subtarget.hasSPE()) {
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
202     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
204     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
205   }
206 
207   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
208   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
209   for (MVT VT : ScalarIntVTs) {
210     setOperationAction(ISD::ADDC, VT, Legal);
211     setOperationAction(ISD::ADDE, VT, Legal);
212     setOperationAction(ISD::SUBC, VT, Legal);
213     setOperationAction(ISD::SUBE, VT, Legal);
214   }
215 
216   if (Subtarget.useCRBits()) {
217     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
218 
219     if (isPPC64 || Subtarget.hasFPCVT()) {
220       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
221       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
222                          isPPC64 ? MVT::i64 : MVT::i32);
223       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
224       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
225                         isPPC64 ? MVT::i64 : MVT::i32);
226     } else {
227       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
228       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
229     }
230 
231     // PowerPC does not support direct load/store of condition registers.
232     setOperationAction(ISD::LOAD, MVT::i1, Custom);
233     setOperationAction(ISD::STORE, MVT::i1, Custom);
234 
235     // FIXME: Remove this once the ANDI glue bug is fixed:
236     if (ANDIGlueBug)
237       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
238 
239     for (MVT VT : MVT::integer_valuetypes()) {
240       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
241       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
242       setTruncStoreAction(VT, MVT::i1, Expand);
243     }
244 
245     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
246   }
247 
248   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
249   // PPC (the libcall is not available).
250   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
251   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
252 
253   // We do not currently implement these libm ops for PowerPC.
254   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
255   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
256   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
257   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
258   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
259   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
260 
261   // PowerPC has no SREM/UREM instructions unless we are on P9
262   // On P9 we may use a hardware instruction to compute the remainder.
263   // The instructions are not legalized directly because in the cases where the
264   // result of both the remainder and the division is required it is more
265   // efficient to compute the remainder from the result of the division rather
266   // than use the remainder instruction.
267   if (Subtarget.isISA3_0()) {
268     setOperationAction(ISD::SREM, MVT::i32, Custom);
269     setOperationAction(ISD::UREM, MVT::i32, Custom);
270     setOperationAction(ISD::SREM, MVT::i64, Custom);
271     setOperationAction(ISD::UREM, MVT::i64, Custom);
272   } else {
273     setOperationAction(ISD::SREM, MVT::i32, Expand);
274     setOperationAction(ISD::UREM, MVT::i32, Expand);
275     setOperationAction(ISD::SREM, MVT::i64, Expand);
276     setOperationAction(ISD::UREM, MVT::i64, Expand);
277   }
278 
279   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
280   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
282   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
284   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
288 
289   // Handle constrained floating-point operations of scalar.
290   // TODO: Handle SPE specific operation.
291   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
295 
296   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
297   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
298   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
299   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
300 
301   // We don't support sin/cos/sqrt/fmod/pow
302   setOperationAction(ISD::FSIN , MVT::f64, Expand);
303   setOperationAction(ISD::FCOS , MVT::f64, Expand);
304   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
305   setOperationAction(ISD::FREM , MVT::f64, Expand);
306   setOperationAction(ISD::FPOW , MVT::f64, Expand);
307   setOperationAction(ISD::FSIN , MVT::f32, Expand);
308   setOperationAction(ISD::FCOS , MVT::f32, Expand);
309   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
310   setOperationAction(ISD::FREM , MVT::f32, Expand);
311   setOperationAction(ISD::FPOW , MVT::f32, Expand);
312   if (Subtarget.hasSPE()) {
313     setOperationAction(ISD::FMA  , MVT::f64, Expand);
314     setOperationAction(ISD::FMA  , MVT::f32, Expand);
315   } else {
316     setOperationAction(ISD::FMA  , MVT::f64, Legal);
317     setOperationAction(ISD::FMA  , MVT::f32, Legal);
318   }
319 
320   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
321 
322   // If we're enabling GP optimizations, use hardware square root
323   if (!Subtarget.hasFSQRT() &&
324       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
325         Subtarget.hasFRE()))
326     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
327 
328   if (!Subtarget.hasFSQRT() &&
329       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
330         Subtarget.hasFRES()))
331     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
332 
333   if (Subtarget.hasFCPSGN()) {
334     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
335     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
336   } else {
337     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
338     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
339   }
340 
341   if (Subtarget.hasFPRND()) {
342     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
343     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
344     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
345     setOperationAction(ISD::FROUND, MVT::f64, Legal);
346 
347     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
348     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
349     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
350     setOperationAction(ISD::FROUND, MVT::f32, Legal);
351   }
352 
353   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
354   // to speed up scalar BSWAP64.
355   // CTPOP or CTTZ were introduced in P8/P9 respectively
356   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
357   if (Subtarget.hasP9Vector())
358     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
359   else
360     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
361   if (Subtarget.isISA3_0()) {
362     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
363     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
364   } else {
365     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
366     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
367   }
368 
369   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
370     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
371     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
372   } else {
373     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
374     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
375   }
376 
377   // PowerPC does not have ROTR
378   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
379   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
380 
381   if (!Subtarget.useCRBits()) {
382     // PowerPC does not have Select
383     setOperationAction(ISD::SELECT, MVT::i32, Expand);
384     setOperationAction(ISD::SELECT, MVT::i64, Expand);
385     setOperationAction(ISD::SELECT, MVT::f32, Expand);
386     setOperationAction(ISD::SELECT, MVT::f64, Expand);
387   }
388 
389   // PowerPC wants to turn select_cc of FP into fsel when possible.
390   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
391   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
392 
393   // PowerPC wants to optimize integer setcc a bit
394   if (!Subtarget.useCRBits())
395     setOperationAction(ISD::SETCC, MVT::i32, Custom);
396 
397   // PowerPC does not have BRCOND which requires SetCC
398   if (!Subtarget.useCRBits())
399     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
400 
401   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
402 
403   if (Subtarget.hasSPE()) {
404     // SPE has built-in conversions
405     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
406     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
407     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
408   } else {
409     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
410     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
411 
412     // PowerPC does not have [U|S]INT_TO_FP
413     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
414     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
415   }
416 
417   if (Subtarget.hasDirectMove() && isPPC64) {
418     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
419     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
420     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
421     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
422     if (TM.Options.UnsafeFPMath) {
423       setOperationAction(ISD::LRINT, MVT::f64, Legal);
424       setOperationAction(ISD::LRINT, MVT::f32, Legal);
425       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
426       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
427       setOperationAction(ISD::LROUND, MVT::f64, Legal);
428       setOperationAction(ISD::LROUND, MVT::f32, Legal);
429       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
430       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
431     }
432   } else {
433     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
434     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
435     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
436     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
437   }
438 
439   // We cannot sextinreg(i1).  Expand to shifts.
440   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
441 
442   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
443   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
444   // support continuation, user-level threading, and etc.. As a result, no
445   // other SjLj exception interfaces are implemented and please don't build
446   // your own exception handling based on them.
447   // LLVM/Clang supports zero-cost DWARF exception handling.
448   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
449   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
450 
451   // We want to legalize GlobalAddress and ConstantPool nodes into the
452   // appropriate instructions to materialize the address.
453   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
454   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
455   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
456   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
457   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
458   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
459   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
460   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
461   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
462   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
463 
464   // TRAP is legal.
465   setOperationAction(ISD::TRAP, MVT::Other, Legal);
466 
467   // TRAMPOLINE is custom lowered.
468   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
469   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
470 
471   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
472   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
473 
474   if (Subtarget.is64BitELFABI()) {
475     // VAARG always uses double-word chunks, so promote anything smaller.
476     setOperationAction(ISD::VAARG, MVT::i1, Promote);
477     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
478     setOperationAction(ISD::VAARG, MVT::i8, Promote);
479     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
480     setOperationAction(ISD::VAARG, MVT::i16, Promote);
481     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
482     setOperationAction(ISD::VAARG, MVT::i32, Promote);
483     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
484     setOperationAction(ISD::VAARG, MVT::Other, Expand);
485   } else if (Subtarget.is32BitELFABI()) {
486     // VAARG is custom lowered with the 32-bit SVR4 ABI.
487     setOperationAction(ISD::VAARG, MVT::Other, Custom);
488     setOperationAction(ISD::VAARG, MVT::i64, Custom);
489   } else
490     setOperationAction(ISD::VAARG, MVT::Other, Expand);
491 
492   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
493   if (Subtarget.is32BitELFABI())
494     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
495   else
496     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
497 
498   // Use the default implementation.
499   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
500   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
501   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
502   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
503   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
504   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
505   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
506   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
507   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
508 
509   // We want to custom lower some of our intrinsics.
510   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
511 
512   // To handle counter-based loop conditions.
513   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
514 
515   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
516   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
517   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
518   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
519 
520   // Comparisons that require checking two conditions.
521   if (Subtarget.hasSPE()) {
522     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
523     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
524     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
525     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
526   }
527   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
528   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
529   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
530   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
531   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
532   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
533   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
534   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
535   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
536   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
537   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
538   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
539 
540   if (Subtarget.has64BitSupport()) {
541     // They also have instructions for converting between i64 and fp.
542     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
543     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
544     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
545     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
546     // This is just the low 32 bits of a (signed) fp->i64 conversion.
547     // We cannot do this with Promote because i64 is not a legal type.
548     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
549 
550     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
551       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
552   } else {
553     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
554     if (Subtarget.hasSPE())
555       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
556     else
557       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
558   }
559 
560   // With the instructions enabled under FPCVT, we can do everything.
561   if (Subtarget.hasFPCVT()) {
562     if (Subtarget.has64BitSupport()) {
563       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
564       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
565       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
566       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
567     }
568 
569     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
570     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
571     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
572     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
573   }
574 
575   if (Subtarget.use64BitRegs()) {
576     // 64-bit PowerPC implementations can support i64 types directly
577     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
578     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
579     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
580     // 64-bit PowerPC wants to expand i128 shifts itself.
581     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
582     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
583     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
584   } else {
585     // 32-bit PowerPC wants to expand i64 shifts itself.
586     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
587     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
588     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
589   }
590 
591   if (Subtarget.hasVSX()) {
592     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
593     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
594     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
595     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
596   }
597 
598   if (Subtarget.hasAltivec()) {
599     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
600       setOperationAction(ISD::SADDSAT, VT, Legal);
601       setOperationAction(ISD::SSUBSAT, VT, Legal);
602       setOperationAction(ISD::UADDSAT, VT, Legal);
603       setOperationAction(ISD::USUBSAT, VT, Legal);
604     }
605     // First set operation action for all vector types to expand. Then we
606     // will selectively turn on ones that can be effectively codegen'd.
607     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
608       // add/sub are legal for all supported vector VT's.
609       setOperationAction(ISD::ADD, VT, Legal);
610       setOperationAction(ISD::SUB, VT, Legal);
611 
612       // For v2i64, these are only valid with P8Vector. This is corrected after
613       // the loop.
614       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
615         setOperationAction(ISD::SMAX, VT, Legal);
616         setOperationAction(ISD::SMIN, VT, Legal);
617         setOperationAction(ISD::UMAX, VT, Legal);
618         setOperationAction(ISD::UMIN, VT, Legal);
619       }
620       else {
621         setOperationAction(ISD::SMAX, VT, Expand);
622         setOperationAction(ISD::SMIN, VT, Expand);
623         setOperationAction(ISD::UMAX, VT, Expand);
624         setOperationAction(ISD::UMIN, VT, Expand);
625       }
626 
627       if (Subtarget.hasVSX()) {
628         setOperationAction(ISD::FMAXNUM, VT, Legal);
629         setOperationAction(ISD::FMINNUM, VT, Legal);
630       }
631 
632       // Vector instructions introduced in P8
633       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
634         setOperationAction(ISD::CTPOP, VT, Legal);
635         setOperationAction(ISD::CTLZ, VT, Legal);
636       }
637       else {
638         setOperationAction(ISD::CTPOP, VT, Expand);
639         setOperationAction(ISD::CTLZ, VT, Expand);
640       }
641 
642       // Vector instructions introduced in P9
643       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
644         setOperationAction(ISD::CTTZ, VT, Legal);
645       else
646         setOperationAction(ISD::CTTZ, VT, Expand);
647 
648       // We promote all shuffles to v16i8.
649       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
650       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
651 
652       // We promote all non-typed operations to v4i32.
653       setOperationAction(ISD::AND   , VT, Promote);
654       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
655       setOperationAction(ISD::OR    , VT, Promote);
656       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
657       setOperationAction(ISD::XOR   , VT, Promote);
658       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
659       setOperationAction(ISD::LOAD  , VT, Promote);
660       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
661       setOperationAction(ISD::SELECT, VT, Promote);
662       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
663       setOperationAction(ISD::VSELECT, VT, Legal);
664       setOperationAction(ISD::SELECT_CC, VT, Promote);
665       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
666       setOperationAction(ISD::STORE, VT, Promote);
667       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
668 
669       // No other operations are legal.
670       setOperationAction(ISD::MUL , VT, Expand);
671       setOperationAction(ISD::SDIV, VT, Expand);
672       setOperationAction(ISD::SREM, VT, Expand);
673       setOperationAction(ISD::UDIV, VT, Expand);
674       setOperationAction(ISD::UREM, VT, Expand);
675       setOperationAction(ISD::FDIV, VT, Expand);
676       setOperationAction(ISD::FREM, VT, Expand);
677       setOperationAction(ISD::FNEG, VT, Expand);
678       setOperationAction(ISD::FSQRT, VT, Expand);
679       setOperationAction(ISD::FLOG, VT, Expand);
680       setOperationAction(ISD::FLOG10, VT, Expand);
681       setOperationAction(ISD::FLOG2, VT, Expand);
682       setOperationAction(ISD::FEXP, VT, Expand);
683       setOperationAction(ISD::FEXP2, VT, Expand);
684       setOperationAction(ISD::FSIN, VT, Expand);
685       setOperationAction(ISD::FCOS, VT, Expand);
686       setOperationAction(ISD::FABS, VT, Expand);
687       setOperationAction(ISD::FFLOOR, VT, Expand);
688       setOperationAction(ISD::FCEIL,  VT, Expand);
689       setOperationAction(ISD::FTRUNC, VT, Expand);
690       setOperationAction(ISD::FRINT,  VT, Expand);
691       setOperationAction(ISD::FNEARBYINT, VT, Expand);
692       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
693       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
694       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
695       setOperationAction(ISD::MULHU, VT, Expand);
696       setOperationAction(ISD::MULHS, VT, Expand);
697       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
698       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
699       setOperationAction(ISD::UDIVREM, VT, Expand);
700       setOperationAction(ISD::SDIVREM, VT, Expand);
701       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
702       setOperationAction(ISD::FPOW, VT, Expand);
703       setOperationAction(ISD::BSWAP, VT, Expand);
704       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
705       setOperationAction(ISD::ROTL, VT, Expand);
706       setOperationAction(ISD::ROTR, VT, Expand);
707 
708       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
709         setTruncStoreAction(VT, InnerVT, Expand);
710         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
711         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
712         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
713       }
714     }
715     if (!Subtarget.hasP8Vector()) {
716       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
717       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
718       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
719       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
720     }
721 
722     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
723       setOperationAction(ISD::ABS, VT, Custom);
724 
725     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
726     // with merges, splats, etc.
727     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
728 
729     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
730     // are cheap, so handle them before they get expanded to scalar.
731     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
732     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
733     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
734     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
735     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
736 
737     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
738     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
739     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
740     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
741     setOperationAction(ISD::SELECT, MVT::v4i32,
742                        Subtarget.useCRBits() ? Legal : Expand);
743     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
744     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
745     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
746     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
747     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
748     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
749     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
750     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
751     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
752 
753     // Without hasP8Altivec set, v2i64 SMAX isn't available.
754     // But ABS custom lowering requires SMAX support.
755     if (!Subtarget.hasP8Altivec())
756       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
757 
758     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
759     if (Subtarget.hasAltivec())
760       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
761         setOperationAction(ISD::ROTL, VT, Legal);
762     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
763     if (Subtarget.hasP8Altivec())
764       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
765 
766     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
767     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
768     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
769     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
770 
771     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
772     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
773 
774     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
775       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
776       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
777     }
778 
779     if (Subtarget.hasP8Altivec())
780       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
781     else
782       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
783 
784     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
785     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
786 
787     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
788     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
789 
790     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
791     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
792     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
793     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
794 
795     // Altivec does not contain unordered floating-point compare instructions
796     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
797     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
798     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
799     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
800 
801     if (Subtarget.hasVSX()) {
802       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
803       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
804       if (Subtarget.hasP8Vector()) {
805         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
806         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
807       }
808       if (Subtarget.hasDirectMove() && isPPC64) {
809         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
810         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
811         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
812         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
813         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
814         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
816         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
817       }
818       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
819 
820       // The nearbyint variants are not allowed to raise the inexact exception
821       // so we can only code-gen them with unsafe math.
822       if (TM.Options.UnsafeFPMath) {
823         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
824         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
825       }
826 
827       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
828       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
829       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
830       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
831       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
832       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
833       setOperationAction(ISD::FROUND, MVT::f64, Legal);
834       setOperationAction(ISD::FRINT, MVT::f64, Legal);
835 
836       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
837       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
838       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
839       setOperationAction(ISD::FROUND, MVT::f32, Legal);
840       setOperationAction(ISD::FRINT, MVT::f32, Legal);
841 
842       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
843       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
844 
845       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
846       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
847 
848       // Share the Altivec comparison restrictions.
849       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
850       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
851       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
852       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
853 
854       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
855       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
856 
857       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
858 
859       if (Subtarget.hasP8Vector())
860         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
861 
862       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
863 
864       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
865       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
866       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
867 
868       if (Subtarget.hasP8Altivec()) {
869         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
870         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
871         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
872 
873         // 128 bit shifts can be accomplished via 3 instructions for SHL and
874         // SRL, but not for SRA because of the instructions available:
875         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
876         // doing
877         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
878         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
879         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
880 
881         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
882       }
883       else {
884         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
885         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
886         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
887 
888         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 
890         // VSX v2i64 only supports non-arithmetic operations.
891         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
892         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
893       }
894 
895       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
896       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
897       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
898       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
899 
900       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
901 
902       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
903       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
904       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
905       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
906 
907       // Custom handling for partial vectors of integers converted to
908       // floating point. We already have optimal handling for v2i32 through
909       // the DAG combine, so those aren't necessary.
910       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
911       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
912       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
913       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
914       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
915       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
916       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
917       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
918 
919       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
920       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
921       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
922       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
923       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
924       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
925 
926       if (Subtarget.hasDirectMove())
927         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
928       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
929 
930       // Handle constrained floating-point operations of vector.
931       // The predictor is `hasVSX` because altivec instruction has
932       // no exception but VSX vector instruction has.
933       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
934       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
935       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
936       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
937 
938       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
939       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
940       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
941       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
942 
943       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
944     }
945 
946     if (Subtarget.hasP8Altivec()) {
947       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
948       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
949     }
950 
951     if (Subtarget.hasP9Vector()) {
952       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
953       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
954 
955       // 128 bit shifts can be accomplished via 3 instructions for SHL and
956       // SRL, but not for SRA because of the instructions available:
957       // VS{RL} and VS{RL}O.
958       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
959       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
960       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
961 
962       if (EnableQuadPrecision) {
963         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
964         setOperationAction(ISD::FADD, MVT::f128, Legal);
965         setOperationAction(ISD::FSUB, MVT::f128, Legal);
966         setOperationAction(ISD::FDIV, MVT::f128, Legal);
967         setOperationAction(ISD::FMUL, MVT::f128, Legal);
968         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
969         // No extending loads to f128 on PPC.
970         for (MVT FPT : MVT::fp_valuetypes())
971           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
972         setOperationAction(ISD::FMA, MVT::f128, Legal);
973         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
974         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
975         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
976         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
977         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
978         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
979 
980         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
981         setOperationAction(ISD::FRINT, MVT::f128, Legal);
982         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
983         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
984         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
985         setOperationAction(ISD::FROUND, MVT::f128, Legal);
986 
987         setOperationAction(ISD::SELECT, MVT::f128, Expand);
988         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
989         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
990         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
991         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
992         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
993         // No implementation for these ops for PowerPC.
994         setOperationAction(ISD::FSIN , MVT::f128, Expand);
995         setOperationAction(ISD::FCOS , MVT::f128, Expand);
996         setOperationAction(ISD::FPOW, MVT::f128, Expand);
997         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
998         setOperationAction(ISD::FREM, MVT::f128, Expand);
999 
1000         // Handle constrained floating-point operations of fp128
1001         setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1002         setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1003         setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1004         setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1005       }
1006       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1007       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1008       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1009       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1010       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1011     }
1012 
1013     if (Subtarget.hasP9Altivec()) {
1014       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1015       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1016 
1017       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1018       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1019       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1020       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1021       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1022       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1023       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1024     }
1025   }
1026 
1027   if (Subtarget.hasQPX()) {
1028     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1030     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1031     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
1032 
1033     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
1034     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
1035 
1036     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
1037     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
1038 
1039     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
1040     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
1041 
1042     if (!Subtarget.useCRBits())
1043       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
1044     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1045 
1046     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
1047     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
1048     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
1049     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
1050     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
1051     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1052     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1053 
1054     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1055     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1056 
1057     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1058     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1059 
1060     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1061     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1062     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1063     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1064     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1065     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1066     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1067     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1068     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1069     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1070 
1071     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1072     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1073 
1074     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1075     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1076 
1077     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1078 
1079     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1080     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1081     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1082     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1083 
1084     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1085     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1086 
1087     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1088     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1089 
1090     if (!Subtarget.useCRBits())
1091       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1092     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1093 
1094     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1095     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1096     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1097     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1098     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1099     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1100     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1101 
1102     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1103     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1104 
1105     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1106     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1107     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1108     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1109     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1110     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1111     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1112     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1113     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1114     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1115 
1116     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1117     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1118 
1119     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1120     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1121 
1122     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1123 
1124     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1125     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1126     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1127 
1128     if (!Subtarget.useCRBits())
1129       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1130     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1131 
1132     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1133     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1134 
1135     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1137     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1138     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1139     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1140     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1141     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1142 
1143     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1144     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1145 
1146     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1147 
1148     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1149     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1150     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1151     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1152 
1153     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1154     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1155     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1156     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1157 
1158     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1159     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1160 
1161     // These need to set FE_INEXACT, and so cannot be vectorized here.
1162     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1163     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1164 
1165     if (TM.Options.UnsafeFPMath) {
1166       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1167       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1168 
1169       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1170       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1171     } else {
1172       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1173       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1174 
1175       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1176       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1177     }
1178 
1179     // TODO: Handle constrained floating-point operations of v4f64
1180   }
1181 
1182   if (Subtarget.has64BitSupport())
1183     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1184 
1185   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1186 
1187   if (!isPPC64) {
1188     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1189     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1190   }
1191 
1192   setBooleanContents(ZeroOrOneBooleanContent);
1193 
1194   if (Subtarget.hasAltivec()) {
1195     // Altivec instructions set fields to all zeros or all ones.
1196     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1197   }
1198 
1199   if (!isPPC64) {
1200     // These libcalls are not available in 32-bit.
1201     setLibcallName(RTLIB::SHL_I128, nullptr);
1202     setLibcallName(RTLIB::SRL_I128, nullptr);
1203     setLibcallName(RTLIB::SRA_I128, nullptr);
1204   }
1205 
1206   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1207 
1208   // We have target-specific dag combine patterns for the following nodes:
1209   setTargetDAGCombine(ISD::ADD);
1210   setTargetDAGCombine(ISD::SHL);
1211   setTargetDAGCombine(ISD::SRA);
1212   setTargetDAGCombine(ISD::SRL);
1213   setTargetDAGCombine(ISD::MUL);
1214   setTargetDAGCombine(ISD::SINT_TO_FP);
1215   setTargetDAGCombine(ISD::BUILD_VECTOR);
1216   if (Subtarget.hasFPCVT())
1217     setTargetDAGCombine(ISD::UINT_TO_FP);
1218   setTargetDAGCombine(ISD::LOAD);
1219   setTargetDAGCombine(ISD::STORE);
1220   setTargetDAGCombine(ISD::BR_CC);
1221   if (Subtarget.useCRBits())
1222     setTargetDAGCombine(ISD::BRCOND);
1223   setTargetDAGCombine(ISD::BSWAP);
1224   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1225   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1226   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1227 
1228   setTargetDAGCombine(ISD::SIGN_EXTEND);
1229   setTargetDAGCombine(ISD::ZERO_EXTEND);
1230   setTargetDAGCombine(ISD::ANY_EXTEND);
1231 
1232   setTargetDAGCombine(ISD::TRUNCATE);
1233   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1234 
1235 
1236   if (Subtarget.useCRBits()) {
1237     setTargetDAGCombine(ISD::TRUNCATE);
1238     setTargetDAGCombine(ISD::SETCC);
1239     setTargetDAGCombine(ISD::SELECT_CC);
1240   }
1241 
1242   // Use reciprocal estimates.
1243   if (TM.Options.UnsafeFPMath) {
1244     setTargetDAGCombine(ISD::FDIV);
1245     setTargetDAGCombine(ISD::FSQRT);
1246   }
1247 
1248   if (Subtarget.hasP9Altivec()) {
1249     setTargetDAGCombine(ISD::ABS);
1250     setTargetDAGCombine(ISD::VSELECT);
1251   }
1252 
1253   if (EnableQuadPrecision) {
1254     setLibcallName(RTLIB::LOG_F128, "logf128");
1255     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1256     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1257     setLibcallName(RTLIB::EXP_F128, "expf128");
1258     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1259     setLibcallName(RTLIB::SIN_F128, "sinf128");
1260     setLibcallName(RTLIB::COS_F128, "cosf128");
1261     setLibcallName(RTLIB::POW_F128, "powf128");
1262     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1263     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1264     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1265     setLibcallName(RTLIB::REM_F128, "fmodf128");
1266   }
1267 
1268   // With 32 condition bits, we don't need to sink (and duplicate) compares
1269   // aggressively in CodeGenPrep.
1270   if (Subtarget.useCRBits()) {
1271     setHasMultipleConditionRegisters();
1272     setJumpIsExpensive();
1273   }
1274 
1275   setMinFunctionAlignment(Align(4));
1276 
1277   switch (Subtarget.getCPUDirective()) {
1278   default: break;
1279   case PPC::DIR_970:
1280   case PPC::DIR_A2:
1281   case PPC::DIR_E500:
1282   case PPC::DIR_E500mc:
1283   case PPC::DIR_E5500:
1284   case PPC::DIR_PWR4:
1285   case PPC::DIR_PWR5:
1286   case PPC::DIR_PWR5X:
1287   case PPC::DIR_PWR6:
1288   case PPC::DIR_PWR6X:
1289   case PPC::DIR_PWR7:
1290   case PPC::DIR_PWR8:
1291   case PPC::DIR_PWR9:
1292   case PPC::DIR_PWR_FUTURE:
1293     setPrefLoopAlignment(Align(16));
1294     setPrefFunctionAlignment(Align(16));
1295     break;
1296   }
1297 
1298   if (Subtarget.enableMachineScheduler())
1299     setSchedulingPreference(Sched::Source);
1300   else
1301     setSchedulingPreference(Sched::Hybrid);
1302 
1303   computeRegisterProperties(STI.getRegisterInfo());
1304 
1305   // The Freescale cores do better with aggressive inlining of memcpy and
1306   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1307   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1308       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1309     MaxStoresPerMemset = 32;
1310     MaxStoresPerMemsetOptSize = 16;
1311     MaxStoresPerMemcpy = 32;
1312     MaxStoresPerMemcpyOptSize = 8;
1313     MaxStoresPerMemmove = 32;
1314     MaxStoresPerMemmoveOptSize = 8;
1315   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1316     // The A2 also benefits from (very) aggressive inlining of memcpy and
1317     // friends. The overhead of a the function call, even when warm, can be
1318     // over one hundred cycles.
1319     MaxStoresPerMemset = 128;
1320     MaxStoresPerMemcpy = 128;
1321     MaxStoresPerMemmove = 128;
1322     MaxLoadsPerMemcmp = 128;
1323   } else {
1324     MaxLoadsPerMemcmp = 8;
1325     MaxLoadsPerMemcmpOptSize = 4;
1326   }
1327 }
1328 
1329 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1330 /// the desired ByVal argument alignment.
1331 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1332                              unsigned MaxMaxAlign) {
1333   if (MaxAlign == MaxMaxAlign)
1334     return;
1335   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1336     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1337       MaxAlign = 32;
1338     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1339       MaxAlign = 16;
1340   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1341     unsigned EltAlign = 0;
1342     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1343     if (EltAlign > MaxAlign)
1344       MaxAlign = EltAlign;
1345   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1346     for (auto *EltTy : STy->elements()) {
1347       unsigned EltAlign = 0;
1348       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1349       if (EltAlign > MaxAlign)
1350         MaxAlign = EltAlign;
1351       if (MaxAlign == MaxMaxAlign)
1352         break;
1353     }
1354   }
1355 }
1356 
1357 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1358 /// function arguments in the caller parameter area.
1359 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1360                                                   const DataLayout &DL) const {
1361   // 16byte and wider vectors are passed on 16byte boundary.
1362   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1363   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1364   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1365     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1366   return Align;
1367 }
1368 
1369 bool PPCTargetLowering::useSoftFloat() const {
1370   return Subtarget.useSoftFloat();
1371 }
1372 
1373 bool PPCTargetLowering::hasSPE() const {
1374   return Subtarget.hasSPE();
1375 }
1376 
1377 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1378   return VT.isScalarInteger();
1379 }
1380 
1381 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1382   switch ((PPCISD::NodeType)Opcode) {
1383   case PPCISD::FIRST_NUMBER:    break;
1384   case PPCISD::FSEL:            return "PPCISD::FSEL";
1385   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1386   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1387   case PPCISD::FCFID:           return "PPCISD::FCFID";
1388   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1389   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1390   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1391   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1392   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1393   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1394   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1395   case PPCISD::FP_TO_UINT_IN_VSR:
1396                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1397   case PPCISD::FP_TO_SINT_IN_VSR:
1398                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1399   case PPCISD::FRE:             return "PPCISD::FRE";
1400   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1401   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1402   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1403   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1404   case PPCISD::VPERM:           return "PPCISD::VPERM";
1405   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1406   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1407   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1408   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1409   case PPCISD::CMPB:            return "PPCISD::CMPB";
1410   case PPCISD::Hi:              return "PPCISD::Hi";
1411   case PPCISD::Lo:              return "PPCISD::Lo";
1412   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1413   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1414   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1415   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1416   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1417   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1418   case PPCISD::SRL:             return "PPCISD::SRL";
1419   case PPCISD::SRA:             return "PPCISD::SRA";
1420   case PPCISD::SHL:             return "PPCISD::SHL";
1421   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1422   case PPCISD::CALL:            return "PPCISD::CALL";
1423   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1424   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1425   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1426   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1427   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1428   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1429   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1430   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1431   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1432   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1433   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1434   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1435   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1436   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1437   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1438   case PPCISD::ANDI_rec_1_EQ_BIT:
1439     return "PPCISD::ANDI_rec_1_EQ_BIT";
1440   case PPCISD::ANDI_rec_1_GT_BIT:
1441     return "PPCISD::ANDI_rec_1_GT_BIT";
1442   case PPCISD::VCMP:            return "PPCISD::VCMP";
1443   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1444   case PPCISD::LBRX:            return "PPCISD::LBRX";
1445   case PPCISD::STBRX:           return "PPCISD::STBRX";
1446   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1447   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1448   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1449   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1450   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1451   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1452   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1453   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1454   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1455   case PPCISD::ST_VSR_SCAL_INT:
1456                                 return "PPCISD::ST_VSR_SCAL_INT";
1457   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1458   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1459   case PPCISD::BDZ:             return "PPCISD::BDZ";
1460   case PPCISD::MFFS:            return "PPCISD::MFFS";
1461   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1462   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1463   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1464   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1465   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1466   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1467   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1468   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1469   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1470   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1471   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1472   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1473   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1474   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1475   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1476   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1477   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1478   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1479   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1480   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1481   case PPCISD::SC:              return "PPCISD::SC";
1482   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1483   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1484   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1485   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1486   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1487   case PPCISD::VABSD:           return "PPCISD::VABSD";
1488   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1489   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1490   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1491   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1492   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1493   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1494   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1495   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1496   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1497   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1498   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1499   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1500   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1501   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1502   }
1503   return nullptr;
1504 }
1505 
1506 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1507                                           EVT VT) const {
1508   if (!VT.isVector())
1509     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1510 
1511   if (Subtarget.hasQPX())
1512     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1513 
1514   return VT.changeVectorElementTypeToInteger();
1515 }
1516 
1517 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1518   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1519   return true;
1520 }
1521 
1522 //===----------------------------------------------------------------------===//
1523 // Node matching predicates, for use by the tblgen matching code.
1524 //===----------------------------------------------------------------------===//
1525 
1526 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1527 static bool isFloatingPointZero(SDValue Op) {
1528   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1529     return CFP->getValueAPF().isZero();
1530   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1531     // Maybe this has already been legalized into the constant pool?
1532     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1533       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1534         return CFP->getValueAPF().isZero();
1535   }
1536   return false;
1537 }
1538 
1539 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1540 /// true if Op is undef or if it matches the specified value.
1541 static bool isConstantOrUndef(int Op, int Val) {
1542   return Op < 0 || Op == Val;
1543 }
1544 
1545 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1546 /// VPKUHUM instruction.
1547 /// The ShuffleKind distinguishes between big-endian operations with
1548 /// two different inputs (0), either-endian operations with two identical
1549 /// inputs (1), and little-endian operations with two different inputs (2).
1550 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1551 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1552                                SelectionDAG &DAG) {
1553   bool IsLE = DAG.getDataLayout().isLittleEndian();
1554   if (ShuffleKind == 0) {
1555     if (IsLE)
1556       return false;
1557     for (unsigned i = 0; i != 16; ++i)
1558       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1559         return false;
1560   } else if (ShuffleKind == 2) {
1561     if (!IsLE)
1562       return false;
1563     for (unsigned i = 0; i != 16; ++i)
1564       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1565         return false;
1566   } else if (ShuffleKind == 1) {
1567     unsigned j = IsLE ? 0 : 1;
1568     for (unsigned i = 0; i != 8; ++i)
1569       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1570           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1571         return false;
1572   }
1573   return true;
1574 }
1575 
1576 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1577 /// VPKUWUM instruction.
1578 /// The ShuffleKind distinguishes between big-endian operations with
1579 /// two different inputs (0), either-endian operations with two identical
1580 /// inputs (1), and little-endian operations with two different inputs (2).
1581 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1582 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1583                                SelectionDAG &DAG) {
1584   bool IsLE = DAG.getDataLayout().isLittleEndian();
1585   if (ShuffleKind == 0) {
1586     if (IsLE)
1587       return false;
1588     for (unsigned i = 0; i != 16; i += 2)
1589       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1590           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1591         return false;
1592   } else if (ShuffleKind == 2) {
1593     if (!IsLE)
1594       return false;
1595     for (unsigned i = 0; i != 16; i += 2)
1596       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1597           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1598         return false;
1599   } else if (ShuffleKind == 1) {
1600     unsigned j = IsLE ? 0 : 2;
1601     for (unsigned i = 0; i != 8; i += 2)
1602       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1603           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1604           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1605           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1606         return false;
1607   }
1608   return true;
1609 }
1610 
1611 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1612 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1613 /// current subtarget.
1614 ///
1615 /// The ShuffleKind distinguishes between big-endian operations with
1616 /// two different inputs (0), either-endian operations with two identical
1617 /// inputs (1), and little-endian operations with two different inputs (2).
1618 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1619 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1620                                SelectionDAG &DAG) {
1621   const PPCSubtarget& Subtarget =
1622       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1623   if (!Subtarget.hasP8Vector())
1624     return false;
1625 
1626   bool IsLE = DAG.getDataLayout().isLittleEndian();
1627   if (ShuffleKind == 0) {
1628     if (IsLE)
1629       return false;
1630     for (unsigned i = 0; i != 16; i += 4)
1631       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1632           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1633           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1634           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1635         return false;
1636   } else if (ShuffleKind == 2) {
1637     if (!IsLE)
1638       return false;
1639     for (unsigned i = 0; i != 16; i += 4)
1640       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1641           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1642           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1643           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1644         return false;
1645   } else if (ShuffleKind == 1) {
1646     unsigned j = IsLE ? 0 : 4;
1647     for (unsigned i = 0; i != 8; i += 4)
1648       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1649           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1650           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1651           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1652           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1653           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1654           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1655           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1656         return false;
1657   }
1658   return true;
1659 }
1660 
1661 /// isVMerge - Common function, used to match vmrg* shuffles.
1662 ///
1663 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1664                      unsigned LHSStart, unsigned RHSStart) {
1665   if (N->getValueType(0) != MVT::v16i8)
1666     return false;
1667   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1668          "Unsupported merge size!");
1669 
1670   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1671     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1672       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1673                              LHSStart+j+i*UnitSize) ||
1674           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1675                              RHSStart+j+i*UnitSize))
1676         return false;
1677     }
1678   return true;
1679 }
1680 
1681 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1682 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1683 /// The ShuffleKind distinguishes between big-endian merges with two
1684 /// different inputs (0), either-endian merges with two identical inputs (1),
1685 /// and little-endian merges with two different inputs (2).  For the latter,
1686 /// the input operands are swapped (see PPCInstrAltivec.td).
1687 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1688                              unsigned ShuffleKind, SelectionDAG &DAG) {
1689   if (DAG.getDataLayout().isLittleEndian()) {
1690     if (ShuffleKind == 1) // unary
1691       return isVMerge(N, UnitSize, 0, 0);
1692     else if (ShuffleKind == 2) // swapped
1693       return isVMerge(N, UnitSize, 0, 16);
1694     else
1695       return false;
1696   } else {
1697     if (ShuffleKind == 1) // unary
1698       return isVMerge(N, UnitSize, 8, 8);
1699     else if (ShuffleKind == 0) // normal
1700       return isVMerge(N, UnitSize, 8, 24);
1701     else
1702       return false;
1703   }
1704 }
1705 
1706 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1707 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1708 /// The ShuffleKind distinguishes between big-endian merges with two
1709 /// different inputs (0), either-endian merges with two identical inputs (1),
1710 /// and little-endian merges with two different inputs (2).  For the latter,
1711 /// the input operands are swapped (see PPCInstrAltivec.td).
1712 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1713                              unsigned ShuffleKind, SelectionDAG &DAG) {
1714   if (DAG.getDataLayout().isLittleEndian()) {
1715     if (ShuffleKind == 1) // unary
1716       return isVMerge(N, UnitSize, 8, 8);
1717     else if (ShuffleKind == 2) // swapped
1718       return isVMerge(N, UnitSize, 8, 24);
1719     else
1720       return false;
1721   } else {
1722     if (ShuffleKind == 1) // unary
1723       return isVMerge(N, UnitSize, 0, 0);
1724     else if (ShuffleKind == 0) // normal
1725       return isVMerge(N, UnitSize, 0, 16);
1726     else
1727       return false;
1728   }
1729 }
1730 
1731 /**
1732  * Common function used to match vmrgew and vmrgow shuffles
1733  *
1734  * The indexOffset determines whether to look for even or odd words in
1735  * the shuffle mask. This is based on the of the endianness of the target
1736  * machine.
1737  *   - Little Endian:
1738  *     - Use offset of 0 to check for odd elements
1739  *     - Use offset of 4 to check for even elements
1740  *   - Big Endian:
1741  *     - Use offset of 0 to check for even elements
1742  *     - Use offset of 4 to check for odd elements
1743  * A detailed description of the vector element ordering for little endian and
1744  * big endian can be found at
1745  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1746  * Targeting your applications - what little endian and big endian IBM XL C/C++
1747  * compiler differences mean to you
1748  *
1749  * The mask to the shuffle vector instruction specifies the indices of the
1750  * elements from the two input vectors to place in the result. The elements are
1751  * numbered in array-access order, starting with the first vector. These vectors
1752  * are always of type v16i8, thus each vector will contain 16 elements of size
1753  * 8. More info on the shuffle vector can be found in the
1754  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1755  * Language Reference.
1756  *
1757  * The RHSStartValue indicates whether the same input vectors are used (unary)
1758  * or two different input vectors are used, based on the following:
1759  *   - If the instruction uses the same vector for both inputs, the range of the
1760  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1761  *     be 0.
1762  *   - If the instruction has two different vectors then the range of the
1763  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1764  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1765  *     to 31 specify elements in the second vector).
1766  *
1767  * \param[in] N The shuffle vector SD Node to analyze
1768  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1769  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1770  * vector to the shuffle_vector instruction
1771  * \return true iff this shuffle vector represents an even or odd word merge
1772  */
1773 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1774                      unsigned RHSStartValue) {
1775   if (N->getValueType(0) != MVT::v16i8)
1776     return false;
1777 
1778   for (unsigned i = 0; i < 2; ++i)
1779     for (unsigned j = 0; j < 4; ++j)
1780       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1781                              i*RHSStartValue+j+IndexOffset) ||
1782           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1783                              i*RHSStartValue+j+IndexOffset+8))
1784         return false;
1785   return true;
1786 }
1787 
1788 /**
1789  * Determine if the specified shuffle mask is suitable for the vmrgew or
1790  * vmrgow instructions.
1791  *
1792  * \param[in] N The shuffle vector SD Node to analyze
1793  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1794  * \param[in] ShuffleKind Identify the type of merge:
1795  *   - 0 = big-endian merge with two different inputs;
1796  *   - 1 = either-endian merge with two identical inputs;
1797  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1798  *     little-endian merges).
1799  * \param[in] DAG The current SelectionDAG
1800  * \return true iff this shuffle mask
1801  */
1802 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1803                               unsigned ShuffleKind, SelectionDAG &DAG) {
1804   if (DAG.getDataLayout().isLittleEndian()) {
1805     unsigned indexOffset = CheckEven ? 4 : 0;
1806     if (ShuffleKind == 1) // Unary
1807       return isVMerge(N, indexOffset, 0);
1808     else if (ShuffleKind == 2) // swapped
1809       return isVMerge(N, indexOffset, 16);
1810     else
1811       return false;
1812   }
1813   else {
1814     unsigned indexOffset = CheckEven ? 0 : 4;
1815     if (ShuffleKind == 1) // Unary
1816       return isVMerge(N, indexOffset, 0);
1817     else if (ShuffleKind == 0) // Normal
1818       return isVMerge(N, indexOffset, 16);
1819     else
1820       return false;
1821   }
1822   return false;
1823 }
1824 
1825 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1826 /// amount, otherwise return -1.
1827 /// The ShuffleKind distinguishes between big-endian operations with two
1828 /// different inputs (0), either-endian operations with two identical inputs
1829 /// (1), and little-endian operations with two different inputs (2).  For the
1830 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1831 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1832                              SelectionDAG &DAG) {
1833   if (N->getValueType(0) != MVT::v16i8)
1834     return -1;
1835 
1836   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1837 
1838   // Find the first non-undef value in the shuffle mask.
1839   unsigned i;
1840   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1841     /*search*/;
1842 
1843   if (i == 16) return -1;  // all undef.
1844 
1845   // Otherwise, check to see if the rest of the elements are consecutively
1846   // numbered from this value.
1847   unsigned ShiftAmt = SVOp->getMaskElt(i);
1848   if (ShiftAmt < i) return -1;
1849 
1850   ShiftAmt -= i;
1851   bool isLE = DAG.getDataLayout().isLittleEndian();
1852 
1853   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1854     // Check the rest of the elements to see if they are consecutive.
1855     for (++i; i != 16; ++i)
1856       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1857         return -1;
1858   } else if (ShuffleKind == 1) {
1859     // Check the rest of the elements to see if they are consecutive.
1860     for (++i; i != 16; ++i)
1861       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1862         return -1;
1863   } else
1864     return -1;
1865 
1866   if (isLE)
1867     ShiftAmt = 16 - ShiftAmt;
1868 
1869   return ShiftAmt;
1870 }
1871 
1872 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1873 /// specifies a splat of a single element that is suitable for input to
1874 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1875 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1876   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1877          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1878 
1879   // The consecutive indices need to specify an element, not part of two
1880   // different elements.  So abandon ship early if this isn't the case.
1881   if (N->getMaskElt(0) % EltSize != 0)
1882     return false;
1883 
1884   // This is a splat operation if each element of the permute is the same, and
1885   // if the value doesn't reference the second vector.
1886   unsigned ElementBase = N->getMaskElt(0);
1887 
1888   // FIXME: Handle UNDEF elements too!
1889   if (ElementBase >= 16)
1890     return false;
1891 
1892   // Check that the indices are consecutive, in the case of a multi-byte element
1893   // splatted with a v16i8 mask.
1894   for (unsigned i = 1; i != EltSize; ++i)
1895     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1896       return false;
1897 
1898   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1899     if (N->getMaskElt(i) < 0) continue;
1900     for (unsigned j = 0; j != EltSize; ++j)
1901       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1902         return false;
1903   }
1904   return true;
1905 }
1906 
1907 /// Check that the mask is shuffling N byte elements. Within each N byte
1908 /// element of the mask, the indices could be either in increasing or
1909 /// decreasing order as long as they are consecutive.
1910 /// \param[in] N the shuffle vector SD Node to analyze
1911 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1912 /// Word/DoubleWord/QuadWord).
1913 /// \param[in] StepLen the delta indices number among the N byte element, if
1914 /// the mask is in increasing/decreasing order then it is 1/-1.
1915 /// \return true iff the mask is shuffling N byte elements.
1916 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1917                                    int StepLen) {
1918   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1919          "Unexpected element width.");
1920   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1921 
1922   unsigned NumOfElem = 16 / Width;
1923   unsigned MaskVal[16]; //  Width is never greater than 16
1924   for (unsigned i = 0; i < NumOfElem; ++i) {
1925     MaskVal[0] = N->getMaskElt(i * Width);
1926     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1927       return false;
1928     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1929       return false;
1930     }
1931 
1932     for (unsigned int j = 1; j < Width; ++j) {
1933       MaskVal[j] = N->getMaskElt(i * Width + j);
1934       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1935         return false;
1936       }
1937     }
1938   }
1939 
1940   return true;
1941 }
1942 
1943 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1944                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1945   if (!isNByteElemShuffleMask(N, 4, 1))
1946     return false;
1947 
1948   // Now we look at mask elements 0,4,8,12
1949   unsigned M0 = N->getMaskElt(0) / 4;
1950   unsigned M1 = N->getMaskElt(4) / 4;
1951   unsigned M2 = N->getMaskElt(8) / 4;
1952   unsigned M3 = N->getMaskElt(12) / 4;
1953   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1954   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1955 
1956   // Below, let H and L be arbitrary elements of the shuffle mask
1957   // where H is in the range [4,7] and L is in the range [0,3].
1958   // H, 1, 2, 3 or L, 5, 6, 7
1959   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1960       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1961     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1962     InsertAtByte = IsLE ? 12 : 0;
1963     Swap = M0 < 4;
1964     return true;
1965   }
1966   // 0, H, 2, 3 or 4, L, 6, 7
1967   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1968       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1969     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1970     InsertAtByte = IsLE ? 8 : 4;
1971     Swap = M1 < 4;
1972     return true;
1973   }
1974   // 0, 1, H, 3 or 4, 5, L, 7
1975   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1976       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1977     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1978     InsertAtByte = IsLE ? 4 : 8;
1979     Swap = M2 < 4;
1980     return true;
1981   }
1982   // 0, 1, 2, H or 4, 5, 6, L
1983   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1984       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1985     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1986     InsertAtByte = IsLE ? 0 : 12;
1987     Swap = M3 < 4;
1988     return true;
1989   }
1990 
1991   // If both vector operands for the shuffle are the same vector, the mask will
1992   // contain only elements from the first one and the second one will be undef.
1993   if (N->getOperand(1).isUndef()) {
1994     ShiftElts = 0;
1995     Swap = true;
1996     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1997     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1998       InsertAtByte = IsLE ? 12 : 0;
1999       return true;
2000     }
2001     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2002       InsertAtByte = IsLE ? 8 : 4;
2003       return true;
2004     }
2005     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2006       InsertAtByte = IsLE ? 4 : 8;
2007       return true;
2008     }
2009     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2010       InsertAtByte = IsLE ? 0 : 12;
2011       return true;
2012     }
2013   }
2014 
2015   return false;
2016 }
2017 
2018 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2019                                bool &Swap, bool IsLE) {
2020   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2021   // Ensure each byte index of the word is consecutive.
2022   if (!isNByteElemShuffleMask(N, 4, 1))
2023     return false;
2024 
2025   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2026   unsigned M0 = N->getMaskElt(0) / 4;
2027   unsigned M1 = N->getMaskElt(4) / 4;
2028   unsigned M2 = N->getMaskElt(8) / 4;
2029   unsigned M3 = N->getMaskElt(12) / 4;
2030 
2031   // If both vector operands for the shuffle are the same vector, the mask will
2032   // contain only elements from the first one and the second one will be undef.
2033   if (N->getOperand(1).isUndef()) {
2034     assert(M0 < 4 && "Indexing into an undef vector?");
2035     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2036       return false;
2037 
2038     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2039     Swap = false;
2040     return true;
2041   }
2042 
2043   // Ensure each word index of the ShuffleVector Mask is consecutive.
2044   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2045     return false;
2046 
2047   if (IsLE) {
2048     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2049       // Input vectors don't need to be swapped if the leading element
2050       // of the result is one of the 3 left elements of the second vector
2051       // (or if there is no shift to be done at all).
2052       Swap = false;
2053       ShiftElts = (8 - M0) % 8;
2054     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2055       // Input vectors need to be swapped if the leading element
2056       // of the result is one of the 3 left elements of the first vector
2057       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2058       Swap = true;
2059       ShiftElts = (4 - M0) % 4;
2060     }
2061 
2062     return true;
2063   } else {                                          // BE
2064     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2065       // Input vectors don't need to be swapped if the leading element
2066       // of the result is one of the 4 elements of the first vector.
2067       Swap = false;
2068       ShiftElts = M0;
2069     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2070       // Input vectors need to be swapped if the leading element
2071       // of the result is one of the 4 elements of the right vector.
2072       Swap = true;
2073       ShiftElts = M0 - 4;
2074     }
2075 
2076     return true;
2077   }
2078 }
2079 
2080 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2081   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2082 
2083   if (!isNByteElemShuffleMask(N, Width, -1))
2084     return false;
2085 
2086   for (int i = 0; i < 16; i += Width)
2087     if (N->getMaskElt(i) != i + Width - 1)
2088       return false;
2089 
2090   return true;
2091 }
2092 
2093 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2094   return isXXBRShuffleMaskHelper(N, 2);
2095 }
2096 
2097 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2098   return isXXBRShuffleMaskHelper(N, 4);
2099 }
2100 
2101 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2102   return isXXBRShuffleMaskHelper(N, 8);
2103 }
2104 
2105 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2106   return isXXBRShuffleMaskHelper(N, 16);
2107 }
2108 
2109 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2110 /// if the inputs to the instruction should be swapped and set \p DM to the
2111 /// value for the immediate.
2112 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2113 /// AND element 0 of the result comes from the first input (LE) or second input
2114 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2115 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2116 /// mask.
2117 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2118                                bool &Swap, bool IsLE) {
2119   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2120 
2121   // Ensure each byte index of the double word is consecutive.
2122   if (!isNByteElemShuffleMask(N, 8, 1))
2123     return false;
2124 
2125   unsigned M0 = N->getMaskElt(0) / 8;
2126   unsigned M1 = N->getMaskElt(8) / 8;
2127   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2128 
2129   // If both vector operands for the shuffle are the same vector, the mask will
2130   // contain only elements from the first one and the second one will be undef.
2131   if (N->getOperand(1).isUndef()) {
2132     if ((M0 | M1) < 2) {
2133       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2134       Swap = false;
2135       return true;
2136     } else
2137       return false;
2138   }
2139 
2140   if (IsLE) {
2141     if (M0 > 1 && M1 < 2) {
2142       Swap = false;
2143     } else if (M0 < 2 && M1 > 1) {
2144       M0 = (M0 + 2) % 4;
2145       M1 = (M1 + 2) % 4;
2146       Swap = true;
2147     } else
2148       return false;
2149 
2150     // Note: if control flow comes here that means Swap is already set above
2151     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2152     return true;
2153   } else { // BE
2154     if (M0 < 2 && M1 > 1) {
2155       Swap = false;
2156     } else if (M0 > 1 && M1 < 2) {
2157       M0 = (M0 + 2) % 4;
2158       M1 = (M1 + 2) % 4;
2159       Swap = true;
2160     } else
2161       return false;
2162 
2163     // Note: if control flow comes here that means Swap is already set above
2164     DM = (M0 << 1) + (M1 & 1);
2165     return true;
2166   }
2167 }
2168 
2169 
2170 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2171 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2172 /// elements are counted from the left of the vector register).
2173 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2174                                          SelectionDAG &DAG) {
2175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2176   assert(isSplatShuffleMask(SVOp, EltSize));
2177   if (DAG.getDataLayout().isLittleEndian())
2178     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2179   else
2180     return SVOp->getMaskElt(0) / EltSize;
2181 }
2182 
2183 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2184 /// by using a vspltis[bhw] instruction of the specified element size, return
2185 /// the constant being splatted.  The ByteSize field indicates the number of
2186 /// bytes of each element [124] -> [bhw].
2187 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2188   SDValue OpVal(nullptr, 0);
2189 
2190   // If ByteSize of the splat is bigger than the element size of the
2191   // build_vector, then we have a case where we are checking for a splat where
2192   // multiple elements of the buildvector are folded together into a single
2193   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2194   unsigned EltSize = 16/N->getNumOperands();
2195   if (EltSize < ByteSize) {
2196     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2197     SDValue UniquedVals[4];
2198     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2199 
2200     // See if all of the elements in the buildvector agree across.
2201     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2202       if (N->getOperand(i).isUndef()) continue;
2203       // If the element isn't a constant, bail fully out.
2204       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2205 
2206       if (!UniquedVals[i&(Multiple-1)].getNode())
2207         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2208       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2209         return SDValue();  // no match.
2210     }
2211 
2212     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2213     // either constant or undef values that are identical for each chunk.  See
2214     // if these chunks can form into a larger vspltis*.
2215 
2216     // Check to see if all of the leading entries are either 0 or -1.  If
2217     // neither, then this won't fit into the immediate field.
2218     bool LeadingZero = true;
2219     bool LeadingOnes = true;
2220     for (unsigned i = 0; i != Multiple-1; ++i) {
2221       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2222 
2223       LeadingZero &= isNullConstant(UniquedVals[i]);
2224       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2225     }
2226     // Finally, check the least significant entry.
2227     if (LeadingZero) {
2228       if (!UniquedVals[Multiple-1].getNode())
2229         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2230       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2231       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2232         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2233     }
2234     if (LeadingOnes) {
2235       if (!UniquedVals[Multiple-1].getNode())
2236         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2237       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2238       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2239         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2240     }
2241 
2242     return SDValue();
2243   }
2244 
2245   // Check to see if this buildvec has a single non-undef value in its elements.
2246   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2247     if (N->getOperand(i).isUndef()) continue;
2248     if (!OpVal.getNode())
2249       OpVal = N->getOperand(i);
2250     else if (OpVal != N->getOperand(i))
2251       return SDValue();
2252   }
2253 
2254   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2255 
2256   unsigned ValSizeInBytes = EltSize;
2257   uint64_t Value = 0;
2258   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2259     Value = CN->getZExtValue();
2260   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2261     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2262     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2263   }
2264 
2265   // If the splat value is larger than the element value, then we can never do
2266   // this splat.  The only case that we could fit the replicated bits into our
2267   // immediate field for would be zero, and we prefer to use vxor for it.
2268   if (ValSizeInBytes < ByteSize) return SDValue();
2269 
2270   // If the element value is larger than the splat value, check if it consists
2271   // of a repeated bit pattern of size ByteSize.
2272   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2273     return SDValue();
2274 
2275   // Properly sign extend the value.
2276   int MaskVal = SignExtend32(Value, ByteSize * 8);
2277 
2278   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2279   if (MaskVal == 0) return SDValue();
2280 
2281   // Finally, if this value fits in a 5 bit sext field, return it
2282   if (SignExtend32<5>(MaskVal) == MaskVal)
2283     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2284   return SDValue();
2285 }
2286 
2287 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2288 /// amount, otherwise return -1.
2289 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2290   EVT VT = N->getValueType(0);
2291   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2292     return -1;
2293 
2294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2295 
2296   // Find the first non-undef value in the shuffle mask.
2297   unsigned i;
2298   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2299     /*search*/;
2300 
2301   if (i == 4) return -1;  // all undef.
2302 
2303   // Otherwise, check to see if the rest of the elements are consecutively
2304   // numbered from this value.
2305   unsigned ShiftAmt = SVOp->getMaskElt(i);
2306   if (ShiftAmt < i) return -1;
2307   ShiftAmt -= i;
2308 
2309   // Check the rest of the elements to see if they are consecutive.
2310   for (++i; i != 4; ++i)
2311     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2312       return -1;
2313 
2314   return ShiftAmt;
2315 }
2316 
2317 //===----------------------------------------------------------------------===//
2318 //  Addressing Mode Selection
2319 //===----------------------------------------------------------------------===//
2320 
2321 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2322 /// or 64-bit immediate, and if the value can be accurately represented as a
2323 /// sign extension from a 16-bit value.  If so, this returns true and the
2324 /// immediate.
2325 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2326   if (!isa<ConstantSDNode>(N))
2327     return false;
2328 
2329   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2330   if (N->getValueType(0) == MVT::i32)
2331     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2332   else
2333     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2334 }
2335 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2336   return isIntS16Immediate(Op.getNode(), Imm);
2337 }
2338 
2339 
2340 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2341 /// be represented as an indexed [r+r] operation.
2342 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2343                                                SDValue &Index,
2344                                                SelectionDAG &DAG) const {
2345   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2346       UI != E; ++UI) {
2347     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2348       if (Memop->getMemoryVT() == MVT::f64) {
2349           Base = N.getOperand(0);
2350           Index = N.getOperand(1);
2351           return true;
2352       }
2353     }
2354   }
2355   return false;
2356 }
2357 
2358 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2359 /// can be represented as an indexed [r+r] operation.  Returns false if it
2360 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2361 /// non-zero and N can be represented by a base register plus a signed 16-bit
2362 /// displacement, make a more precise judgement by checking (displacement % \p
2363 /// EncodingAlignment).
2364 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2365                                             SDValue &Index, SelectionDAG &DAG,
2366                                             unsigned EncodingAlignment) const {
2367   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2368   // a [pc+imm].
2369   if (SelectAddressPCRel(N, Base))
2370     return false;
2371 
2372   int16_t imm = 0;
2373   if (N.getOpcode() == ISD::ADD) {
2374     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2375     // SPE load/store can only handle 8-bit offsets.
2376     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2377         return true;
2378     if (isIntS16Immediate(N.getOperand(1), imm) &&
2379         (!EncodingAlignment || !(imm % EncodingAlignment)))
2380       return false; // r+i
2381     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2382       return false;    // r+i
2383 
2384     Base = N.getOperand(0);
2385     Index = N.getOperand(1);
2386     return true;
2387   } else if (N.getOpcode() == ISD::OR) {
2388     if (isIntS16Immediate(N.getOperand(1), imm) &&
2389         (!EncodingAlignment || !(imm % EncodingAlignment)))
2390       return false; // r+i can fold it if we can.
2391 
2392     // If this is an or of disjoint bitfields, we can codegen this as an add
2393     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2394     // disjoint.
2395     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2396 
2397     if (LHSKnown.Zero.getBoolValue()) {
2398       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2399       // If all of the bits are known zero on the LHS or RHS, the add won't
2400       // carry.
2401       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2402         Base = N.getOperand(0);
2403         Index = N.getOperand(1);
2404         return true;
2405       }
2406     }
2407   }
2408 
2409   return false;
2410 }
2411 
2412 // If we happen to be doing an i64 load or store into a stack slot that has
2413 // less than a 4-byte alignment, then the frame-index elimination may need to
2414 // use an indexed load or store instruction (because the offset may not be a
2415 // multiple of 4). The extra register needed to hold the offset comes from the
2416 // register scavenger, and it is possible that the scavenger will need to use
2417 // an emergency spill slot. As a result, we need to make sure that a spill slot
2418 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2419 // stack slot.
2420 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2421   // FIXME: This does not handle the LWA case.
2422   if (VT != MVT::i64)
2423     return;
2424 
2425   // NOTE: We'll exclude negative FIs here, which come from argument
2426   // lowering, because there are no known test cases triggering this problem
2427   // using packed structures (or similar). We can remove this exclusion if
2428   // we find such a test case. The reason why this is so test-case driven is
2429   // because this entire 'fixup' is only to prevent crashes (from the
2430   // register scavenger) on not-really-valid inputs. For example, if we have:
2431   //   %a = alloca i1
2432   //   %b = bitcast i1* %a to i64*
2433   //   store i64* a, i64 b
2434   // then the store should really be marked as 'align 1', but is not. If it
2435   // were marked as 'align 1' then the indexed form would have been
2436   // instruction-selected initially, and the problem this 'fixup' is preventing
2437   // won't happen regardless.
2438   if (FrameIdx < 0)
2439     return;
2440 
2441   MachineFunction &MF = DAG.getMachineFunction();
2442   MachineFrameInfo &MFI = MF.getFrameInfo();
2443 
2444   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2445     return;
2446 
2447   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2448   FuncInfo->setHasNonRISpills();
2449 }
2450 
2451 /// Returns true if the address N can be represented by a base register plus
2452 /// a signed 16-bit displacement [r+imm], and if it is not better
2453 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2454 /// displacements that are multiples of that value.
2455 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2456                                             SDValue &Base,
2457                                             SelectionDAG &DAG,
2458                                             unsigned EncodingAlignment) const {
2459   // FIXME dl should come from parent load or store, not from address
2460   SDLoc dl(N);
2461 
2462   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2463   // a [pc+imm].
2464   if (SelectAddressPCRel(N, Base))
2465     return false;
2466 
2467   // If this can be more profitably realized as r+r, fail.
2468   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2469     return false;
2470 
2471   if (N.getOpcode() == ISD::ADD) {
2472     int16_t imm = 0;
2473     if (isIntS16Immediate(N.getOperand(1), imm) &&
2474         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2475       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2476       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2477         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2478         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2479       } else {
2480         Base = N.getOperand(0);
2481       }
2482       return true; // [r+i]
2483     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2484       // Match LOAD (ADD (X, Lo(G))).
2485       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2486              && "Cannot handle constant offsets yet!");
2487       Disp = N.getOperand(1).getOperand(0);  // The global address.
2488       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2489              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2490              Disp.getOpcode() == ISD::TargetConstantPool ||
2491              Disp.getOpcode() == ISD::TargetJumpTable);
2492       Base = N.getOperand(0);
2493       return true;  // [&g+r]
2494     }
2495   } else if (N.getOpcode() == ISD::OR) {
2496     int16_t imm = 0;
2497     if (isIntS16Immediate(N.getOperand(1), imm) &&
2498         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2499       // If this is an or of disjoint bitfields, we can codegen this as an add
2500       // (for better address arithmetic) if the LHS and RHS of the OR are
2501       // provably disjoint.
2502       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2503 
2504       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2505         // If all of the bits are known zero on the LHS or RHS, the add won't
2506         // carry.
2507         if (FrameIndexSDNode *FI =
2508               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2509           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2510           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2511         } else {
2512           Base = N.getOperand(0);
2513         }
2514         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2515         return true;
2516       }
2517     }
2518   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2519     // Loading from a constant address.
2520 
2521     // If this address fits entirely in a 16-bit sext immediate field, codegen
2522     // this as "d, 0"
2523     int16_t Imm;
2524     if (isIntS16Immediate(CN, Imm) &&
2525         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2526       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2527       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2528                              CN->getValueType(0));
2529       return true;
2530     }
2531 
2532     // Handle 32-bit sext immediates with LIS + addr mode.
2533     if ((CN->getValueType(0) == MVT::i32 ||
2534          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2535         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2536       int Addr = (int)CN->getZExtValue();
2537 
2538       // Otherwise, break this down into an LIS + disp.
2539       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2540 
2541       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2542                                    MVT::i32);
2543       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2544       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2545       return true;
2546     }
2547   }
2548 
2549   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2550   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2551     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2552     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2553   } else
2554     Base = N;
2555   return true;      // [r+0]
2556 }
2557 
2558 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2559 /// represented as an indexed [r+r] operation.
2560 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2561                                                 SDValue &Index,
2562                                                 SelectionDAG &DAG) const {
2563   // Check to see if we can easily represent this as an [r+r] address.  This
2564   // will fail if it thinks that the address is more profitably represented as
2565   // reg+imm, e.g. where imm = 0.
2566   if (SelectAddressRegReg(N, Base, Index, DAG))
2567     return true;
2568 
2569   // If the address is the result of an add, we will utilize the fact that the
2570   // address calculation includes an implicit add.  However, we can reduce
2571   // register pressure if we do not materialize a constant just for use as the
2572   // index register.  We only get rid of the add if it is not an add of a
2573   // value and a 16-bit signed constant and both have a single use.
2574   int16_t imm = 0;
2575   if (N.getOpcode() == ISD::ADD &&
2576       (!isIntS16Immediate(N.getOperand(1), imm) ||
2577        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2578     Base = N.getOperand(0);
2579     Index = N.getOperand(1);
2580     return true;
2581   }
2582 
2583   // Otherwise, do it the hard way, using R0 as the base register.
2584   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2585                          N.getValueType());
2586   Index = N;
2587   return true;
2588 }
2589 
2590 /// Returns true if this address is a PC Relative address.
2591 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG.
2592 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2593   ConstantPoolSDNode *ConstPoolNode =
2594       dyn_cast<ConstantPoolSDNode>(N.getNode());
2595   bool HasFlag = ConstPoolNode &&
2596                  ConstPoolNode->getTargetFlags() == PPCII::MO_PCREL_FLAG;
2597   bool HasNode = N.getOpcode() == PPCISD::MAT_PCREL_ADDR;
2598   if (HasFlag || HasNode) {
2599     Base = N;
2600     return true;
2601   }
2602   return false;
2603 }
2604 
2605 /// Returns true if we should use a direct load into vector instruction
2606 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2607 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2608 
2609   // If there are any other uses other than scalar to vector, then we should
2610   // keep it as a scalar load -> direct move pattern to prevent multiple
2611   // loads.
2612   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2613   if (!LD)
2614     return false;
2615 
2616   EVT MemVT = LD->getMemoryVT();
2617   if (!MemVT.isSimple())
2618     return false;
2619   switch(MemVT.getSimpleVT().SimpleTy) {
2620   case MVT::i64:
2621     break;
2622   case MVT::i32:
2623     if (!ST.hasP8Vector())
2624       return false;
2625     break;
2626   case MVT::i16:
2627   case MVT::i8:
2628     if (!ST.hasP9Vector())
2629       return false;
2630     break;
2631   default:
2632     return false;
2633   }
2634 
2635   SDValue LoadedVal(N, 0);
2636   if (!LoadedVal.hasOneUse())
2637     return false;
2638 
2639   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2640        UI != UE; ++UI)
2641     if (UI.getUse().get().getResNo() == 0 &&
2642         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2643       return false;
2644 
2645   return true;
2646 }
2647 
2648 /// getPreIndexedAddressParts - returns true by value, base pointer and
2649 /// offset pointer and addressing mode by reference if the node's address
2650 /// can be legally represented as pre-indexed load / store address.
2651 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2652                                                   SDValue &Offset,
2653                                                   ISD::MemIndexedMode &AM,
2654                                                   SelectionDAG &DAG) const {
2655   if (DisablePPCPreinc) return false;
2656 
2657   bool isLoad = true;
2658   SDValue Ptr;
2659   EVT VT;
2660   unsigned Alignment;
2661   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2662     Ptr = LD->getBasePtr();
2663     VT = LD->getMemoryVT();
2664     Alignment = LD->getAlignment();
2665   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2666     Ptr = ST->getBasePtr();
2667     VT  = ST->getMemoryVT();
2668     Alignment = ST->getAlignment();
2669     isLoad = false;
2670   } else
2671     return false;
2672 
2673   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2674   // instructions because we can fold these into a more efficient instruction
2675   // instead, (such as LXSD).
2676   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2677     return false;
2678   }
2679 
2680   // PowerPC doesn't have preinc load/store instructions for vectors (except
2681   // for QPX, which does have preinc r+r forms).
2682   if (VT.isVector()) {
2683     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2684       return false;
2685     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2686       AM = ISD::PRE_INC;
2687       return true;
2688     }
2689   }
2690 
2691   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2692     // Common code will reject creating a pre-inc form if the base pointer
2693     // is a frame index, or if N is a store and the base pointer is either
2694     // the same as or a predecessor of the value being stored.  Check for
2695     // those situations here, and try with swapped Base/Offset instead.
2696     bool Swap = false;
2697 
2698     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2699       Swap = true;
2700     else if (!isLoad) {
2701       SDValue Val = cast<StoreSDNode>(N)->getValue();
2702       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2703         Swap = true;
2704     }
2705 
2706     if (Swap)
2707       std::swap(Base, Offset);
2708 
2709     AM = ISD::PRE_INC;
2710     return true;
2711   }
2712 
2713   // LDU/STU can only handle immediates that are a multiple of 4.
2714   if (VT != MVT::i64) {
2715     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2716       return false;
2717   } else {
2718     // LDU/STU need an address with at least 4-byte alignment.
2719     if (Alignment < 4)
2720       return false;
2721 
2722     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2723       return false;
2724   }
2725 
2726   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2727     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2728     // sext i32 to i64 when addr mode is r+i.
2729     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2730         LD->getExtensionType() == ISD::SEXTLOAD &&
2731         isa<ConstantSDNode>(Offset))
2732       return false;
2733   }
2734 
2735   AM = ISD::PRE_INC;
2736   return true;
2737 }
2738 
2739 //===----------------------------------------------------------------------===//
2740 //  LowerOperation implementation
2741 //===----------------------------------------------------------------------===//
2742 
2743 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2744 /// and LoOpFlags to the target MO flags.
2745 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2746                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2747                                const GlobalValue *GV = nullptr) {
2748   HiOpFlags = PPCII::MO_HA;
2749   LoOpFlags = PPCII::MO_LO;
2750 
2751   // Don't use the pic base if not in PIC relocation model.
2752   if (IsPIC) {
2753     HiOpFlags |= PPCII::MO_PIC_FLAG;
2754     LoOpFlags |= PPCII::MO_PIC_FLAG;
2755   }
2756 }
2757 
2758 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2759                              SelectionDAG &DAG) {
2760   SDLoc DL(HiPart);
2761   EVT PtrVT = HiPart.getValueType();
2762   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2763 
2764   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2765   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2766 
2767   // With PIC, the first instruction is actually "GR+hi(&G)".
2768   if (isPIC)
2769     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2770                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2771 
2772   // Generate non-pic code that has direct accesses to the constant pool.
2773   // The address of the global is just (hi(&g)+lo(&g)).
2774   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2775 }
2776 
2777 static void setUsesTOCBasePtr(MachineFunction &MF) {
2778   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2779   FuncInfo->setUsesTOCBasePtr();
2780 }
2781 
2782 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2783   setUsesTOCBasePtr(DAG.getMachineFunction());
2784 }
2785 
2786 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2787                                        SDValue GA) const {
2788   const bool Is64Bit = Subtarget.isPPC64();
2789   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2790   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2791                         : Subtarget.isAIXABI()
2792                               ? DAG.getRegister(PPC::R2, VT)
2793                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2794   SDValue Ops[] = { GA, Reg };
2795   return DAG.getMemIntrinsicNode(
2796       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2797       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2798       MachineMemOperand::MOLoad);
2799 }
2800 
2801 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2802                                              SelectionDAG &DAG) const {
2803   EVT PtrVT = Op.getValueType();
2804   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2805   const Constant *C = CP->getConstVal();
2806 
2807   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2808   // The actual address of the GlobalValue is stored in the TOC.
2809   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2810     if (Subtarget.hasPCRelativeMemops()) {
2811       SDLoc DL(CP);
2812       EVT Ty = getPointerTy(DAG.getDataLayout());
2813       SDValue ConstPool = DAG.getTargetConstantPool(C, Ty,
2814                                                     CP->getAlignment(),
2815                                                     CP->getOffset(),
2816                                                     PPCII::MO_PCREL_FLAG);
2817       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2818     }
2819     setUsesTOCBasePtr(DAG);
2820     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2821     return getTOCEntry(DAG, SDLoc(CP), GA);
2822   }
2823 
2824   unsigned MOHiFlag, MOLoFlag;
2825   bool IsPIC = isPositionIndependent();
2826   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2827 
2828   if (IsPIC && Subtarget.isSVR4ABI()) {
2829     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2830                                            PPCII::MO_PIC_FLAG);
2831     return getTOCEntry(DAG, SDLoc(CP), GA);
2832   }
2833 
2834   SDValue CPIHi =
2835     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2836   SDValue CPILo =
2837     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2838   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2839 }
2840 
2841 // For 64-bit PowerPC, prefer the more compact relative encodings.
2842 // This trades 32 bits per jump table entry for one or two instructions
2843 // on the jump site.
2844 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2845   if (isJumpTableRelative())
2846     return MachineJumpTableInfo::EK_LabelDifference32;
2847 
2848   return TargetLowering::getJumpTableEncoding();
2849 }
2850 
2851 bool PPCTargetLowering::isJumpTableRelative() const {
2852   if (UseAbsoluteJumpTables)
2853     return false;
2854   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2855     return true;
2856   return TargetLowering::isJumpTableRelative();
2857 }
2858 
2859 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2860                                                     SelectionDAG &DAG) const {
2861   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2862     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2863 
2864   switch (getTargetMachine().getCodeModel()) {
2865   case CodeModel::Small:
2866   case CodeModel::Medium:
2867     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2868   default:
2869     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2870                        getPointerTy(DAG.getDataLayout()));
2871   }
2872 }
2873 
2874 const MCExpr *
2875 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2876                                                 unsigned JTI,
2877                                                 MCContext &Ctx) const {
2878   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2879     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2880 
2881   switch (getTargetMachine().getCodeModel()) {
2882   case CodeModel::Small:
2883   case CodeModel::Medium:
2884     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2885   default:
2886     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2887   }
2888 }
2889 
2890 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2891   EVT PtrVT = Op.getValueType();
2892   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2893 
2894   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2895   // The actual address of the GlobalValue is stored in the TOC.
2896   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2897     setUsesTOCBasePtr(DAG);
2898     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2899     return getTOCEntry(DAG, SDLoc(JT), GA);
2900   }
2901 
2902   unsigned MOHiFlag, MOLoFlag;
2903   bool IsPIC = isPositionIndependent();
2904   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2905 
2906   if (IsPIC && Subtarget.isSVR4ABI()) {
2907     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2908                                         PPCII::MO_PIC_FLAG);
2909     return getTOCEntry(DAG, SDLoc(GA), GA);
2910   }
2911 
2912   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2913   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2914   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2915 }
2916 
2917 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2918                                              SelectionDAG &DAG) const {
2919   EVT PtrVT = Op.getValueType();
2920   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2921   const BlockAddress *BA = BASDN->getBlockAddress();
2922 
2923   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2924   // The actual BlockAddress is stored in the TOC.
2925   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2926     setUsesTOCBasePtr(DAG);
2927     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2928     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2929   }
2930 
2931   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2932   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2933     return getTOCEntry(
2934         DAG, SDLoc(BASDN),
2935         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2936 
2937   unsigned MOHiFlag, MOLoFlag;
2938   bool IsPIC = isPositionIndependent();
2939   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2940   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2941   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2942   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2943 }
2944 
2945 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2946                                               SelectionDAG &DAG) const {
2947   // FIXME: TLS addresses currently use medium model code sequences,
2948   // which is the most useful form.  Eventually support for small and
2949   // large models could be added if users need it, at the cost of
2950   // additional complexity.
2951   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2952   if (DAG.getTarget().useEmulatedTLS())
2953     return LowerToTLSEmulatedModel(GA, DAG);
2954 
2955   SDLoc dl(GA);
2956   const GlobalValue *GV = GA->getGlobal();
2957   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2958   bool is64bit = Subtarget.isPPC64();
2959   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2960   PICLevel::Level picLevel = M->getPICLevel();
2961 
2962   const TargetMachine &TM = getTargetMachine();
2963   TLSModel::Model Model = TM.getTLSModel(GV);
2964 
2965   if (Model == TLSModel::LocalExec) {
2966     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2967                                                PPCII::MO_TPREL_HA);
2968     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2969                                                PPCII::MO_TPREL_LO);
2970     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2971                              : DAG.getRegister(PPC::R2, MVT::i32);
2972 
2973     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2974     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2975   }
2976 
2977   if (Model == TLSModel::InitialExec) {
2978     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2979     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2980                                                 PPCII::MO_TLS);
2981     SDValue GOTPtr;
2982     if (is64bit) {
2983       setUsesTOCBasePtr(DAG);
2984       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2985       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2986                            PtrVT, GOTReg, TGA);
2987     } else {
2988       if (!TM.isPositionIndependent())
2989         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2990       else if (picLevel == PICLevel::SmallPIC)
2991         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2992       else
2993         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2994     }
2995     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2996                                    PtrVT, TGA, GOTPtr);
2997     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2998   }
2999 
3000   if (Model == TLSModel::GeneralDynamic) {
3001     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3002     SDValue GOTPtr;
3003     if (is64bit) {
3004       setUsesTOCBasePtr(DAG);
3005       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3006       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3007                                    GOTReg, TGA);
3008     } else {
3009       if (picLevel == PICLevel::SmallPIC)
3010         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3011       else
3012         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3013     }
3014     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3015                        GOTPtr, TGA, TGA);
3016   }
3017 
3018   if (Model == TLSModel::LocalDynamic) {
3019     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3020     SDValue GOTPtr;
3021     if (is64bit) {
3022       setUsesTOCBasePtr(DAG);
3023       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3024       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3025                            GOTReg, TGA);
3026     } else {
3027       if (picLevel == PICLevel::SmallPIC)
3028         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3029       else
3030         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3031     }
3032     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3033                                   PtrVT, GOTPtr, TGA, TGA);
3034     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3035                                       PtrVT, TLSAddr, TGA);
3036     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3037   }
3038 
3039   llvm_unreachable("Unknown TLS model!");
3040 }
3041 
3042 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3043                                               SelectionDAG &DAG) const {
3044   EVT PtrVT = Op.getValueType();
3045   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3046   SDLoc DL(GSDN);
3047   const GlobalValue *GV = GSDN->getGlobal();
3048 
3049   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3050   // The actual address of the GlobalValue is stored in the TOC.
3051   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3052     setUsesTOCBasePtr(DAG);
3053     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3054     return getTOCEntry(DAG, DL, GA);
3055   }
3056 
3057   unsigned MOHiFlag, MOLoFlag;
3058   bool IsPIC = isPositionIndependent();
3059   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3060 
3061   if (IsPIC && Subtarget.isSVR4ABI()) {
3062     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3063                                             GSDN->getOffset(),
3064                                             PPCII::MO_PIC_FLAG);
3065     return getTOCEntry(DAG, DL, GA);
3066   }
3067 
3068   SDValue GAHi =
3069     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3070   SDValue GALo =
3071     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3072 
3073   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3074 }
3075 
3076 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3077   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3078   SDLoc dl(Op);
3079 
3080   if (Op.getValueType() == MVT::v2i64) {
3081     // When the operands themselves are v2i64 values, we need to do something
3082     // special because VSX has no underlying comparison operations for these.
3083     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3084       // Equality can be handled by casting to the legal type for Altivec
3085       // comparisons, everything else needs to be expanded.
3086       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3087         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3088                  DAG.getSetCC(dl, MVT::v4i32,
3089                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3090                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3091                    CC));
3092       }
3093 
3094       return SDValue();
3095     }
3096 
3097     // We handle most of these in the usual way.
3098     return Op;
3099   }
3100 
3101   // If we're comparing for equality to zero, expose the fact that this is
3102   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3103   // fold the new nodes.
3104   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3105     return V;
3106 
3107   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3108     // Leave comparisons against 0 and -1 alone for now, since they're usually
3109     // optimized.  FIXME: revisit this when we can custom lower all setcc
3110     // optimizations.
3111     if (C->isAllOnesValue() || C->isNullValue())
3112       return SDValue();
3113   }
3114 
3115   // If we have an integer seteq/setne, turn it into a compare against zero
3116   // by xor'ing the rhs with the lhs, which is faster than setting a
3117   // condition register, reading it back out, and masking the correct bit.  The
3118   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3119   // the result to other bit-twiddling opportunities.
3120   EVT LHSVT = Op.getOperand(0).getValueType();
3121   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3122     EVT VT = Op.getValueType();
3123     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3124                                 Op.getOperand(1));
3125     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3126   }
3127   return SDValue();
3128 }
3129 
3130 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3131   SDNode *Node = Op.getNode();
3132   EVT VT = Node->getValueType(0);
3133   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3134   SDValue InChain = Node->getOperand(0);
3135   SDValue VAListPtr = Node->getOperand(1);
3136   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3137   SDLoc dl(Node);
3138 
3139   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3140 
3141   // gpr_index
3142   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3143                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3144   InChain = GprIndex.getValue(1);
3145 
3146   if (VT == MVT::i64) {
3147     // Check if GprIndex is even
3148     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3149                                  DAG.getConstant(1, dl, MVT::i32));
3150     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3151                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3152     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3153                                           DAG.getConstant(1, dl, MVT::i32));
3154     // Align GprIndex to be even if it isn't
3155     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3156                            GprIndex);
3157   }
3158 
3159   // fpr index is 1 byte after gpr
3160   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3161                                DAG.getConstant(1, dl, MVT::i32));
3162 
3163   // fpr
3164   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3165                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3166   InChain = FprIndex.getValue(1);
3167 
3168   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3169                                        DAG.getConstant(8, dl, MVT::i32));
3170 
3171   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3172                                         DAG.getConstant(4, dl, MVT::i32));
3173 
3174   // areas
3175   SDValue OverflowArea =
3176       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3177   InChain = OverflowArea.getValue(1);
3178 
3179   SDValue RegSaveArea =
3180       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3181   InChain = RegSaveArea.getValue(1);
3182 
3183   // select overflow_area if index > 8
3184   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3185                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3186 
3187   // adjustment constant gpr_index * 4/8
3188   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3189                                     VT.isInteger() ? GprIndex : FprIndex,
3190                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3191                                                     MVT::i32));
3192 
3193   // OurReg = RegSaveArea + RegConstant
3194   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3195                                RegConstant);
3196 
3197   // Floating types are 32 bytes into RegSaveArea
3198   if (VT.isFloatingPoint())
3199     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3200                          DAG.getConstant(32, dl, MVT::i32));
3201 
3202   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3203   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3204                                    VT.isInteger() ? GprIndex : FprIndex,
3205                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3206                                                    MVT::i32));
3207 
3208   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3209                               VT.isInteger() ? VAListPtr : FprPtr,
3210                               MachinePointerInfo(SV), MVT::i8);
3211 
3212   // determine if we should load from reg_save_area or overflow_area
3213   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3214 
3215   // increase overflow_area by 4/8 if gpr/fpr > 8
3216   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3217                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3218                                           dl, MVT::i32));
3219 
3220   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3221                              OverflowAreaPlusN);
3222 
3223   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3224                               MachinePointerInfo(), MVT::i32);
3225 
3226   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3227 }
3228 
3229 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3230   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3231 
3232   // We have to copy the entire va_list struct:
3233   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3234   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3235                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3236                        false, true, false, MachinePointerInfo(),
3237                        MachinePointerInfo());
3238 }
3239 
3240 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3241                                                   SelectionDAG &DAG) const {
3242   if (Subtarget.isAIXABI())
3243     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3244 
3245   return Op.getOperand(0);
3246 }
3247 
3248 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3249                                                 SelectionDAG &DAG) const {
3250   if (Subtarget.isAIXABI())
3251     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3252 
3253   SDValue Chain = Op.getOperand(0);
3254   SDValue Trmp = Op.getOperand(1); // trampoline
3255   SDValue FPtr = Op.getOperand(2); // nested function
3256   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3257   SDLoc dl(Op);
3258 
3259   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3260   bool isPPC64 = (PtrVT == MVT::i64);
3261   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3262 
3263   TargetLowering::ArgListTy Args;
3264   TargetLowering::ArgListEntry Entry;
3265 
3266   Entry.Ty = IntPtrTy;
3267   Entry.Node = Trmp; Args.push_back(Entry);
3268 
3269   // TrampSize == (isPPC64 ? 48 : 40);
3270   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3271                                isPPC64 ? MVT::i64 : MVT::i32);
3272   Args.push_back(Entry);
3273 
3274   Entry.Node = FPtr; Args.push_back(Entry);
3275   Entry.Node = Nest; Args.push_back(Entry);
3276 
3277   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3278   TargetLowering::CallLoweringInfo CLI(DAG);
3279   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3280       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3281       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3282 
3283   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3284   return CallResult.second;
3285 }
3286 
3287 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3288   MachineFunction &MF = DAG.getMachineFunction();
3289   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3290   EVT PtrVT = getPointerTy(MF.getDataLayout());
3291 
3292   SDLoc dl(Op);
3293 
3294   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3295     // vastart just stores the address of the VarArgsFrameIndex slot into the
3296     // memory location argument.
3297     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3298     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3299     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3300                         MachinePointerInfo(SV));
3301   }
3302 
3303   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3304   // We suppose the given va_list is already allocated.
3305   //
3306   // typedef struct {
3307   //  char gpr;     /* index into the array of 8 GPRs
3308   //                 * stored in the register save area
3309   //                 * gpr=0 corresponds to r3,
3310   //                 * gpr=1 to r4, etc.
3311   //                 */
3312   //  char fpr;     /* index into the array of 8 FPRs
3313   //                 * stored in the register save area
3314   //                 * fpr=0 corresponds to f1,
3315   //                 * fpr=1 to f2, etc.
3316   //                 */
3317   //  char *overflow_arg_area;
3318   //                /* location on stack that holds
3319   //                 * the next overflow argument
3320   //                 */
3321   //  char *reg_save_area;
3322   //               /* where r3:r10 and f1:f8 (if saved)
3323   //                * are stored
3324   //                */
3325   // } va_list[1];
3326 
3327   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3328   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3329   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3330                                             PtrVT);
3331   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3332                                  PtrVT);
3333 
3334   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3335   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3336 
3337   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3338   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3339 
3340   uint64_t FPROffset = 1;
3341   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3342 
3343   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3344 
3345   // Store first byte : number of int regs
3346   SDValue firstStore =
3347       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3348                         MachinePointerInfo(SV), MVT::i8);
3349   uint64_t nextOffset = FPROffset;
3350   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3351                                   ConstFPROffset);
3352 
3353   // Store second byte : number of float regs
3354   SDValue secondStore =
3355       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3356                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3357   nextOffset += StackOffset;
3358   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3359 
3360   // Store second word : arguments given on stack
3361   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3362                                     MachinePointerInfo(SV, nextOffset));
3363   nextOffset += FrameOffset;
3364   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3365 
3366   // Store third word : arguments given in registers
3367   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3368                       MachinePointerInfo(SV, nextOffset));
3369 }
3370 
3371 /// FPR - The set of FP registers that should be allocated for arguments
3372 /// on Darwin and AIX.
3373 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3374                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3375                                 PPC::F11, PPC::F12, PPC::F13};
3376 
3377 /// QFPR - The set of QPX registers that should be allocated for arguments.
3378 static const MCPhysReg QFPR[] = {
3379     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3380     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3381 
3382 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3383 /// the stack.
3384 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3385                                        unsigned PtrByteSize) {
3386   unsigned ArgSize = ArgVT.getStoreSize();
3387   if (Flags.isByVal())
3388     ArgSize = Flags.getByValSize();
3389 
3390   // Round up to multiples of the pointer size, except for array members,
3391   // which are always packed.
3392   if (!Flags.isInConsecutiveRegs())
3393     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3394 
3395   return ArgSize;
3396 }
3397 
3398 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3399 /// on the stack.
3400 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3401                                          ISD::ArgFlagsTy Flags,
3402                                          unsigned PtrByteSize) {
3403   Align Alignment(PtrByteSize);
3404 
3405   // Altivec parameters are padded to a 16 byte boundary.
3406   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3407       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3408       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3409       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3410     Alignment = Align(16);
3411   // QPX vector types stored in double-precision are padded to a 32 byte
3412   // boundary.
3413   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3414     Alignment = Align(32);
3415 
3416   // ByVal parameters are aligned as requested.
3417   if (Flags.isByVal()) {
3418     auto BVAlign = Flags.getNonZeroByValAlign();
3419     if (BVAlign > PtrByteSize) {
3420       if (BVAlign.value() % PtrByteSize != 0)
3421         llvm_unreachable(
3422             "ByVal alignment is not a multiple of the pointer size");
3423 
3424       Alignment = BVAlign;
3425     }
3426   }
3427 
3428   // Array members are always packed to their original alignment.
3429   if (Flags.isInConsecutiveRegs()) {
3430     // If the array member was split into multiple registers, the first
3431     // needs to be aligned to the size of the full type.  (Except for
3432     // ppcf128, which is only aligned as its f64 components.)
3433     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3434       Alignment = Align(OrigVT.getStoreSize());
3435     else
3436       Alignment = Align(ArgVT.getStoreSize());
3437   }
3438 
3439   return Alignment;
3440 }
3441 
3442 /// CalculateStackSlotUsed - Return whether this argument will use its
3443 /// stack slot (instead of being passed in registers).  ArgOffset,
3444 /// AvailableFPRs, and AvailableVRs must hold the current argument
3445 /// position, and will be updated to account for this argument.
3446 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3447                                    ISD::ArgFlagsTy Flags,
3448                                    unsigned PtrByteSize,
3449                                    unsigned LinkageSize,
3450                                    unsigned ParamAreaSize,
3451                                    unsigned &ArgOffset,
3452                                    unsigned &AvailableFPRs,
3453                                    unsigned &AvailableVRs, bool HasQPX) {
3454   bool UseMemory = false;
3455 
3456   // Respect alignment of argument on the stack.
3457   Align Alignment =
3458       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3459   ArgOffset = alignTo(ArgOffset, Alignment);
3460   // If there's no space left in the argument save area, we must
3461   // use memory (this check also catches zero-sized arguments).
3462   if (ArgOffset >= LinkageSize + ParamAreaSize)
3463     UseMemory = true;
3464 
3465   // Allocate argument on the stack.
3466   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3467   if (Flags.isInConsecutiveRegsLast())
3468     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3469   // If we overran the argument save area, we must use memory
3470   // (this check catches arguments passed partially in memory)
3471   if (ArgOffset > LinkageSize + ParamAreaSize)
3472     UseMemory = true;
3473 
3474   // However, if the argument is actually passed in an FPR or a VR,
3475   // we don't use memory after all.
3476   if (!Flags.isByVal()) {
3477     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3478         // QPX registers overlap with the scalar FP registers.
3479         (HasQPX && (ArgVT == MVT::v4f32 ||
3480                     ArgVT == MVT::v4f64 ||
3481                     ArgVT == MVT::v4i1)))
3482       if (AvailableFPRs > 0) {
3483         --AvailableFPRs;
3484         return false;
3485       }
3486     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3487         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3488         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3489         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3490       if (AvailableVRs > 0) {
3491         --AvailableVRs;
3492         return false;
3493       }
3494   }
3495 
3496   return UseMemory;
3497 }
3498 
3499 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3500 /// ensure minimum alignment required for target.
3501 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3502                                      unsigned NumBytes) {
3503   return alignTo(NumBytes, Lowering->getStackAlign());
3504 }
3505 
3506 SDValue PPCTargetLowering::LowerFormalArguments(
3507     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3508     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3509     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3510   if (Subtarget.isAIXABI())
3511     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3512                                     InVals);
3513   if (Subtarget.is64BitELFABI())
3514     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3515                                        InVals);
3516   if (Subtarget.is32BitELFABI())
3517     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3518                                        InVals);
3519 
3520   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3521                                      InVals);
3522 }
3523 
3524 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3525     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3526     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3527     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3528 
3529   // 32-bit SVR4 ABI Stack Frame Layout:
3530   //              +-----------------------------------+
3531   //        +-->  |            Back chain             |
3532   //        |     +-----------------------------------+
3533   //        |     | Floating-point register save area |
3534   //        |     +-----------------------------------+
3535   //        |     |    General register save area     |
3536   //        |     +-----------------------------------+
3537   //        |     |          CR save word             |
3538   //        |     +-----------------------------------+
3539   //        |     |         VRSAVE save word          |
3540   //        |     +-----------------------------------+
3541   //        |     |         Alignment padding         |
3542   //        |     +-----------------------------------+
3543   //        |     |     Vector register save area     |
3544   //        |     +-----------------------------------+
3545   //        |     |       Local variable space        |
3546   //        |     +-----------------------------------+
3547   //        |     |        Parameter list area        |
3548   //        |     +-----------------------------------+
3549   //        |     |           LR save word            |
3550   //        |     +-----------------------------------+
3551   // SP-->  +---  |            Back chain             |
3552   //              +-----------------------------------+
3553   //
3554   // Specifications:
3555   //   System V Application Binary Interface PowerPC Processor Supplement
3556   //   AltiVec Technology Programming Interface Manual
3557 
3558   MachineFunction &MF = DAG.getMachineFunction();
3559   MachineFrameInfo &MFI = MF.getFrameInfo();
3560   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3561 
3562   EVT PtrVT = getPointerTy(MF.getDataLayout());
3563   // Potential tail calls could cause overwriting of argument stack slots.
3564   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3565                        (CallConv == CallingConv::Fast));
3566   unsigned PtrByteSize = 4;
3567 
3568   // Assign locations to all of the incoming arguments.
3569   SmallVector<CCValAssign, 16> ArgLocs;
3570   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3571                  *DAG.getContext());
3572 
3573   // Reserve space for the linkage area on the stack.
3574   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3575   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3576   if (useSoftFloat())
3577     CCInfo.PreAnalyzeFormalArguments(Ins);
3578 
3579   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3580   CCInfo.clearWasPPCF128();
3581 
3582   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3583     CCValAssign &VA = ArgLocs[i];
3584 
3585     // Arguments stored in registers.
3586     if (VA.isRegLoc()) {
3587       const TargetRegisterClass *RC;
3588       EVT ValVT = VA.getValVT();
3589 
3590       switch (ValVT.getSimpleVT().SimpleTy) {
3591         default:
3592           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3593         case MVT::i1:
3594         case MVT::i32:
3595           RC = &PPC::GPRCRegClass;
3596           break;
3597         case MVT::f32:
3598           if (Subtarget.hasP8Vector())
3599             RC = &PPC::VSSRCRegClass;
3600           else if (Subtarget.hasSPE())
3601             RC = &PPC::GPRCRegClass;
3602           else
3603             RC = &PPC::F4RCRegClass;
3604           break;
3605         case MVT::f64:
3606           if (Subtarget.hasVSX())
3607             RC = &PPC::VSFRCRegClass;
3608           else if (Subtarget.hasSPE())
3609             // SPE passes doubles in GPR pairs.
3610             RC = &PPC::GPRCRegClass;
3611           else
3612             RC = &PPC::F8RCRegClass;
3613           break;
3614         case MVT::v16i8:
3615         case MVT::v8i16:
3616         case MVT::v4i32:
3617           RC = &PPC::VRRCRegClass;
3618           break;
3619         case MVT::v4f32:
3620           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3621           break;
3622         case MVT::v2f64:
3623         case MVT::v2i64:
3624           RC = &PPC::VRRCRegClass;
3625           break;
3626         case MVT::v4f64:
3627           RC = &PPC::QFRCRegClass;
3628           break;
3629         case MVT::v4i1:
3630           RC = &PPC::QBRCRegClass;
3631           break;
3632       }
3633 
3634       SDValue ArgValue;
3635       // Transform the arguments stored in physical registers into
3636       // virtual ones.
3637       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3638         assert(i + 1 < e && "No second half of double precision argument");
3639         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3640         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3641         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3642         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3643         if (!Subtarget.isLittleEndian())
3644           std::swap (ArgValueLo, ArgValueHi);
3645         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3646                                ArgValueHi);
3647       } else {
3648         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3649         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3650                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3651         if (ValVT == MVT::i1)
3652           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3653       }
3654 
3655       InVals.push_back(ArgValue);
3656     } else {
3657       // Argument stored in memory.
3658       assert(VA.isMemLoc());
3659 
3660       // Get the extended size of the argument type in stack
3661       unsigned ArgSize = VA.getLocVT().getStoreSize();
3662       // Get the actual size of the argument type
3663       unsigned ObjSize = VA.getValVT().getStoreSize();
3664       unsigned ArgOffset = VA.getLocMemOffset();
3665       // Stack objects in PPC32 are right justified.
3666       ArgOffset += ArgSize - ObjSize;
3667       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3668 
3669       // Create load nodes to retrieve arguments from the stack.
3670       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3671       InVals.push_back(
3672           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3673     }
3674   }
3675 
3676   // Assign locations to all of the incoming aggregate by value arguments.
3677   // Aggregates passed by value are stored in the local variable space of the
3678   // caller's stack frame, right above the parameter list area.
3679   SmallVector<CCValAssign, 16> ByValArgLocs;
3680   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3681                       ByValArgLocs, *DAG.getContext());
3682 
3683   // Reserve stack space for the allocations in CCInfo.
3684   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3685 
3686   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3687 
3688   // Area that is at least reserved in the caller of this function.
3689   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3690   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3691 
3692   // Set the size that is at least reserved in caller of this function.  Tail
3693   // call optimized function's reserved stack space needs to be aligned so that
3694   // taking the difference between two stack areas will result in an aligned
3695   // stack.
3696   MinReservedArea =
3697       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3698   FuncInfo->setMinReservedArea(MinReservedArea);
3699 
3700   SmallVector<SDValue, 8> MemOps;
3701 
3702   // If the function takes variable number of arguments, make a frame index for
3703   // the start of the first vararg value... for expansion of llvm.va_start.
3704   if (isVarArg) {
3705     static const MCPhysReg GPArgRegs[] = {
3706       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3707       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3708     };
3709     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3710 
3711     static const MCPhysReg FPArgRegs[] = {
3712       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3713       PPC::F8
3714     };
3715     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3716 
3717     if (useSoftFloat() || hasSPE())
3718        NumFPArgRegs = 0;
3719 
3720     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3721     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3722 
3723     // Make room for NumGPArgRegs and NumFPArgRegs.
3724     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3725                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3726 
3727     FuncInfo->setVarArgsStackOffset(
3728       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3729                             CCInfo.getNextStackOffset(), true));
3730 
3731     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3732     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3733 
3734     // The fixed integer arguments of a variadic function are stored to the
3735     // VarArgsFrameIndex on the stack so that they may be loaded by
3736     // dereferencing the result of va_next.
3737     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3738       // Get an existing live-in vreg, or add a new one.
3739       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3740       if (!VReg)
3741         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3742 
3743       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3744       SDValue Store =
3745           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3746       MemOps.push_back(Store);
3747       // Increment the address by four for the next argument to store
3748       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3749       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3750     }
3751 
3752     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3753     // is set.
3754     // The double arguments are stored to the VarArgsFrameIndex
3755     // on the stack.
3756     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3757       // Get an existing live-in vreg, or add a new one.
3758       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3759       if (!VReg)
3760         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3761 
3762       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3763       SDValue Store =
3764           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3765       MemOps.push_back(Store);
3766       // Increment the address by eight for the next argument to store
3767       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3768                                          PtrVT);
3769       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3770     }
3771   }
3772 
3773   if (!MemOps.empty())
3774     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3775 
3776   return Chain;
3777 }
3778 
3779 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3780 // value to MVT::i64 and then truncate to the correct register size.
3781 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3782                                              EVT ObjectVT, SelectionDAG &DAG,
3783                                              SDValue ArgVal,
3784                                              const SDLoc &dl) const {
3785   if (Flags.isSExt())
3786     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3787                          DAG.getValueType(ObjectVT));
3788   else if (Flags.isZExt())
3789     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3790                          DAG.getValueType(ObjectVT));
3791 
3792   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3793 }
3794 
3795 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3796     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3797     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3798     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3799   // TODO: add description of PPC stack frame format, or at least some docs.
3800   //
3801   bool isELFv2ABI = Subtarget.isELFv2ABI();
3802   bool isLittleEndian = Subtarget.isLittleEndian();
3803   MachineFunction &MF = DAG.getMachineFunction();
3804   MachineFrameInfo &MFI = MF.getFrameInfo();
3805   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3806 
3807   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3808          "fastcc not supported on varargs functions");
3809 
3810   EVT PtrVT = getPointerTy(MF.getDataLayout());
3811   // Potential tail calls could cause overwriting of argument stack slots.
3812   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3813                        (CallConv == CallingConv::Fast));
3814   unsigned PtrByteSize = 8;
3815   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3816 
3817   static const MCPhysReg GPR[] = {
3818     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3819     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3820   };
3821   static const MCPhysReg VR[] = {
3822     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3823     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3824   };
3825 
3826   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3827   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3828   const unsigned Num_VR_Regs  = array_lengthof(VR);
3829   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3830 
3831   // Do a first pass over the arguments to determine whether the ABI
3832   // guarantees that our caller has allocated the parameter save area
3833   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3834   // in the ELFv2 ABI, it is true if this is a vararg function or if
3835   // any parameter is located in a stack slot.
3836 
3837   bool HasParameterArea = !isELFv2ABI || isVarArg;
3838   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3839   unsigned NumBytes = LinkageSize;
3840   unsigned AvailableFPRs = Num_FPR_Regs;
3841   unsigned AvailableVRs = Num_VR_Regs;
3842   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3843     if (Ins[i].Flags.isNest())
3844       continue;
3845 
3846     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3847                                PtrByteSize, LinkageSize, ParamAreaSize,
3848                                NumBytes, AvailableFPRs, AvailableVRs,
3849                                Subtarget.hasQPX()))
3850       HasParameterArea = true;
3851   }
3852 
3853   // Add DAG nodes to load the arguments or copy them out of registers.  On
3854   // entry to a function on PPC, the arguments start after the linkage area,
3855   // although the first ones are often in registers.
3856 
3857   unsigned ArgOffset = LinkageSize;
3858   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3859   unsigned &QFPR_idx = FPR_idx;
3860   SmallVector<SDValue, 8> MemOps;
3861   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3862   unsigned CurArgIdx = 0;
3863   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3864     SDValue ArgVal;
3865     bool needsLoad = false;
3866     EVT ObjectVT = Ins[ArgNo].VT;
3867     EVT OrigVT = Ins[ArgNo].ArgVT;
3868     unsigned ObjSize = ObjectVT.getStoreSize();
3869     unsigned ArgSize = ObjSize;
3870     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3871     if (Ins[ArgNo].isOrigArg()) {
3872       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3873       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3874     }
3875     // We re-align the argument offset for each argument, except when using the
3876     // fast calling convention, when we need to make sure we do that only when
3877     // we'll actually use a stack slot.
3878     unsigned CurArgOffset;
3879     Align Alignment;
3880     auto ComputeArgOffset = [&]() {
3881       /* Respect alignment of argument on the stack.  */
3882       Alignment =
3883           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3884       ArgOffset = alignTo(ArgOffset, Alignment);
3885       CurArgOffset = ArgOffset;
3886     };
3887 
3888     if (CallConv != CallingConv::Fast) {
3889       ComputeArgOffset();
3890 
3891       /* Compute GPR index associated with argument offset.  */
3892       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3893       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3894     }
3895 
3896     // FIXME the codegen can be much improved in some cases.
3897     // We do not have to keep everything in memory.
3898     if (Flags.isByVal()) {
3899       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3900 
3901       if (CallConv == CallingConv::Fast)
3902         ComputeArgOffset();
3903 
3904       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3905       ObjSize = Flags.getByValSize();
3906       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3907       // Empty aggregate parameters do not take up registers.  Examples:
3908       //   struct { } a;
3909       //   union  { } b;
3910       //   int c[0];
3911       // etc.  However, we have to provide a place-holder in InVals, so
3912       // pretend we have an 8-byte item at the current address for that
3913       // purpose.
3914       if (!ObjSize) {
3915         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3916         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3917         InVals.push_back(FIN);
3918         continue;
3919       }
3920 
3921       // Create a stack object covering all stack doublewords occupied
3922       // by the argument.  If the argument is (fully or partially) on
3923       // the stack, or if the argument is fully in registers but the
3924       // caller has allocated the parameter save anyway, we can refer
3925       // directly to the caller's stack frame.  Otherwise, create a
3926       // local copy in our own frame.
3927       int FI;
3928       if (HasParameterArea ||
3929           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3930         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3931       else
3932         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3933       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3934 
3935       // Handle aggregates smaller than 8 bytes.
3936       if (ObjSize < PtrByteSize) {
3937         // The value of the object is its address, which differs from the
3938         // address of the enclosing doubleword on big-endian systems.
3939         SDValue Arg = FIN;
3940         if (!isLittleEndian) {
3941           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3942           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3943         }
3944         InVals.push_back(Arg);
3945 
3946         if (GPR_idx != Num_GPR_Regs) {
3947           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3948           FuncInfo->addLiveInAttr(VReg, Flags);
3949           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3950           SDValue Store;
3951 
3952           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3953             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3954                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3955             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3956                                       MachinePointerInfo(&*FuncArg), ObjType);
3957           } else {
3958             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3959             // store the whole register as-is to the parameter save area
3960             // slot.
3961             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3962                                  MachinePointerInfo(&*FuncArg));
3963           }
3964 
3965           MemOps.push_back(Store);
3966         }
3967         // Whether we copied from a register or not, advance the offset
3968         // into the parameter save area by a full doubleword.
3969         ArgOffset += PtrByteSize;
3970         continue;
3971       }
3972 
3973       // The value of the object is its address, which is the address of
3974       // its first stack doubleword.
3975       InVals.push_back(FIN);
3976 
3977       // Store whatever pieces of the object are in registers to memory.
3978       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3979         if (GPR_idx == Num_GPR_Regs)
3980           break;
3981 
3982         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3983         FuncInfo->addLiveInAttr(VReg, Flags);
3984         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3985         SDValue Addr = FIN;
3986         if (j) {
3987           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3988           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3989         }
3990         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3991                                      MachinePointerInfo(&*FuncArg, j));
3992         MemOps.push_back(Store);
3993         ++GPR_idx;
3994       }
3995       ArgOffset += ArgSize;
3996       continue;
3997     }
3998 
3999     switch (ObjectVT.getSimpleVT().SimpleTy) {
4000     default: llvm_unreachable("Unhandled argument type!");
4001     case MVT::i1:
4002     case MVT::i32:
4003     case MVT::i64:
4004       if (Flags.isNest()) {
4005         // The 'nest' parameter, if any, is passed in R11.
4006         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4007         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4008 
4009         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4010           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4011 
4012         break;
4013       }
4014 
4015       // These can be scalar arguments or elements of an integer array type
4016       // passed directly.  Clang may use those instead of "byval" aggregate
4017       // types to avoid forcing arguments to memory unnecessarily.
4018       if (GPR_idx != Num_GPR_Regs) {
4019         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4020         FuncInfo->addLiveInAttr(VReg, Flags);
4021         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4022 
4023         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4024           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4025           // value to MVT::i64 and then truncate to the correct register size.
4026           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4027       } else {
4028         if (CallConv == CallingConv::Fast)
4029           ComputeArgOffset();
4030 
4031         needsLoad = true;
4032         ArgSize = PtrByteSize;
4033       }
4034       if (CallConv != CallingConv::Fast || needsLoad)
4035         ArgOffset += 8;
4036       break;
4037 
4038     case MVT::f32:
4039     case MVT::f64:
4040       // These can be scalar arguments or elements of a float array type
4041       // passed directly.  The latter are used to implement ELFv2 homogenous
4042       // float aggregates.
4043       if (FPR_idx != Num_FPR_Regs) {
4044         unsigned VReg;
4045 
4046         if (ObjectVT == MVT::f32)
4047           VReg = MF.addLiveIn(FPR[FPR_idx],
4048                               Subtarget.hasP8Vector()
4049                                   ? &PPC::VSSRCRegClass
4050                                   : &PPC::F4RCRegClass);
4051         else
4052           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4053                                                 ? &PPC::VSFRCRegClass
4054                                                 : &PPC::F8RCRegClass);
4055 
4056         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4057         ++FPR_idx;
4058       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4059         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4060         // once we support fp <-> gpr moves.
4061 
4062         // This can only ever happen in the presence of f32 array types,
4063         // since otherwise we never run out of FPRs before running out
4064         // of GPRs.
4065         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4066         FuncInfo->addLiveInAttr(VReg, Flags);
4067         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4068 
4069         if (ObjectVT == MVT::f32) {
4070           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4071             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4072                                  DAG.getConstant(32, dl, MVT::i32));
4073           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4074         }
4075 
4076         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4077       } else {
4078         if (CallConv == CallingConv::Fast)
4079           ComputeArgOffset();
4080 
4081         needsLoad = true;
4082       }
4083 
4084       // When passing an array of floats, the array occupies consecutive
4085       // space in the argument area; only round up to the next doubleword
4086       // at the end of the array.  Otherwise, each float takes 8 bytes.
4087       if (CallConv != CallingConv::Fast || needsLoad) {
4088         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4089         ArgOffset += ArgSize;
4090         if (Flags.isInConsecutiveRegsLast())
4091           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4092       }
4093       break;
4094     case MVT::v4f32:
4095     case MVT::v4i32:
4096     case MVT::v8i16:
4097     case MVT::v16i8:
4098     case MVT::v2f64:
4099     case MVT::v2i64:
4100     case MVT::v1i128:
4101     case MVT::f128:
4102       if (!Subtarget.hasQPX()) {
4103         // These can be scalar arguments or elements of a vector array type
4104         // passed directly.  The latter are used to implement ELFv2 homogenous
4105         // vector aggregates.
4106         if (VR_idx != Num_VR_Regs) {
4107           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4108           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4109           ++VR_idx;
4110         } else {
4111           if (CallConv == CallingConv::Fast)
4112             ComputeArgOffset();
4113           needsLoad = true;
4114         }
4115         if (CallConv != CallingConv::Fast || needsLoad)
4116           ArgOffset += 16;
4117         break;
4118       } // not QPX
4119 
4120       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4121              "Invalid QPX parameter type");
4122       LLVM_FALLTHROUGH;
4123 
4124     case MVT::v4f64:
4125     case MVT::v4i1:
4126       // QPX vectors are treated like their scalar floating-point subregisters
4127       // (except that they're larger).
4128       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4129       if (QFPR_idx != Num_QFPR_Regs) {
4130         const TargetRegisterClass *RC;
4131         switch (ObjectVT.getSimpleVT().SimpleTy) {
4132         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4133         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4134         default:         RC = &PPC::QBRCRegClass; break;
4135         }
4136 
4137         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4138         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4139         ++QFPR_idx;
4140       } else {
4141         if (CallConv == CallingConv::Fast)
4142           ComputeArgOffset();
4143         needsLoad = true;
4144       }
4145       if (CallConv != CallingConv::Fast || needsLoad)
4146         ArgOffset += Sz;
4147       break;
4148     }
4149 
4150     // We need to load the argument to a virtual register if we determined
4151     // above that we ran out of physical registers of the appropriate type.
4152     if (needsLoad) {
4153       if (ObjSize < ArgSize && !isLittleEndian)
4154         CurArgOffset += ArgSize - ObjSize;
4155       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4156       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4157       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4158     }
4159 
4160     InVals.push_back(ArgVal);
4161   }
4162 
4163   // Area that is at least reserved in the caller of this function.
4164   unsigned MinReservedArea;
4165   if (HasParameterArea)
4166     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4167   else
4168     MinReservedArea = LinkageSize;
4169 
4170   // Set the size that is at least reserved in caller of this function.  Tail
4171   // call optimized functions' reserved stack space needs to be aligned so that
4172   // taking the difference between two stack areas will result in an aligned
4173   // stack.
4174   MinReservedArea =
4175       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4176   FuncInfo->setMinReservedArea(MinReservedArea);
4177 
4178   // If the function takes variable number of arguments, make a frame index for
4179   // the start of the first vararg value... for expansion of llvm.va_start.
4180   if (isVarArg) {
4181     int Depth = ArgOffset;
4182 
4183     FuncInfo->setVarArgsFrameIndex(
4184       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4185     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4186 
4187     // If this function is vararg, store any remaining integer argument regs
4188     // to their spots on the stack so that they may be loaded by dereferencing
4189     // the result of va_next.
4190     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4191          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4192       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4193       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4194       SDValue Store =
4195           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4196       MemOps.push_back(Store);
4197       // Increment the address by four for the next argument to store
4198       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4199       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4200     }
4201   }
4202 
4203   if (!MemOps.empty())
4204     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4205 
4206   return Chain;
4207 }
4208 
4209 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4210     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4211     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4212     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4213   // TODO: add description of PPC stack frame format, or at least some docs.
4214   //
4215   MachineFunction &MF = DAG.getMachineFunction();
4216   MachineFrameInfo &MFI = MF.getFrameInfo();
4217   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4218 
4219   EVT PtrVT = getPointerTy(MF.getDataLayout());
4220   bool isPPC64 = PtrVT == MVT::i64;
4221   // Potential tail calls could cause overwriting of argument stack slots.
4222   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4223                        (CallConv == CallingConv::Fast));
4224   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4225   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4226   unsigned ArgOffset = LinkageSize;
4227   // Area that is at least reserved in caller of this function.
4228   unsigned MinReservedArea = ArgOffset;
4229 
4230   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4231     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4232     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4233   };
4234   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4235     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4236     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4237   };
4238   static const MCPhysReg VR[] = {
4239     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4240     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4241   };
4242 
4243   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4244   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4245   const unsigned Num_VR_Regs  = array_lengthof( VR);
4246 
4247   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4248 
4249   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4250 
4251   // In 32-bit non-varargs functions, the stack space for vectors is after the
4252   // stack space for non-vectors.  We do not use this space unless we have
4253   // too many vectors to fit in registers, something that only occurs in
4254   // constructed examples:), but we have to walk the arglist to figure
4255   // that out...for the pathological case, compute VecArgOffset as the
4256   // start of the vector parameter area.  Computing VecArgOffset is the
4257   // entire point of the following loop.
4258   unsigned VecArgOffset = ArgOffset;
4259   if (!isVarArg && !isPPC64) {
4260     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4261          ++ArgNo) {
4262       EVT ObjectVT = Ins[ArgNo].VT;
4263       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4264 
4265       if (Flags.isByVal()) {
4266         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4267         unsigned ObjSize = Flags.getByValSize();
4268         unsigned ArgSize =
4269                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4270         VecArgOffset += ArgSize;
4271         continue;
4272       }
4273 
4274       switch(ObjectVT.getSimpleVT().SimpleTy) {
4275       default: llvm_unreachable("Unhandled argument type!");
4276       case MVT::i1:
4277       case MVT::i32:
4278       case MVT::f32:
4279         VecArgOffset += 4;
4280         break;
4281       case MVT::i64:  // PPC64
4282       case MVT::f64:
4283         // FIXME: We are guaranteed to be !isPPC64 at this point.
4284         // Does MVT::i64 apply?
4285         VecArgOffset += 8;
4286         break;
4287       case MVT::v4f32:
4288       case MVT::v4i32:
4289       case MVT::v8i16:
4290       case MVT::v16i8:
4291         // Nothing to do, we're only looking at Nonvector args here.
4292         break;
4293       }
4294     }
4295   }
4296   // We've found where the vector parameter area in memory is.  Skip the
4297   // first 12 parameters; these don't use that memory.
4298   VecArgOffset = ((VecArgOffset+15)/16)*16;
4299   VecArgOffset += 12*16;
4300 
4301   // Add DAG nodes to load the arguments or copy them out of registers.  On
4302   // entry to a function on PPC, the arguments start after the linkage area,
4303   // although the first ones are often in registers.
4304 
4305   SmallVector<SDValue, 8> MemOps;
4306   unsigned nAltivecParamsAtEnd = 0;
4307   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4308   unsigned CurArgIdx = 0;
4309   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4310     SDValue ArgVal;
4311     bool needsLoad = false;
4312     EVT ObjectVT = Ins[ArgNo].VT;
4313     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4314     unsigned ArgSize = ObjSize;
4315     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4316     if (Ins[ArgNo].isOrigArg()) {
4317       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4318       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4319     }
4320     unsigned CurArgOffset = ArgOffset;
4321 
4322     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4323     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4324         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4325       if (isVarArg || isPPC64) {
4326         MinReservedArea = ((MinReservedArea+15)/16)*16;
4327         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4328                                                   Flags,
4329                                                   PtrByteSize);
4330       } else  nAltivecParamsAtEnd++;
4331     } else
4332       // Calculate min reserved area.
4333       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4334                                                 Flags,
4335                                                 PtrByteSize);
4336 
4337     // FIXME the codegen can be much improved in some cases.
4338     // We do not have to keep everything in memory.
4339     if (Flags.isByVal()) {
4340       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4341 
4342       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4343       ObjSize = Flags.getByValSize();
4344       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4345       // Objects of size 1 and 2 are right justified, everything else is
4346       // left justified.  This means the memory address is adjusted forwards.
4347       if (ObjSize==1 || ObjSize==2) {
4348         CurArgOffset = CurArgOffset + (4 - ObjSize);
4349       }
4350       // The value of the object is its address.
4351       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4352       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4353       InVals.push_back(FIN);
4354       if (ObjSize==1 || ObjSize==2) {
4355         if (GPR_idx != Num_GPR_Regs) {
4356           unsigned VReg;
4357           if (isPPC64)
4358             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4359           else
4360             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4361           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4362           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4363           SDValue Store =
4364               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4365                                 MachinePointerInfo(&*FuncArg), ObjType);
4366           MemOps.push_back(Store);
4367           ++GPR_idx;
4368         }
4369 
4370         ArgOffset += PtrByteSize;
4371 
4372         continue;
4373       }
4374       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4375         // Store whatever pieces of the object are in registers
4376         // to memory.  ArgOffset will be the address of the beginning
4377         // of the object.
4378         if (GPR_idx != Num_GPR_Regs) {
4379           unsigned VReg;
4380           if (isPPC64)
4381             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4382           else
4383             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4384           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4385           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4386           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4387           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4388                                        MachinePointerInfo(&*FuncArg, j));
4389           MemOps.push_back(Store);
4390           ++GPR_idx;
4391           ArgOffset += PtrByteSize;
4392         } else {
4393           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4394           break;
4395         }
4396       }
4397       continue;
4398     }
4399 
4400     switch (ObjectVT.getSimpleVT().SimpleTy) {
4401     default: llvm_unreachable("Unhandled argument type!");
4402     case MVT::i1:
4403     case MVT::i32:
4404       if (!isPPC64) {
4405         if (GPR_idx != Num_GPR_Regs) {
4406           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4407           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4408 
4409           if (ObjectVT == MVT::i1)
4410             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4411 
4412           ++GPR_idx;
4413         } else {
4414           needsLoad = true;
4415           ArgSize = PtrByteSize;
4416         }
4417         // All int arguments reserve stack space in the Darwin ABI.
4418         ArgOffset += PtrByteSize;
4419         break;
4420       }
4421       LLVM_FALLTHROUGH;
4422     case MVT::i64:  // PPC64
4423       if (GPR_idx != Num_GPR_Regs) {
4424         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4425         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4426 
4427         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4428           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4429           // value to MVT::i64 and then truncate to the correct register size.
4430           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4431 
4432         ++GPR_idx;
4433       } else {
4434         needsLoad = true;
4435         ArgSize = PtrByteSize;
4436       }
4437       // All int arguments reserve stack space in the Darwin ABI.
4438       ArgOffset += 8;
4439       break;
4440 
4441     case MVT::f32:
4442     case MVT::f64:
4443       // Every 4 bytes of argument space consumes one of the GPRs available for
4444       // argument passing.
4445       if (GPR_idx != Num_GPR_Regs) {
4446         ++GPR_idx;
4447         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4448           ++GPR_idx;
4449       }
4450       if (FPR_idx != Num_FPR_Regs) {
4451         unsigned VReg;
4452 
4453         if (ObjectVT == MVT::f32)
4454           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4455         else
4456           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4457 
4458         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4459         ++FPR_idx;
4460       } else {
4461         needsLoad = true;
4462       }
4463 
4464       // All FP arguments reserve stack space in the Darwin ABI.
4465       ArgOffset += isPPC64 ? 8 : ObjSize;
4466       break;
4467     case MVT::v4f32:
4468     case MVT::v4i32:
4469     case MVT::v8i16:
4470     case MVT::v16i8:
4471       // Note that vector arguments in registers don't reserve stack space,
4472       // except in varargs functions.
4473       if (VR_idx != Num_VR_Regs) {
4474         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4475         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4476         if (isVarArg) {
4477           while ((ArgOffset % 16) != 0) {
4478             ArgOffset += PtrByteSize;
4479             if (GPR_idx != Num_GPR_Regs)
4480               GPR_idx++;
4481           }
4482           ArgOffset += 16;
4483           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4484         }
4485         ++VR_idx;
4486       } else {
4487         if (!isVarArg && !isPPC64) {
4488           // Vectors go after all the nonvectors.
4489           CurArgOffset = VecArgOffset;
4490           VecArgOffset += 16;
4491         } else {
4492           // Vectors are aligned.
4493           ArgOffset = ((ArgOffset+15)/16)*16;
4494           CurArgOffset = ArgOffset;
4495           ArgOffset += 16;
4496         }
4497         needsLoad = true;
4498       }
4499       break;
4500     }
4501 
4502     // We need to load the argument to a virtual register if we determined above
4503     // that we ran out of physical registers of the appropriate type.
4504     if (needsLoad) {
4505       int FI = MFI.CreateFixedObject(ObjSize,
4506                                      CurArgOffset + (ArgSize - ObjSize),
4507                                      isImmutable);
4508       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4509       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4510     }
4511 
4512     InVals.push_back(ArgVal);
4513   }
4514 
4515   // Allow for Altivec parameters at the end, if needed.
4516   if (nAltivecParamsAtEnd) {
4517     MinReservedArea = ((MinReservedArea+15)/16)*16;
4518     MinReservedArea += 16*nAltivecParamsAtEnd;
4519   }
4520 
4521   // Area that is at least reserved in the caller of this function.
4522   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4523 
4524   // Set the size that is at least reserved in caller of this function.  Tail
4525   // call optimized functions' reserved stack space needs to be aligned so that
4526   // taking the difference between two stack areas will result in an aligned
4527   // stack.
4528   MinReservedArea =
4529       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4530   FuncInfo->setMinReservedArea(MinReservedArea);
4531 
4532   // If the function takes variable number of arguments, make a frame index for
4533   // the start of the first vararg value... for expansion of llvm.va_start.
4534   if (isVarArg) {
4535     int Depth = ArgOffset;
4536 
4537     FuncInfo->setVarArgsFrameIndex(
4538       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4539                             Depth, true));
4540     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4541 
4542     // If this function is vararg, store any remaining integer argument regs
4543     // to their spots on the stack so that they may be loaded by dereferencing
4544     // the result of va_next.
4545     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4546       unsigned VReg;
4547 
4548       if (isPPC64)
4549         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4550       else
4551         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4552 
4553       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4554       SDValue Store =
4555           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4556       MemOps.push_back(Store);
4557       // Increment the address by four for the next argument to store
4558       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4559       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4560     }
4561   }
4562 
4563   if (!MemOps.empty())
4564     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4565 
4566   return Chain;
4567 }
4568 
4569 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4570 /// adjusted to accommodate the arguments for the tailcall.
4571 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4572                                    unsigned ParamSize) {
4573 
4574   if (!isTailCall) return 0;
4575 
4576   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4577   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4578   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4579   // Remember only if the new adjustment is bigger.
4580   if (SPDiff < FI->getTailCallSPDelta())
4581     FI->setTailCallSPDelta(SPDiff);
4582 
4583   return SPDiff;
4584 }
4585 
4586 static bool isFunctionGlobalAddress(SDValue Callee);
4587 
4588 static bool
4589 callsShareTOCBase(const Function *Caller, SDValue Callee,
4590                     const TargetMachine &TM) {
4591    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4592    // don't have enough information to determine if the caller and calle share
4593    // the same  TOC base, so we have to pessimistically assume they don't for
4594    // correctness.
4595    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4596    if (!G)
4597      return false;
4598 
4599    const GlobalValue *GV = G->getGlobal();
4600   // The medium and large code models are expected to provide a sufficiently
4601   // large TOC to provide all data addressing needs of a module with a
4602   // single TOC. Since each module will be addressed with a single TOC then we
4603   // only need to check that caller and callee don't cross dso boundaries.
4604   if (CodeModel::Medium == TM.getCodeModel() ||
4605       CodeModel::Large == TM.getCodeModel())
4606     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4607 
4608   // Otherwise we need to ensure callee and caller are in the same section,
4609   // since the linker may allocate multiple TOCs, and we don't know which
4610   // sections will belong to the same TOC base.
4611 
4612   if (!GV->isStrongDefinitionForLinker())
4613     return false;
4614 
4615   // Any explicitly-specified sections and section prefixes must also match.
4616   // Also, if we're using -ffunction-sections, then each function is always in
4617   // a different section (the same is true for COMDAT functions).
4618   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4619       GV->getSection() != Caller->getSection())
4620     return false;
4621   if (const auto *F = dyn_cast<Function>(GV)) {
4622     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4623       return false;
4624   }
4625 
4626   // If the callee might be interposed, then we can't assume the ultimate call
4627   // target will be in the same section. Even in cases where we can assume that
4628   // interposition won't happen, in any case where the linker might insert a
4629   // stub to allow for interposition, we must generate code as though
4630   // interposition might occur. To understand why this matters, consider a
4631   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4632   // in the same section, but a is in a different module (i.e. has a different
4633   // TOC base pointer). If the linker allows for interposition between b and c,
4634   // then it will generate a stub for the call edge between b and c which will
4635   // save the TOC pointer into the designated stack slot allocated by b. If we
4636   // return true here, and therefore allow a tail call between b and c, that
4637   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4638   // pointer into the stack slot allocated by a (where the a -> b stub saved
4639   // a's TOC base pointer). If we're not considering a tail call, but rather,
4640   // whether a nop is needed after the call instruction in b, because the linker
4641   // will insert a stub, it might complain about a missing nop if we omit it
4642   // (although many don't complain in this case).
4643   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4644     return false;
4645 
4646   return true;
4647 }
4648 
4649 static bool
4650 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4651                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4652   assert(Subtarget.is64BitELFABI());
4653 
4654   const unsigned PtrByteSize = 8;
4655   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4656 
4657   static const MCPhysReg GPR[] = {
4658     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4659     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4660   };
4661   static const MCPhysReg VR[] = {
4662     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4663     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4664   };
4665 
4666   const unsigned NumGPRs = array_lengthof(GPR);
4667   const unsigned NumFPRs = 13;
4668   const unsigned NumVRs = array_lengthof(VR);
4669   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4670 
4671   unsigned NumBytes = LinkageSize;
4672   unsigned AvailableFPRs = NumFPRs;
4673   unsigned AvailableVRs = NumVRs;
4674 
4675   for (const ISD::OutputArg& Param : Outs) {
4676     if (Param.Flags.isNest()) continue;
4677 
4678     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4679                                PtrByteSize, LinkageSize, ParamAreaSize,
4680                                NumBytes, AvailableFPRs, AvailableVRs,
4681                                Subtarget.hasQPX()))
4682       return true;
4683   }
4684   return false;
4685 }
4686 
4687 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4688   if (CB.arg_size() != CallerFn->arg_size())
4689     return false;
4690 
4691   auto CalleeArgIter = CB.arg_begin();
4692   auto CalleeArgEnd = CB.arg_end();
4693   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4694 
4695   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4696     const Value* CalleeArg = *CalleeArgIter;
4697     const Value* CallerArg = &(*CallerArgIter);
4698     if (CalleeArg == CallerArg)
4699       continue;
4700 
4701     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4702     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4703     //      }
4704     // 1st argument of callee is undef and has the same type as caller.
4705     if (CalleeArg->getType() == CallerArg->getType() &&
4706         isa<UndefValue>(CalleeArg))
4707       continue;
4708 
4709     return false;
4710   }
4711 
4712   return true;
4713 }
4714 
4715 // Returns true if TCO is possible between the callers and callees
4716 // calling conventions.
4717 static bool
4718 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4719                                     CallingConv::ID CalleeCC) {
4720   // Tail calls are possible with fastcc and ccc.
4721   auto isTailCallableCC  = [] (CallingConv::ID CC){
4722       return  CC == CallingConv::C || CC == CallingConv::Fast;
4723   };
4724   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4725     return false;
4726 
4727   // We can safely tail call both fastcc and ccc callees from a c calling
4728   // convention caller. If the caller is fastcc, we may have less stack space
4729   // than a non-fastcc caller with the same signature so disable tail-calls in
4730   // that case.
4731   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4732 }
4733 
4734 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4735     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4736     const SmallVectorImpl<ISD::OutputArg> &Outs,
4737     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4738   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4739 
4740   // FIXME: Tail calls are currently disabled when using PC Relative addressing.
4741   // The issue is that PC Relative is only partially implemented and so there
4742   // is currently a mix of functions that require the TOC and functions that do
4743   // not require it. If we have A calls B calls C and both A and B require the
4744   // TOC and C does not and is marked as clobbering R2 then it is not safe for
4745   // B to tail call C. Since we do not have the information of whether or not
4746   // a funciton needs to use the TOC here in this function we need to be
4747   // conservatively safe and disable all tail calls for now.
4748   if (Subtarget.isUsingPCRelativeCalls()) return false;
4749 
4750   if (DisableSCO && !TailCallOpt) return false;
4751 
4752   // Variadic argument functions are not supported.
4753   if (isVarArg) return false;
4754 
4755   auto &Caller = DAG.getMachineFunction().getFunction();
4756   // Check that the calling conventions are compatible for tco.
4757   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4758     return false;
4759 
4760   // Caller contains any byval parameter is not supported.
4761   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4762     return false;
4763 
4764   // Callee contains any byval parameter is not supported, too.
4765   // Note: This is a quick work around, because in some cases, e.g.
4766   // caller's stack size > callee's stack size, we are still able to apply
4767   // sibling call optimization. For example, gcc is able to do SCO for caller1
4768   // in the following example, but not for caller2.
4769   //   struct test {
4770   //     long int a;
4771   //     char ary[56];
4772   //   } gTest;
4773   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4774   //     b->a = v.a;
4775   //     return 0;
4776   //   }
4777   //   void caller1(struct test a, struct test c, struct test *b) {
4778   //     callee(gTest, b); }
4779   //   void caller2(struct test *b) { callee(gTest, b); }
4780   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4781     return false;
4782 
4783   // If callee and caller use different calling conventions, we cannot pass
4784   // parameters on stack since offsets for the parameter area may be different.
4785   if (Caller.getCallingConv() != CalleeCC &&
4786       needStackSlotPassParameters(Subtarget, Outs))
4787     return false;
4788 
4789   // No TCO/SCO on indirect call because Caller have to restore its TOC
4790   if (!isFunctionGlobalAddress(Callee) &&
4791       !isa<ExternalSymbolSDNode>(Callee))
4792     return false;
4793 
4794   // If the caller and callee potentially have different TOC bases then we
4795   // cannot tail call since we need to restore the TOC pointer after the call.
4796   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4797   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4798     return false;
4799 
4800   // TCO allows altering callee ABI, so we don't have to check further.
4801   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4802     return true;
4803 
4804   if (DisableSCO) return false;
4805 
4806   // If callee use the same argument list that caller is using, then we can
4807   // apply SCO on this case. If it is not, then we need to check if callee needs
4808   // stack for passing arguments.
4809   assert(CB && "Expected to have a CallBase!");
4810   if (!hasSameArgumentList(&Caller, *CB) &&
4811       needStackSlotPassParameters(Subtarget, Outs)) {
4812     return false;
4813   }
4814 
4815   return true;
4816 }
4817 
4818 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4819 /// for tail call optimization. Targets which want to do tail call
4820 /// optimization should implement this function.
4821 bool
4822 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4823                                                      CallingConv::ID CalleeCC,
4824                                                      bool isVarArg,
4825                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4826                                                      SelectionDAG& DAG) const {
4827   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4828     return false;
4829 
4830   // Variable argument functions are not supported.
4831   if (isVarArg)
4832     return false;
4833 
4834   MachineFunction &MF = DAG.getMachineFunction();
4835   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4836   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4837     // Functions containing by val parameters are not supported.
4838     for (unsigned i = 0; i != Ins.size(); i++) {
4839        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4840        if (Flags.isByVal()) return false;
4841     }
4842 
4843     // Non-PIC/GOT tail calls are supported.
4844     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4845       return true;
4846 
4847     // At the moment we can only do local tail calls (in same module, hidden
4848     // or protected) if we are generating PIC.
4849     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4850       return G->getGlobal()->hasHiddenVisibility()
4851           || G->getGlobal()->hasProtectedVisibility();
4852   }
4853 
4854   return false;
4855 }
4856 
4857 /// isCallCompatibleAddress - Return the immediate to use if the specified
4858 /// 32-bit value is representable in the immediate field of a BxA instruction.
4859 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4860   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4861   if (!C) return nullptr;
4862 
4863   int Addr = C->getZExtValue();
4864   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4865       SignExtend32<26>(Addr) != Addr)
4866     return nullptr;  // Top 6 bits have to be sext of immediate.
4867 
4868   return DAG
4869       .getConstant(
4870           (int)C->getZExtValue() >> 2, SDLoc(Op),
4871           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4872       .getNode();
4873 }
4874 
4875 namespace {
4876 
4877 struct TailCallArgumentInfo {
4878   SDValue Arg;
4879   SDValue FrameIdxOp;
4880   int FrameIdx = 0;
4881 
4882   TailCallArgumentInfo() = default;
4883 };
4884 
4885 } // end anonymous namespace
4886 
4887 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4888 static void StoreTailCallArgumentsToStackSlot(
4889     SelectionDAG &DAG, SDValue Chain,
4890     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4891     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4892   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4893     SDValue Arg = TailCallArgs[i].Arg;
4894     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4895     int FI = TailCallArgs[i].FrameIdx;
4896     // Store relative to framepointer.
4897     MemOpChains.push_back(DAG.getStore(
4898         Chain, dl, Arg, FIN,
4899         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4900   }
4901 }
4902 
4903 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4904 /// the appropriate stack slot for the tail call optimized function call.
4905 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4906                                              SDValue OldRetAddr, SDValue OldFP,
4907                                              int SPDiff, const SDLoc &dl) {
4908   if (SPDiff) {
4909     // Calculate the new stack slot for the return address.
4910     MachineFunction &MF = DAG.getMachineFunction();
4911     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4912     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4913     bool isPPC64 = Subtarget.isPPC64();
4914     int SlotSize = isPPC64 ? 8 : 4;
4915     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4916     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4917                                                          NewRetAddrLoc, true);
4918     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4919     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4920     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4921                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4922   }
4923   return Chain;
4924 }
4925 
4926 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4927 /// the position of the argument.
4928 static void
4929 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4930                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4931                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4932   int Offset = ArgOffset + SPDiff;
4933   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4934   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4935   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4936   SDValue FIN = DAG.getFrameIndex(FI, VT);
4937   TailCallArgumentInfo Info;
4938   Info.Arg = Arg;
4939   Info.FrameIdxOp = FIN;
4940   Info.FrameIdx = FI;
4941   TailCallArguments.push_back(Info);
4942 }
4943 
4944 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4945 /// stack slot. Returns the chain as result and the loaded frame pointers in
4946 /// LROpOut/FPOpout. Used when tail calling.
4947 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4948     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4949     SDValue &FPOpOut, const SDLoc &dl) const {
4950   if (SPDiff) {
4951     // Load the LR and FP stack slot for later adjusting.
4952     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4953     LROpOut = getReturnAddrFrameIndex(DAG);
4954     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4955     Chain = SDValue(LROpOut.getNode(), 1);
4956   }
4957   return Chain;
4958 }
4959 
4960 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4961 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4962 /// specified by the specific parameter attribute. The copy will be passed as
4963 /// a byval function parameter.
4964 /// Sometimes what we are copying is the end of a larger object, the part that
4965 /// does not fit in registers.
4966 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4967                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4968                                          SelectionDAG &DAG, const SDLoc &dl) {
4969   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4970   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4971                        Flags.getNonZeroByValAlign(), false, false, false,
4972                        MachinePointerInfo(), MachinePointerInfo());
4973 }
4974 
4975 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4976 /// tail calls.
4977 static void LowerMemOpCallTo(
4978     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4979     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4980     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4981     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4982   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4983   if (!isTailCall) {
4984     if (isVector) {
4985       SDValue StackPtr;
4986       if (isPPC64)
4987         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4988       else
4989         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4990       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4991                            DAG.getConstant(ArgOffset, dl, PtrVT));
4992     }
4993     MemOpChains.push_back(
4994         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4995     // Calculate and remember argument location.
4996   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4997                                   TailCallArguments);
4998 }
4999 
5000 static void
5001 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5002                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5003                 SDValue FPOp,
5004                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5005   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5006   // might overwrite each other in case of tail call optimization.
5007   SmallVector<SDValue, 8> MemOpChains2;
5008   // Do not flag preceding copytoreg stuff together with the following stuff.
5009   InFlag = SDValue();
5010   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5011                                     MemOpChains2, dl);
5012   if (!MemOpChains2.empty())
5013     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5014 
5015   // Store the return address to the appropriate stack slot.
5016   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5017 
5018   // Emit callseq_end just before tailcall node.
5019   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5020                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5021   InFlag = Chain.getValue(1);
5022 }
5023 
5024 // Is this global address that of a function that can be called by name? (as
5025 // opposed to something that must hold a descriptor for an indirect call).
5026 static bool isFunctionGlobalAddress(SDValue Callee) {
5027   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5028     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5029         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5030       return false;
5031 
5032     return G->getGlobal()->getValueType()->isFunctionTy();
5033   }
5034 
5035   return false;
5036 }
5037 
5038 SDValue PPCTargetLowering::LowerCallResult(
5039     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5040     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5041     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5042   SmallVector<CCValAssign, 16> RVLocs;
5043   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5044                     *DAG.getContext());
5045 
5046   CCRetInfo.AnalyzeCallResult(
5047       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5048                ? RetCC_PPC_Cold
5049                : RetCC_PPC);
5050 
5051   // Copy all of the result registers out of their specified physreg.
5052   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5053     CCValAssign &VA = RVLocs[i];
5054     assert(VA.isRegLoc() && "Can only return in registers!");
5055 
5056     SDValue Val;
5057 
5058     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5059       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5060                                       InFlag);
5061       Chain = Lo.getValue(1);
5062       InFlag = Lo.getValue(2);
5063       VA = RVLocs[++i]; // skip ahead to next loc
5064       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5065                                       InFlag);
5066       Chain = Hi.getValue(1);
5067       InFlag = Hi.getValue(2);
5068       if (!Subtarget.isLittleEndian())
5069         std::swap (Lo, Hi);
5070       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5071     } else {
5072       Val = DAG.getCopyFromReg(Chain, dl,
5073                                VA.getLocReg(), VA.getLocVT(), InFlag);
5074       Chain = Val.getValue(1);
5075       InFlag = Val.getValue(2);
5076     }
5077 
5078     switch (VA.getLocInfo()) {
5079     default: llvm_unreachable("Unknown loc info!");
5080     case CCValAssign::Full: break;
5081     case CCValAssign::AExt:
5082       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5083       break;
5084     case CCValAssign::ZExt:
5085       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5086                         DAG.getValueType(VA.getValVT()));
5087       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5088       break;
5089     case CCValAssign::SExt:
5090       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5091                         DAG.getValueType(VA.getValVT()));
5092       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5093       break;
5094     }
5095 
5096     InVals.push_back(Val);
5097   }
5098 
5099   return Chain;
5100 }
5101 
5102 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5103                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5104   // PatchPoint calls are not indirect.
5105   if (isPatchPoint)
5106     return false;
5107 
5108   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5109     return false;
5110 
5111   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5112   // becuase the immediate function pointer points to a descriptor instead of
5113   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5114   // pointer immediate points to the global entry point, while the BLA would
5115   // need to jump to the local entry point (see rL211174).
5116   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5117       isBLACompatibleAddress(Callee, DAG))
5118     return false;
5119 
5120   return true;
5121 }
5122 
5123 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5124                               const Function &Caller,
5125                               const SDValue &Callee,
5126                               const PPCSubtarget &Subtarget,
5127                               const TargetMachine &TM) {
5128   if (CFlags.IsTailCall)
5129     return PPCISD::TC_RETURN;
5130 
5131   // This is a call through a function pointer.
5132   if (CFlags.IsIndirect) {
5133     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5134     // indirect calls. The save of the caller's TOC pointer to the stack will be
5135     // inserted into the DAG as part of call lowering. The restore of the TOC
5136     // pointer is modeled by using a pseudo instruction for the call opcode that
5137     // represents the 2 instruction sequence of an indirect branch and link,
5138     // immediately followed by a load of the TOC pointer from the the stack save
5139     // slot into gpr2.
5140     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5141       return PPCISD::BCTRL_LOAD_TOC;
5142 
5143     // An indirect call that does not need a TOC restore.
5144     return PPCISD::BCTRL;
5145   }
5146 
5147   // FIXME: At this moment indirect calls are treated ahead of the
5148   // PC Relative condition because binaries can still contain a possible
5149   // mix of functions that use a TOC and functions that do not use a TOC.
5150   // Once the PC Relative feature is complete this condition should be moved
5151   // up ahead of the indirect calls and should return a PPCISD::BCTRL for
5152   // that case.
5153   if (Subtarget.isUsingPCRelativeCalls()) {
5154     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5155     return PPCISD::CALL_NOTOC;
5156   }
5157 
5158   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5159   // immediately following the call instruction if the caller and callee may
5160   // have different TOC bases. At link time if the linker determines the calls
5161   // may not share a TOC base, the call is redirected to a trampoline inserted
5162   // by the linker. The trampoline will (among other things) save the callers
5163   // TOC pointer at an ABI designated offset in the linkage area and the linker
5164   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5165   // into gpr2.
5166   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5167       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5168                                                     : PPCISD::CALL_NOP;
5169 
5170   return PPCISD::CALL;
5171 }
5172 
5173 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5174                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5175   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5176     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5177       return SDValue(Dest, 0);
5178 
5179   // Returns true if the callee is local, and false otherwise.
5180   auto isLocalCallee = [&]() {
5181     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5182     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5183     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5184 
5185     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5186            !dyn_cast_or_null<GlobalIFunc>(GV);
5187   };
5188 
5189   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5190   // a static relocation model causes some versions of GNU LD (2.17.50, at
5191   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5192   // built with secure-PLT.
5193   bool UsePlt =
5194       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5195       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5196 
5197   // On AIX, direct function calls reference the symbol for the function's
5198   // entry point, which is named by prepending a "." before the function's
5199   // C-linkage name.
5200   const auto getAIXFuncEntryPointSymbolSDNode =
5201       [&](StringRef FuncName, bool IsDeclaration,
5202           const XCOFF::StorageClass &SC) {
5203         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5204 
5205         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5206             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5207 
5208         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5209           // On AIX, an undefined symbol needs to be associated with a
5210           // MCSectionXCOFF to get the correct storage mapping class.
5211           // In this case, XCOFF::XMC_PR.
5212           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5213               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5214               SectionKind::getMetadata());
5215           S->setRepresentedCsect(Sec);
5216         }
5217 
5218         MVT PtrVT =
5219             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5220         return DAG.getMCSymbol(S, PtrVT);
5221       };
5222 
5223   if (isFunctionGlobalAddress(Callee)) {
5224     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5225     const GlobalValue *GV = G->getGlobal();
5226 
5227     if (!Subtarget.isAIXABI())
5228       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5229                                         UsePlt ? PPCII::MO_PLT : 0);
5230 
5231     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5232     const GlobalObject *GO = cast<GlobalObject>(GV);
5233     const XCOFF::StorageClass SC =
5234         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5235     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5236                                             SC);
5237   }
5238 
5239   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5240     const char *SymName = S->getSymbol();
5241     if (!Subtarget.isAIXABI())
5242       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5243                                          UsePlt ? PPCII::MO_PLT : 0);
5244 
5245     // If there exists a user-declared function whose name is the same as the
5246     // ExternalSymbol's, then we pick up the user-declared version.
5247     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5248     if (const Function *F =
5249             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5250       const XCOFF::StorageClass SC =
5251           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5252       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5253                                               SC);
5254     }
5255 
5256     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5257   }
5258 
5259   // No transformation needed.
5260   assert(Callee.getNode() && "What no callee?");
5261   return Callee;
5262 }
5263 
5264 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5265   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5266          "Expected a CALLSEQ_STARTSDNode.");
5267 
5268   // The last operand is the chain, except when the node has glue. If the node
5269   // has glue, then the last operand is the glue, and the chain is the second
5270   // last operand.
5271   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5272   if (LastValue.getValueType() != MVT::Glue)
5273     return LastValue;
5274 
5275   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5276 }
5277 
5278 // Creates the node that moves a functions address into the count register
5279 // to prepare for an indirect call instruction.
5280 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5281                                 SDValue &Glue, SDValue &Chain,
5282                                 const SDLoc &dl) {
5283   SDValue MTCTROps[] = {Chain, Callee, Glue};
5284   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5285   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5286                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5287   // The glue is the second value produced.
5288   Glue = Chain.getValue(1);
5289 }
5290 
5291 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5292                                           SDValue &Glue, SDValue &Chain,
5293                                           SDValue CallSeqStart,
5294                                           const CallBase *CB, const SDLoc &dl,
5295                                           bool hasNest,
5296                                           const PPCSubtarget &Subtarget) {
5297   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5298   // entry point, but to the function descriptor (the function entry point
5299   // address is part of the function descriptor though).
5300   // The function descriptor is a three doubleword structure with the
5301   // following fields: function entry point, TOC base address and
5302   // environment pointer.
5303   // Thus for a call through a function pointer, the following actions need
5304   // to be performed:
5305   //   1. Save the TOC of the caller in the TOC save area of its stack
5306   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5307   //   2. Load the address of the function entry point from the function
5308   //      descriptor.
5309   //   3. Load the TOC of the callee from the function descriptor into r2.
5310   //   4. Load the environment pointer from the function descriptor into
5311   //      r11.
5312   //   5. Branch to the function entry point address.
5313   //   6. On return of the callee, the TOC of the caller needs to be
5314   //      restored (this is done in FinishCall()).
5315   //
5316   // The loads are scheduled at the beginning of the call sequence, and the
5317   // register copies are flagged together to ensure that no other
5318   // operations can be scheduled in between. E.g. without flagging the
5319   // copies together, a TOC access in the caller could be scheduled between
5320   // the assignment of the callee TOC and the branch to the callee, which leads
5321   // to incorrect code.
5322 
5323   // Start by loading the function address from the descriptor.
5324   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5325   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5326                       ? (MachineMemOperand::MODereferenceable |
5327                          MachineMemOperand::MOInvariant)
5328                       : MachineMemOperand::MONone;
5329 
5330   MachinePointerInfo MPI(CB ? CB->getCalledValue() : nullptr);
5331 
5332   // Registers used in building the DAG.
5333   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5334   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5335 
5336   // Offsets of descriptor members.
5337   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5338   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5339 
5340   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5341   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5342 
5343   // One load for the functions entry point address.
5344   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5345                                     Alignment, MMOFlags);
5346 
5347   // One for loading the TOC anchor for the module that contains the called
5348   // function.
5349   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5350   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5351   SDValue TOCPtr =
5352       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5353                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5354 
5355   // One for loading the environment pointer.
5356   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5357   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5358   SDValue LoadEnvPtr =
5359       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5360                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5361 
5362 
5363   // Then copy the newly loaded TOC anchor to the TOC pointer.
5364   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5365   Chain = TOCVal.getValue(0);
5366   Glue = TOCVal.getValue(1);
5367 
5368   // If the function call has an explicit 'nest' parameter, it takes the
5369   // place of the environment pointer.
5370   assert((!hasNest || !Subtarget.isAIXABI()) &&
5371          "Nest parameter is not supported on AIX.");
5372   if (!hasNest) {
5373     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5374     Chain = EnvVal.getValue(0);
5375     Glue = EnvVal.getValue(1);
5376   }
5377 
5378   // The rest of the indirect call sequence is the same as the non-descriptor
5379   // DAG.
5380   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5381 }
5382 
5383 static void
5384 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5385                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5386                   SelectionDAG &DAG,
5387                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5388                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5389                   const PPCSubtarget &Subtarget) {
5390   const bool IsPPC64 = Subtarget.isPPC64();
5391   // MVT for a general purpose register.
5392   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5393 
5394   // First operand is always the chain.
5395   Ops.push_back(Chain);
5396 
5397   // If it's a direct call pass the callee as the second operand.
5398   if (!CFlags.IsIndirect)
5399     Ops.push_back(Callee);
5400   else {
5401     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5402 
5403     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5404     // on the stack (this would have been done in `LowerCall_64SVR4` or
5405     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5406     // represents both the indirect branch and a load that restores the TOC
5407     // pointer from the linkage area. The operand for the TOC restore is an add
5408     // of the TOC save offset to the stack pointer. This must be the second
5409     // operand: after the chain input but before any other variadic arguments.
5410     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5411       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5412 
5413       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5414       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5415       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5416       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5417       Ops.push_back(AddTOC);
5418     }
5419 
5420     // Add the register used for the environment pointer.
5421     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5422       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5423                                     RegVT));
5424 
5425 
5426     // Add CTR register as callee so a bctr can be emitted later.
5427     if (CFlags.IsTailCall)
5428       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5429   }
5430 
5431   // If this is a tail call add stack pointer delta.
5432   if (CFlags.IsTailCall)
5433     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5434 
5435   // Add argument registers to the end of the list so that they are known live
5436   // into the call.
5437   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5438     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5439                                   RegsToPass[i].second.getValueType()));
5440 
5441   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5442   // no way to mark dependencies as implicit here.
5443   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5444   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5445        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5446     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5447 
5448   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5449   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5450     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5451 
5452   // Add a register mask operand representing the call-preserved registers.
5453   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5454   const uint32_t *Mask =
5455       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5456   assert(Mask && "Missing call preserved mask for calling convention");
5457   Ops.push_back(DAG.getRegisterMask(Mask));
5458 
5459   // If the glue is valid, it is the last operand.
5460   if (Glue.getNode())
5461     Ops.push_back(Glue);
5462 }
5463 
5464 SDValue PPCTargetLowering::FinishCall(
5465     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5466     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5467     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5468     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5469     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5470 
5471   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5472       Subtarget.isAIXABI())
5473     setUsesTOCBasePtr(DAG);
5474 
5475   unsigned CallOpc =
5476       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5477                     Subtarget, DAG.getTarget());
5478 
5479   if (!CFlags.IsIndirect)
5480     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5481   else if (Subtarget.usesFunctionDescriptors())
5482     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5483                                   dl, CFlags.HasNest, Subtarget);
5484   else
5485     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5486 
5487   // Build the operand list for the call instruction.
5488   SmallVector<SDValue, 8> Ops;
5489   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5490                     SPDiff, Subtarget);
5491 
5492   // Emit tail call.
5493   if (CFlags.IsTailCall) {
5494     assert(((Callee.getOpcode() == ISD::Register &&
5495              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5496             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5497             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5498             isa<ConstantSDNode>(Callee)) &&
5499            "Expecting a global address, external symbol, absolute value or "
5500            "register");
5501     assert(CallOpc == PPCISD::TC_RETURN &&
5502            "Unexpected call opcode for a tail call.");
5503     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5504     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5505   }
5506 
5507   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5508   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5509   Glue = Chain.getValue(1);
5510 
5511   // When performing tail call optimization the callee pops its arguments off
5512   // the stack. Account for this here so these bytes can be pushed back on in
5513   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5514   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5515                          getTargetMachine().Options.GuaranteedTailCallOpt)
5516                             ? NumBytes
5517                             : 0;
5518 
5519   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5520                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5521                              Glue, dl);
5522   Glue = Chain.getValue(1);
5523 
5524   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5525                          DAG, InVals);
5526 }
5527 
5528 SDValue
5529 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5530                              SmallVectorImpl<SDValue> &InVals) const {
5531   SelectionDAG &DAG                     = CLI.DAG;
5532   SDLoc &dl                             = CLI.DL;
5533   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5534   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5535   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5536   SDValue Chain                         = CLI.Chain;
5537   SDValue Callee                        = CLI.Callee;
5538   bool &isTailCall                      = CLI.IsTailCall;
5539   CallingConv::ID CallConv              = CLI.CallConv;
5540   bool isVarArg                         = CLI.IsVarArg;
5541   bool isPatchPoint                     = CLI.IsPatchPoint;
5542   const CallBase *CB                    = CLI.CB;
5543 
5544   if (isTailCall) {
5545     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5546       isTailCall = false;
5547     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5548       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5549           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5550     else
5551       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5552                                                      Ins, DAG);
5553     if (isTailCall) {
5554       ++NumTailCalls;
5555       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5556         ++NumSiblingCalls;
5557 
5558       assert(isa<GlobalAddressSDNode>(Callee) &&
5559              "Callee should be an llvm::Function object.");
5560       LLVM_DEBUG(
5561           const GlobalValue *GV =
5562               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5563           const unsigned Width =
5564               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5565           dbgs() << "TCO caller: "
5566                  << left_justify(DAG.getMachineFunction().getName(), Width)
5567                  << ", callee linkage: " << GV->getVisibility() << ", "
5568                  << GV->getLinkage() << "\n");
5569     }
5570   }
5571 
5572   if (!isTailCall && CB && CB->isMustTailCall())
5573     report_fatal_error("failed to perform tail call elimination on a call "
5574                        "site marked musttail");
5575 
5576   // When long calls (i.e. indirect calls) are always used, calls are always
5577   // made via function pointer. If we have a function name, first translate it
5578   // into a pointer.
5579   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5580       !isTailCall)
5581     Callee = LowerGlobalAddress(Callee, DAG);
5582 
5583   CallFlags CFlags(
5584       CallConv, isTailCall, isVarArg, isPatchPoint,
5585       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5586       // hasNest
5587       Subtarget.is64BitELFABI() &&
5588           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5589 
5590   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5591     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5592                             InVals, CB);
5593 
5594   if (Subtarget.isSVR4ABI())
5595     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5596                             InVals, CB);
5597 
5598   if (Subtarget.isAIXABI())
5599     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5600                          InVals, CB);
5601 
5602   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5603                           InVals, CB);
5604 }
5605 
5606 SDValue PPCTargetLowering::LowerCall_32SVR4(
5607     SDValue Chain, SDValue Callee, CallFlags CFlags,
5608     const SmallVectorImpl<ISD::OutputArg> &Outs,
5609     const SmallVectorImpl<SDValue> &OutVals,
5610     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5611     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5612     const CallBase *CB) const {
5613   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5614   // of the 32-bit SVR4 ABI stack frame layout.
5615 
5616   const CallingConv::ID CallConv = CFlags.CallConv;
5617   const bool IsVarArg = CFlags.IsVarArg;
5618   const bool IsTailCall = CFlags.IsTailCall;
5619 
5620   assert((CallConv == CallingConv::C ||
5621           CallConv == CallingConv::Cold ||
5622           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5623 
5624   unsigned PtrByteSize = 4;
5625 
5626   MachineFunction &MF = DAG.getMachineFunction();
5627 
5628   // Mark this function as potentially containing a function that contains a
5629   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5630   // and restoring the callers stack pointer in this functions epilog. This is
5631   // done because by tail calling the called function might overwrite the value
5632   // in this function's (MF) stack pointer stack slot 0(SP).
5633   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5634       CallConv == CallingConv::Fast)
5635     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5636 
5637   // Count how many bytes are to be pushed on the stack, including the linkage
5638   // area, parameter list area and the part of the local variable space which
5639   // contains copies of aggregates which are passed by value.
5640 
5641   // Assign locations to all of the outgoing arguments.
5642   SmallVector<CCValAssign, 16> ArgLocs;
5643   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5644 
5645   // Reserve space for the linkage area on the stack.
5646   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5647                        PtrByteSize);
5648   if (useSoftFloat())
5649     CCInfo.PreAnalyzeCallOperands(Outs);
5650 
5651   if (IsVarArg) {
5652     // Handle fixed and variable vector arguments differently.
5653     // Fixed vector arguments go into registers as long as registers are
5654     // available. Variable vector arguments always go into memory.
5655     unsigned NumArgs = Outs.size();
5656 
5657     for (unsigned i = 0; i != NumArgs; ++i) {
5658       MVT ArgVT = Outs[i].VT;
5659       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5660       bool Result;
5661 
5662       if (Outs[i].IsFixed) {
5663         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5664                                CCInfo);
5665       } else {
5666         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5667                                       ArgFlags, CCInfo);
5668       }
5669 
5670       if (Result) {
5671 #ifndef NDEBUG
5672         errs() << "Call operand #" << i << " has unhandled type "
5673              << EVT(ArgVT).getEVTString() << "\n";
5674 #endif
5675         llvm_unreachable(nullptr);
5676       }
5677     }
5678   } else {
5679     // All arguments are treated the same.
5680     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5681   }
5682   CCInfo.clearWasPPCF128();
5683 
5684   // Assign locations to all of the outgoing aggregate by value arguments.
5685   SmallVector<CCValAssign, 16> ByValArgLocs;
5686   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5687 
5688   // Reserve stack space for the allocations in CCInfo.
5689   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5690 
5691   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5692 
5693   // Size of the linkage area, parameter list area and the part of the local
5694   // space variable where copies of aggregates which are passed by value are
5695   // stored.
5696   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5697 
5698   // Calculate by how many bytes the stack has to be adjusted in case of tail
5699   // call optimization.
5700   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5701 
5702   // Adjust the stack pointer for the new arguments...
5703   // These operations are automatically eliminated by the prolog/epilog pass
5704   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5705   SDValue CallSeqStart = Chain;
5706 
5707   // Load the return address and frame pointer so it can be moved somewhere else
5708   // later.
5709   SDValue LROp, FPOp;
5710   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5711 
5712   // Set up a copy of the stack pointer for use loading and storing any
5713   // arguments that may not fit in the registers available for argument
5714   // passing.
5715   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5716 
5717   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5718   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5719   SmallVector<SDValue, 8> MemOpChains;
5720 
5721   bool seenFloatArg = false;
5722   // Walk the register/memloc assignments, inserting copies/loads.
5723   // i - Tracks the index into the list of registers allocated for the call
5724   // RealArgIdx - Tracks the index into the list of actual function arguments
5725   // j - Tracks the index into the list of byval arguments
5726   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5727        i != e;
5728        ++i, ++RealArgIdx) {
5729     CCValAssign &VA = ArgLocs[i];
5730     SDValue Arg = OutVals[RealArgIdx];
5731     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5732 
5733     if (Flags.isByVal()) {
5734       // Argument is an aggregate which is passed by value, thus we need to
5735       // create a copy of it in the local variable space of the current stack
5736       // frame (which is the stack frame of the caller) and pass the address of
5737       // this copy to the callee.
5738       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5739       CCValAssign &ByValVA = ByValArgLocs[j++];
5740       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5741 
5742       // Memory reserved in the local variable space of the callers stack frame.
5743       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5744 
5745       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5746       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5747                            StackPtr, PtrOff);
5748 
5749       // Create a copy of the argument in the local area of the current
5750       // stack frame.
5751       SDValue MemcpyCall =
5752         CreateCopyOfByValArgument(Arg, PtrOff,
5753                                   CallSeqStart.getNode()->getOperand(0),
5754                                   Flags, DAG, dl);
5755 
5756       // This must go outside the CALLSEQ_START..END.
5757       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5758                                                      SDLoc(MemcpyCall));
5759       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5760                              NewCallSeqStart.getNode());
5761       Chain = CallSeqStart = NewCallSeqStart;
5762 
5763       // Pass the address of the aggregate copy on the stack either in a
5764       // physical register or in the parameter list area of the current stack
5765       // frame to the callee.
5766       Arg = PtrOff;
5767     }
5768 
5769     // When useCRBits() is true, there can be i1 arguments.
5770     // It is because getRegisterType(MVT::i1) => MVT::i1,
5771     // and for other integer types getRegisterType() => MVT::i32.
5772     // Extend i1 and ensure callee will get i32.
5773     if (Arg.getValueType() == MVT::i1)
5774       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5775                         dl, MVT::i32, Arg);
5776 
5777     if (VA.isRegLoc()) {
5778       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5779       // Put argument in a physical register.
5780       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5781         bool IsLE = Subtarget.isLittleEndian();
5782         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5783                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5784         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5785         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5786                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5787         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5788                              SVal.getValue(0)));
5789       } else
5790         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5791     } else {
5792       // Put argument in the parameter list area of the current stack frame.
5793       assert(VA.isMemLoc());
5794       unsigned LocMemOffset = VA.getLocMemOffset();
5795 
5796       if (!IsTailCall) {
5797         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5798         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5799                              StackPtr, PtrOff);
5800 
5801         MemOpChains.push_back(
5802             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5803       } else {
5804         // Calculate and remember argument location.
5805         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5806                                  TailCallArguments);
5807       }
5808     }
5809   }
5810 
5811   if (!MemOpChains.empty())
5812     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5813 
5814   // Build a sequence of copy-to-reg nodes chained together with token chain
5815   // and flag operands which copy the outgoing args into the appropriate regs.
5816   SDValue InFlag;
5817   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5818     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5819                              RegsToPass[i].second, InFlag);
5820     InFlag = Chain.getValue(1);
5821   }
5822 
5823   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5824   // registers.
5825   if (IsVarArg) {
5826     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5827     SDValue Ops[] = { Chain, InFlag };
5828 
5829     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5830                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5831 
5832     InFlag = Chain.getValue(1);
5833   }
5834 
5835   if (IsTailCall)
5836     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5837                     TailCallArguments);
5838 
5839   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5840                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5841 }
5842 
5843 // Copy an argument into memory, being careful to do this outside the
5844 // call sequence for the call to which the argument belongs.
5845 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5846     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5847     SelectionDAG &DAG, const SDLoc &dl) const {
5848   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5849                         CallSeqStart.getNode()->getOperand(0),
5850                         Flags, DAG, dl);
5851   // The MEMCPY must go outside the CALLSEQ_START..END.
5852   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5853   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5854                                                  SDLoc(MemcpyCall));
5855   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5856                          NewCallSeqStart.getNode());
5857   return NewCallSeqStart;
5858 }
5859 
5860 SDValue PPCTargetLowering::LowerCall_64SVR4(
5861     SDValue Chain, SDValue Callee, CallFlags CFlags,
5862     const SmallVectorImpl<ISD::OutputArg> &Outs,
5863     const SmallVectorImpl<SDValue> &OutVals,
5864     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5865     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5866     const CallBase *CB) const {
5867   bool isELFv2ABI = Subtarget.isELFv2ABI();
5868   bool isLittleEndian = Subtarget.isLittleEndian();
5869   unsigned NumOps = Outs.size();
5870   bool IsSibCall = false;
5871   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5872 
5873   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5874   unsigned PtrByteSize = 8;
5875 
5876   MachineFunction &MF = DAG.getMachineFunction();
5877 
5878   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5879     IsSibCall = true;
5880 
5881   // Mark this function as potentially containing a function that contains a
5882   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5883   // and restoring the callers stack pointer in this functions epilog. This is
5884   // done because by tail calling the called function might overwrite the value
5885   // in this function's (MF) stack pointer stack slot 0(SP).
5886   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5887     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5888 
5889   assert(!(IsFastCall && CFlags.IsVarArg) &&
5890          "fastcc not supported on varargs functions");
5891 
5892   // Count how many bytes are to be pushed on the stack, including the linkage
5893   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5894   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5895   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5896   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5897   unsigned NumBytes = LinkageSize;
5898   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5899   unsigned &QFPR_idx = FPR_idx;
5900 
5901   static const MCPhysReg GPR[] = {
5902     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5903     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5904   };
5905   static const MCPhysReg VR[] = {
5906     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5907     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5908   };
5909 
5910   const unsigned NumGPRs = array_lengthof(GPR);
5911   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5912   const unsigned NumVRs  = array_lengthof(VR);
5913   const unsigned NumQFPRs = NumFPRs;
5914 
5915   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5916   // can be passed to the callee in registers.
5917   // For the fast calling convention, there is another check below.
5918   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5919   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5920   if (!HasParameterArea) {
5921     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5922     unsigned AvailableFPRs = NumFPRs;
5923     unsigned AvailableVRs = NumVRs;
5924     unsigned NumBytesTmp = NumBytes;
5925     for (unsigned i = 0; i != NumOps; ++i) {
5926       if (Outs[i].Flags.isNest()) continue;
5927       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5928                                 PtrByteSize, LinkageSize, ParamAreaSize,
5929                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5930                                 Subtarget.hasQPX()))
5931         HasParameterArea = true;
5932     }
5933   }
5934 
5935   // When using the fast calling convention, we don't provide backing for
5936   // arguments that will be in registers.
5937   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5938 
5939   // Avoid allocating parameter area for fastcc functions if all the arguments
5940   // can be passed in the registers.
5941   if (IsFastCall)
5942     HasParameterArea = false;
5943 
5944   // Add up all the space actually used.
5945   for (unsigned i = 0; i != NumOps; ++i) {
5946     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5947     EVT ArgVT = Outs[i].VT;
5948     EVT OrigVT = Outs[i].ArgVT;
5949 
5950     if (Flags.isNest())
5951       continue;
5952 
5953     if (IsFastCall) {
5954       if (Flags.isByVal()) {
5955         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5956         if (NumGPRsUsed > NumGPRs)
5957           HasParameterArea = true;
5958       } else {
5959         switch (ArgVT.getSimpleVT().SimpleTy) {
5960         default: llvm_unreachable("Unexpected ValueType for argument!");
5961         case MVT::i1:
5962         case MVT::i32:
5963         case MVT::i64:
5964           if (++NumGPRsUsed <= NumGPRs)
5965             continue;
5966           break;
5967         case MVT::v4i32:
5968         case MVT::v8i16:
5969         case MVT::v16i8:
5970         case MVT::v2f64:
5971         case MVT::v2i64:
5972         case MVT::v1i128:
5973         case MVT::f128:
5974           if (++NumVRsUsed <= NumVRs)
5975             continue;
5976           break;
5977         case MVT::v4f32:
5978           // When using QPX, this is handled like a FP register, otherwise, it
5979           // is an Altivec register.
5980           if (Subtarget.hasQPX()) {
5981             if (++NumFPRsUsed <= NumFPRs)
5982               continue;
5983           } else {
5984             if (++NumVRsUsed <= NumVRs)
5985               continue;
5986           }
5987           break;
5988         case MVT::f32:
5989         case MVT::f64:
5990         case MVT::v4f64: // QPX
5991         case MVT::v4i1:  // QPX
5992           if (++NumFPRsUsed <= NumFPRs)
5993             continue;
5994           break;
5995         }
5996         HasParameterArea = true;
5997       }
5998     }
5999 
6000     /* Respect alignment of argument on the stack.  */
6001     auto Alignement =
6002         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6003     NumBytes = alignTo(NumBytes, Alignement);
6004 
6005     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6006     if (Flags.isInConsecutiveRegsLast())
6007       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6008   }
6009 
6010   unsigned NumBytesActuallyUsed = NumBytes;
6011 
6012   // In the old ELFv1 ABI,
6013   // the prolog code of the callee may store up to 8 GPR argument registers to
6014   // the stack, allowing va_start to index over them in memory if its varargs.
6015   // Because we cannot tell if this is needed on the caller side, we have to
6016   // conservatively assume that it is needed.  As such, make sure we have at
6017   // least enough stack space for the caller to store the 8 GPRs.
6018   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6019   // really requires memory operands, e.g. a vararg function.
6020   if (HasParameterArea)
6021     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6022   else
6023     NumBytes = LinkageSize;
6024 
6025   // Tail call needs the stack to be aligned.
6026   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6027     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6028 
6029   int SPDiff = 0;
6030 
6031   // Calculate by how many bytes the stack has to be adjusted in case of tail
6032   // call optimization.
6033   if (!IsSibCall)
6034     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6035 
6036   // To protect arguments on the stack from being clobbered in a tail call,
6037   // force all the loads to happen before doing any other lowering.
6038   if (CFlags.IsTailCall)
6039     Chain = DAG.getStackArgumentTokenFactor(Chain);
6040 
6041   // Adjust the stack pointer for the new arguments...
6042   // These operations are automatically eliminated by the prolog/epilog pass
6043   if (!IsSibCall)
6044     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6045   SDValue CallSeqStart = Chain;
6046 
6047   // Load the return address and frame pointer so it can be move somewhere else
6048   // later.
6049   SDValue LROp, FPOp;
6050   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6051 
6052   // Set up a copy of the stack pointer for use loading and storing any
6053   // arguments that may not fit in the registers available for argument
6054   // passing.
6055   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6056 
6057   // Figure out which arguments are going to go in registers, and which in
6058   // memory.  Also, if this is a vararg function, floating point operations
6059   // must be stored to our stack, and loaded into integer regs as well, if
6060   // any integer regs are available for argument passing.
6061   unsigned ArgOffset = LinkageSize;
6062 
6063   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6064   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6065 
6066   SmallVector<SDValue, 8> MemOpChains;
6067   for (unsigned i = 0; i != NumOps; ++i) {
6068     SDValue Arg = OutVals[i];
6069     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6070     EVT ArgVT = Outs[i].VT;
6071     EVT OrigVT = Outs[i].ArgVT;
6072 
6073     // PtrOff will be used to store the current argument to the stack if a
6074     // register cannot be found for it.
6075     SDValue PtrOff;
6076 
6077     // We re-align the argument offset for each argument, except when using the
6078     // fast calling convention, when we need to make sure we do that only when
6079     // we'll actually use a stack slot.
6080     auto ComputePtrOff = [&]() {
6081       /* Respect alignment of argument on the stack.  */
6082       auto Alignment =
6083           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6084       ArgOffset = alignTo(ArgOffset, Alignment);
6085 
6086       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6087 
6088       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6089     };
6090 
6091     if (!IsFastCall) {
6092       ComputePtrOff();
6093 
6094       /* Compute GPR index associated with argument offset.  */
6095       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6096       GPR_idx = std::min(GPR_idx, NumGPRs);
6097     }
6098 
6099     // Promote integers to 64-bit values.
6100     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6101       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6102       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6103       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6104     }
6105 
6106     // FIXME memcpy is used way more than necessary.  Correctness first.
6107     // Note: "by value" is code for passing a structure by value, not
6108     // basic types.
6109     if (Flags.isByVal()) {
6110       // Note: Size includes alignment padding, so
6111       //   struct x { short a; char b; }
6112       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6113       // These are the proper values we need for right-justifying the
6114       // aggregate in a parameter register.
6115       unsigned Size = Flags.getByValSize();
6116 
6117       // An empty aggregate parameter takes up no storage and no
6118       // registers.
6119       if (Size == 0)
6120         continue;
6121 
6122       if (IsFastCall)
6123         ComputePtrOff();
6124 
6125       // All aggregates smaller than 8 bytes must be passed right-justified.
6126       if (Size==1 || Size==2 || Size==4) {
6127         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6128         if (GPR_idx != NumGPRs) {
6129           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6130                                         MachinePointerInfo(), VT);
6131           MemOpChains.push_back(Load.getValue(1));
6132           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6133 
6134           ArgOffset += PtrByteSize;
6135           continue;
6136         }
6137       }
6138 
6139       if (GPR_idx == NumGPRs && Size < 8) {
6140         SDValue AddPtr = PtrOff;
6141         if (!isLittleEndian) {
6142           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6143                                           PtrOff.getValueType());
6144           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6145         }
6146         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6147                                                           CallSeqStart,
6148                                                           Flags, DAG, dl);
6149         ArgOffset += PtrByteSize;
6150         continue;
6151       }
6152       // Copy entire object into memory.  There are cases where gcc-generated
6153       // code assumes it is there, even if it could be put entirely into
6154       // registers.  (This is not what the doc says.)
6155 
6156       // FIXME: The above statement is likely due to a misunderstanding of the
6157       // documents.  All arguments must be copied into the parameter area BY
6158       // THE CALLEE in the event that the callee takes the address of any
6159       // formal argument.  That has not yet been implemented.  However, it is
6160       // reasonable to use the stack area as a staging area for the register
6161       // load.
6162 
6163       // Skip this for small aggregates, as we will use the same slot for a
6164       // right-justified copy, below.
6165       if (Size >= 8)
6166         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6167                                                           CallSeqStart,
6168                                                           Flags, DAG, dl);
6169 
6170       // When a register is available, pass a small aggregate right-justified.
6171       if (Size < 8 && GPR_idx != NumGPRs) {
6172         // The easiest way to get this right-justified in a register
6173         // is to copy the structure into the rightmost portion of a
6174         // local variable slot, then load the whole slot into the
6175         // register.
6176         // FIXME: The memcpy seems to produce pretty awful code for
6177         // small aggregates, particularly for packed ones.
6178         // FIXME: It would be preferable to use the slot in the
6179         // parameter save area instead of a new local variable.
6180         SDValue AddPtr = PtrOff;
6181         if (!isLittleEndian) {
6182           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6183           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6184         }
6185         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6186                                                           CallSeqStart,
6187                                                           Flags, DAG, dl);
6188 
6189         // Load the slot into the register.
6190         SDValue Load =
6191             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6192         MemOpChains.push_back(Load.getValue(1));
6193         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6194 
6195         // Done with this argument.
6196         ArgOffset += PtrByteSize;
6197         continue;
6198       }
6199 
6200       // For aggregates larger than PtrByteSize, copy the pieces of the
6201       // object that fit into registers from the parameter save area.
6202       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6203         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6204         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6205         if (GPR_idx != NumGPRs) {
6206           SDValue Load =
6207               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6208           MemOpChains.push_back(Load.getValue(1));
6209           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6210           ArgOffset += PtrByteSize;
6211         } else {
6212           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6213           break;
6214         }
6215       }
6216       continue;
6217     }
6218 
6219     switch (Arg.getSimpleValueType().SimpleTy) {
6220     default: llvm_unreachable("Unexpected ValueType for argument!");
6221     case MVT::i1:
6222     case MVT::i32:
6223     case MVT::i64:
6224       if (Flags.isNest()) {
6225         // The 'nest' parameter, if any, is passed in R11.
6226         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6227         break;
6228       }
6229 
6230       // These can be scalar arguments or elements of an integer array type
6231       // passed directly.  Clang may use those instead of "byval" aggregate
6232       // types to avoid forcing arguments to memory unnecessarily.
6233       if (GPR_idx != NumGPRs) {
6234         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6235       } else {
6236         if (IsFastCall)
6237           ComputePtrOff();
6238 
6239         assert(HasParameterArea &&
6240                "Parameter area must exist to pass an argument in memory.");
6241         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6242                          true, CFlags.IsTailCall, false, MemOpChains,
6243                          TailCallArguments, dl);
6244         if (IsFastCall)
6245           ArgOffset += PtrByteSize;
6246       }
6247       if (!IsFastCall)
6248         ArgOffset += PtrByteSize;
6249       break;
6250     case MVT::f32:
6251     case MVT::f64: {
6252       // These can be scalar arguments or elements of a float array type
6253       // passed directly.  The latter are used to implement ELFv2 homogenous
6254       // float aggregates.
6255 
6256       // Named arguments go into FPRs first, and once they overflow, the
6257       // remaining arguments go into GPRs and then the parameter save area.
6258       // Unnamed arguments for vararg functions always go to GPRs and
6259       // then the parameter save area.  For now, put all arguments to vararg
6260       // routines always in both locations (FPR *and* GPR or stack slot).
6261       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6262       bool NeededLoad = false;
6263 
6264       // First load the argument into the next available FPR.
6265       if (FPR_idx != NumFPRs)
6266         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6267 
6268       // Next, load the argument into GPR or stack slot if needed.
6269       if (!NeedGPROrStack)
6270         ;
6271       else if (GPR_idx != NumGPRs && !IsFastCall) {
6272         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6273         // once we support fp <-> gpr moves.
6274 
6275         // In the non-vararg case, this can only ever happen in the
6276         // presence of f32 array types, since otherwise we never run
6277         // out of FPRs before running out of GPRs.
6278         SDValue ArgVal;
6279 
6280         // Double values are always passed in a single GPR.
6281         if (Arg.getValueType() != MVT::f32) {
6282           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6283 
6284         // Non-array float values are extended and passed in a GPR.
6285         } else if (!Flags.isInConsecutiveRegs()) {
6286           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6287           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6288 
6289         // If we have an array of floats, we collect every odd element
6290         // together with its predecessor into one GPR.
6291         } else if (ArgOffset % PtrByteSize != 0) {
6292           SDValue Lo, Hi;
6293           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6294           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6295           if (!isLittleEndian)
6296             std::swap(Lo, Hi);
6297           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6298 
6299         // The final element, if even, goes into the first half of a GPR.
6300         } else if (Flags.isInConsecutiveRegsLast()) {
6301           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6302           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6303           if (!isLittleEndian)
6304             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6305                                  DAG.getConstant(32, dl, MVT::i32));
6306 
6307         // Non-final even elements are skipped; they will be handled
6308         // together the with subsequent argument on the next go-around.
6309         } else
6310           ArgVal = SDValue();
6311 
6312         if (ArgVal.getNode())
6313           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6314       } else {
6315         if (IsFastCall)
6316           ComputePtrOff();
6317 
6318         // Single-precision floating-point values are mapped to the
6319         // second (rightmost) word of the stack doubleword.
6320         if (Arg.getValueType() == MVT::f32 &&
6321             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6322           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6323           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6324         }
6325 
6326         assert(HasParameterArea &&
6327                "Parameter area must exist to pass an argument in memory.");
6328         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6329                          true, CFlags.IsTailCall, false, MemOpChains,
6330                          TailCallArguments, dl);
6331 
6332         NeededLoad = true;
6333       }
6334       // When passing an array of floats, the array occupies consecutive
6335       // space in the argument area; only round up to the next doubleword
6336       // at the end of the array.  Otherwise, each float takes 8 bytes.
6337       if (!IsFastCall || NeededLoad) {
6338         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6339                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6340         if (Flags.isInConsecutiveRegsLast())
6341           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6342       }
6343       break;
6344     }
6345     case MVT::v4f32:
6346     case MVT::v4i32:
6347     case MVT::v8i16:
6348     case MVT::v16i8:
6349     case MVT::v2f64:
6350     case MVT::v2i64:
6351     case MVT::v1i128:
6352     case MVT::f128:
6353       if (!Subtarget.hasQPX()) {
6354       // These can be scalar arguments or elements of a vector array type
6355       // passed directly.  The latter are used to implement ELFv2 homogenous
6356       // vector aggregates.
6357 
6358       // For a varargs call, named arguments go into VRs or on the stack as
6359       // usual; unnamed arguments always go to the stack or the corresponding
6360       // GPRs when within range.  For now, we always put the value in both
6361       // locations (or even all three).
6362       if (CFlags.IsVarArg) {
6363         assert(HasParameterArea &&
6364                "Parameter area must exist if we have a varargs call.");
6365         // We could elide this store in the case where the object fits
6366         // entirely in R registers.  Maybe later.
6367         SDValue Store =
6368             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6369         MemOpChains.push_back(Store);
6370         if (VR_idx != NumVRs) {
6371           SDValue Load =
6372               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6373           MemOpChains.push_back(Load.getValue(1));
6374           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6375         }
6376         ArgOffset += 16;
6377         for (unsigned i=0; i<16; i+=PtrByteSize) {
6378           if (GPR_idx == NumGPRs)
6379             break;
6380           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6381                                    DAG.getConstant(i, dl, PtrVT));
6382           SDValue Load =
6383               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6384           MemOpChains.push_back(Load.getValue(1));
6385           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6386         }
6387         break;
6388       }
6389 
6390       // Non-varargs Altivec params go into VRs or on the stack.
6391       if (VR_idx != NumVRs) {
6392         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6393       } else {
6394         if (IsFastCall)
6395           ComputePtrOff();
6396 
6397         assert(HasParameterArea &&
6398                "Parameter area must exist to pass an argument in memory.");
6399         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6400                          true, CFlags.IsTailCall, true, MemOpChains,
6401                          TailCallArguments, dl);
6402         if (IsFastCall)
6403           ArgOffset += 16;
6404       }
6405 
6406       if (!IsFastCall)
6407         ArgOffset += 16;
6408       break;
6409       } // not QPX
6410 
6411       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6412              "Invalid QPX parameter type");
6413 
6414       LLVM_FALLTHROUGH;
6415     case MVT::v4f64:
6416     case MVT::v4i1: {
6417       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6418       if (CFlags.IsVarArg) {
6419         assert(HasParameterArea &&
6420                "Parameter area must exist if we have a varargs call.");
6421         // We could elide this store in the case where the object fits
6422         // entirely in R registers.  Maybe later.
6423         SDValue Store =
6424             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6425         MemOpChains.push_back(Store);
6426         if (QFPR_idx != NumQFPRs) {
6427           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6428                                      PtrOff, MachinePointerInfo());
6429           MemOpChains.push_back(Load.getValue(1));
6430           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6431         }
6432         ArgOffset += (IsF32 ? 16 : 32);
6433         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6434           if (GPR_idx == NumGPRs)
6435             break;
6436           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6437                                    DAG.getConstant(i, dl, PtrVT));
6438           SDValue Load =
6439               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6440           MemOpChains.push_back(Load.getValue(1));
6441           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6442         }
6443         break;
6444       }
6445 
6446       // Non-varargs QPX params go into registers or on the stack.
6447       if (QFPR_idx != NumQFPRs) {
6448         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6449       } else {
6450         if (IsFastCall)
6451           ComputePtrOff();
6452 
6453         assert(HasParameterArea &&
6454                "Parameter area must exist to pass an argument in memory.");
6455         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6456                          true, CFlags.IsTailCall, true, MemOpChains,
6457                          TailCallArguments, dl);
6458         if (IsFastCall)
6459           ArgOffset += (IsF32 ? 16 : 32);
6460       }
6461 
6462       if (!IsFastCall)
6463         ArgOffset += (IsF32 ? 16 : 32);
6464       break;
6465       }
6466     }
6467   }
6468 
6469   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6470          "mismatch in size of parameter area");
6471   (void)NumBytesActuallyUsed;
6472 
6473   if (!MemOpChains.empty())
6474     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6475 
6476   // Check if this is an indirect call (MTCTR/BCTRL).
6477   // See prepareDescriptorIndirectCall and buildCallOperands for more
6478   // information about calls through function pointers in the 64-bit SVR4 ABI.
6479   if (CFlags.IsIndirect) {
6480     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6481     // Load r2 into a virtual register and store it to the TOC save area.
6482     setUsesTOCBasePtr(DAG);
6483     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6484     // TOC save area offset.
6485     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6486     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6487     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6488     Chain = DAG.getStore(
6489         Val.getValue(1), dl, Val, AddPtr,
6490         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6491     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6492     // This does not mean the MTCTR instruction must use R12; it's easier
6493     // to model this as an extra parameter, so do that.
6494     if (isELFv2ABI && !CFlags.IsPatchPoint)
6495       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6496   }
6497 
6498   // Build a sequence of copy-to-reg nodes chained together with token chain
6499   // and flag operands which copy the outgoing args into the appropriate regs.
6500   SDValue InFlag;
6501   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6502     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6503                              RegsToPass[i].second, InFlag);
6504     InFlag = Chain.getValue(1);
6505   }
6506 
6507   if (CFlags.IsTailCall && !IsSibCall)
6508     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6509                     TailCallArguments);
6510 
6511   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6512                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6513 }
6514 
6515 SDValue PPCTargetLowering::LowerCall_Darwin(
6516     SDValue Chain, SDValue Callee, CallFlags CFlags,
6517     const SmallVectorImpl<ISD::OutputArg> &Outs,
6518     const SmallVectorImpl<SDValue> &OutVals,
6519     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6520     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6521     const CallBase *CB) const {
6522   unsigned NumOps = Outs.size();
6523 
6524   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6525   bool isPPC64 = PtrVT == MVT::i64;
6526   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6527 
6528   MachineFunction &MF = DAG.getMachineFunction();
6529 
6530   // Mark this function as potentially containing a function that contains a
6531   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6532   // and restoring the callers stack pointer in this functions epilog. This is
6533   // done because by tail calling the called function might overwrite the value
6534   // in this function's (MF) stack pointer stack slot 0(SP).
6535   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6536       CFlags.CallConv == CallingConv::Fast)
6537     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6538 
6539   // Count how many bytes are to be pushed on the stack, including the linkage
6540   // area, and parameter passing area.  We start with 24/48 bytes, which is
6541   // prereserved space for [SP][CR][LR][3 x unused].
6542   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6543   unsigned NumBytes = LinkageSize;
6544 
6545   // Add up all the space actually used.
6546   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6547   // they all go in registers, but we must reserve stack space for them for
6548   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6549   // assigned stack space in order, with padding so Altivec parameters are
6550   // 16-byte aligned.
6551   unsigned nAltivecParamsAtEnd = 0;
6552   for (unsigned i = 0; i != NumOps; ++i) {
6553     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6554     EVT ArgVT = Outs[i].VT;
6555     // Varargs Altivec parameters are padded to a 16 byte boundary.
6556     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6557         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6558         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6559       if (!CFlags.IsVarArg && !isPPC64) {
6560         // Non-varargs Altivec parameters go after all the non-Altivec
6561         // parameters; handle those later so we know how much padding we need.
6562         nAltivecParamsAtEnd++;
6563         continue;
6564       }
6565       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6566       NumBytes = ((NumBytes+15)/16)*16;
6567     }
6568     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6569   }
6570 
6571   // Allow for Altivec parameters at the end, if needed.
6572   if (nAltivecParamsAtEnd) {
6573     NumBytes = ((NumBytes+15)/16)*16;
6574     NumBytes += 16*nAltivecParamsAtEnd;
6575   }
6576 
6577   // The prolog code of the callee may store up to 8 GPR argument registers to
6578   // the stack, allowing va_start to index over them in memory if its varargs.
6579   // Because we cannot tell if this is needed on the caller side, we have to
6580   // conservatively assume that it is needed.  As such, make sure we have at
6581   // least enough stack space for the caller to store the 8 GPRs.
6582   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6583 
6584   // Tail call needs the stack to be aligned.
6585   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6586       CFlags.CallConv == CallingConv::Fast)
6587     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6588 
6589   // Calculate by how many bytes the stack has to be adjusted in case of tail
6590   // call optimization.
6591   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6592 
6593   // To protect arguments on the stack from being clobbered in a tail call,
6594   // force all the loads to happen before doing any other lowering.
6595   if (CFlags.IsTailCall)
6596     Chain = DAG.getStackArgumentTokenFactor(Chain);
6597 
6598   // Adjust the stack pointer for the new arguments...
6599   // These operations are automatically eliminated by the prolog/epilog pass
6600   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6601   SDValue CallSeqStart = Chain;
6602 
6603   // Load the return address and frame pointer so it can be move somewhere else
6604   // later.
6605   SDValue LROp, FPOp;
6606   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6607 
6608   // Set up a copy of the stack pointer for use loading and storing any
6609   // arguments that may not fit in the registers available for argument
6610   // passing.
6611   SDValue StackPtr;
6612   if (isPPC64)
6613     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6614   else
6615     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6616 
6617   // Figure out which arguments are going to go in registers, and which in
6618   // memory.  Also, if this is a vararg function, floating point operations
6619   // must be stored to our stack, and loaded into integer regs as well, if
6620   // any integer regs are available for argument passing.
6621   unsigned ArgOffset = LinkageSize;
6622   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6623 
6624   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6625     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6626     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6627   };
6628   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6629     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6630     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6631   };
6632   static const MCPhysReg VR[] = {
6633     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6634     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6635   };
6636   const unsigned NumGPRs = array_lengthof(GPR_32);
6637   const unsigned NumFPRs = 13;
6638   const unsigned NumVRs  = array_lengthof(VR);
6639 
6640   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6641 
6642   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6643   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6644 
6645   SmallVector<SDValue, 8> MemOpChains;
6646   for (unsigned i = 0; i != NumOps; ++i) {
6647     SDValue Arg = OutVals[i];
6648     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6649 
6650     // PtrOff will be used to store the current argument to the stack if a
6651     // register cannot be found for it.
6652     SDValue PtrOff;
6653 
6654     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6655 
6656     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6657 
6658     // On PPC64, promote integers to 64-bit values.
6659     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6660       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6661       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6662       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6663     }
6664 
6665     // FIXME memcpy is used way more than necessary.  Correctness first.
6666     // Note: "by value" is code for passing a structure by value, not
6667     // basic types.
6668     if (Flags.isByVal()) {
6669       unsigned Size = Flags.getByValSize();
6670       // Very small objects are passed right-justified.  Everything else is
6671       // passed left-justified.
6672       if (Size==1 || Size==2) {
6673         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6674         if (GPR_idx != NumGPRs) {
6675           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6676                                         MachinePointerInfo(), VT);
6677           MemOpChains.push_back(Load.getValue(1));
6678           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6679 
6680           ArgOffset += PtrByteSize;
6681         } else {
6682           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6683                                           PtrOff.getValueType());
6684           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6685           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6686                                                             CallSeqStart,
6687                                                             Flags, DAG, dl);
6688           ArgOffset += PtrByteSize;
6689         }
6690         continue;
6691       }
6692       // Copy entire object into memory.  There are cases where gcc-generated
6693       // code assumes it is there, even if it could be put entirely into
6694       // registers.  (This is not what the doc says.)
6695       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6696                                                         CallSeqStart,
6697                                                         Flags, DAG, dl);
6698 
6699       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6700       // copy the pieces of the object that fit into registers from the
6701       // parameter save area.
6702       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6703         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6704         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6705         if (GPR_idx != NumGPRs) {
6706           SDValue Load =
6707               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6708           MemOpChains.push_back(Load.getValue(1));
6709           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6710           ArgOffset += PtrByteSize;
6711         } else {
6712           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6713           break;
6714         }
6715       }
6716       continue;
6717     }
6718 
6719     switch (Arg.getSimpleValueType().SimpleTy) {
6720     default: llvm_unreachable("Unexpected ValueType for argument!");
6721     case MVT::i1:
6722     case MVT::i32:
6723     case MVT::i64:
6724       if (GPR_idx != NumGPRs) {
6725         if (Arg.getValueType() == MVT::i1)
6726           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6727 
6728         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6729       } else {
6730         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6731                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6732                          TailCallArguments, dl);
6733       }
6734       ArgOffset += PtrByteSize;
6735       break;
6736     case MVT::f32:
6737     case MVT::f64:
6738       if (FPR_idx != NumFPRs) {
6739         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6740 
6741         if (CFlags.IsVarArg) {
6742           SDValue Store =
6743               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6744           MemOpChains.push_back(Store);
6745 
6746           // Float varargs are always shadowed in available integer registers
6747           if (GPR_idx != NumGPRs) {
6748             SDValue Load =
6749                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6750             MemOpChains.push_back(Load.getValue(1));
6751             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6752           }
6753           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6754             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6755             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6756             SDValue Load =
6757                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6758             MemOpChains.push_back(Load.getValue(1));
6759             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6760           }
6761         } else {
6762           // If we have any FPRs remaining, we may also have GPRs remaining.
6763           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6764           // GPRs.
6765           if (GPR_idx != NumGPRs)
6766             ++GPR_idx;
6767           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6768               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6769             ++GPR_idx;
6770         }
6771       } else
6772         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6773                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6774                          TailCallArguments, dl);
6775       if (isPPC64)
6776         ArgOffset += 8;
6777       else
6778         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6779       break;
6780     case MVT::v4f32:
6781     case MVT::v4i32:
6782     case MVT::v8i16:
6783     case MVT::v16i8:
6784       if (CFlags.IsVarArg) {
6785         // These go aligned on the stack, or in the corresponding R registers
6786         // when within range.  The Darwin PPC ABI doc claims they also go in
6787         // V registers; in fact gcc does this only for arguments that are
6788         // prototyped, not for those that match the ...  We do it for all
6789         // arguments, seems to work.
6790         while (ArgOffset % 16 !=0) {
6791           ArgOffset += PtrByteSize;
6792           if (GPR_idx != NumGPRs)
6793             GPR_idx++;
6794         }
6795         // We could elide this store in the case where the object fits
6796         // entirely in R registers.  Maybe later.
6797         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6798                              DAG.getConstant(ArgOffset, dl, PtrVT));
6799         SDValue Store =
6800             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6801         MemOpChains.push_back(Store);
6802         if (VR_idx != NumVRs) {
6803           SDValue Load =
6804               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6805           MemOpChains.push_back(Load.getValue(1));
6806           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6807         }
6808         ArgOffset += 16;
6809         for (unsigned i=0; i<16; i+=PtrByteSize) {
6810           if (GPR_idx == NumGPRs)
6811             break;
6812           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6813                                    DAG.getConstant(i, dl, PtrVT));
6814           SDValue Load =
6815               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6816           MemOpChains.push_back(Load.getValue(1));
6817           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6818         }
6819         break;
6820       }
6821 
6822       // Non-varargs Altivec params generally go in registers, but have
6823       // stack space allocated at the end.
6824       if (VR_idx != NumVRs) {
6825         // Doesn't have GPR space allocated.
6826         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6827       } else if (nAltivecParamsAtEnd==0) {
6828         // We are emitting Altivec params in order.
6829         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6830                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6831                          TailCallArguments, dl);
6832         ArgOffset += 16;
6833       }
6834       break;
6835     }
6836   }
6837   // If all Altivec parameters fit in registers, as they usually do,
6838   // they get stack space following the non-Altivec parameters.  We
6839   // don't track this here because nobody below needs it.
6840   // If there are more Altivec parameters than fit in registers emit
6841   // the stores here.
6842   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6843     unsigned j = 0;
6844     // Offset is aligned; skip 1st 12 params which go in V registers.
6845     ArgOffset = ((ArgOffset+15)/16)*16;
6846     ArgOffset += 12*16;
6847     for (unsigned i = 0; i != NumOps; ++i) {
6848       SDValue Arg = OutVals[i];
6849       EVT ArgType = Outs[i].VT;
6850       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6851           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6852         if (++j > NumVRs) {
6853           SDValue PtrOff;
6854           // We are emitting Altivec params in order.
6855           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6856                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6857                            TailCallArguments, dl);
6858           ArgOffset += 16;
6859         }
6860       }
6861     }
6862   }
6863 
6864   if (!MemOpChains.empty())
6865     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6866 
6867   // On Darwin, R12 must contain the address of an indirect callee.  This does
6868   // not mean the MTCTR instruction must use R12; it's easier to model this as
6869   // an extra parameter, so do that.
6870   if (CFlags.IsIndirect) {
6871     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6872     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6873                                                    PPC::R12), Callee));
6874   }
6875 
6876   // Build a sequence of copy-to-reg nodes chained together with token chain
6877   // and flag operands which copy the outgoing args into the appropriate regs.
6878   SDValue InFlag;
6879   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6880     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6881                              RegsToPass[i].second, InFlag);
6882     InFlag = Chain.getValue(1);
6883   }
6884 
6885   if (CFlags.IsTailCall)
6886     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6887                     TailCallArguments);
6888 
6889   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6890                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6891 }
6892 
6893 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6894                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6895                    CCState &State) {
6896 
6897   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6898       State.getMachineFunction().getSubtarget());
6899   const bool IsPPC64 = Subtarget.isPPC64();
6900   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6901   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6902 
6903   assert((!ValVT.isInteger() ||
6904           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6905          "Integer argument exceeds register size: should have been legalized");
6906 
6907   if (ValVT == MVT::f128)
6908     report_fatal_error("f128 is unimplemented on AIX.");
6909 
6910   if (ArgFlags.isNest())
6911     report_fatal_error("Nest arguments are unimplemented.");
6912 
6913   if (ValVT.isVector() || LocVT.isVector())
6914     report_fatal_error("Vector arguments are unimplemented on AIX.");
6915 
6916   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6917                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6918                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6919   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6920                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6921                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6922 
6923   if (ArgFlags.isByVal()) {
6924     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6925       report_fatal_error("Pass-by-value arguments with alignment greater than "
6926                          "register width are not supported.");
6927 
6928     const unsigned ByValSize = ArgFlags.getByValSize();
6929 
6930     // An empty aggregate parameter takes up no storage and no registers,
6931     // but needs a MemLoc for a stack slot for the formal arguments side.
6932     if (ByValSize == 0) {
6933       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6934                                        State.getNextStackOffset(), RegVT,
6935                                        LocInfo));
6936       return false;
6937     }
6938 
6939     State.AllocateStack(alignTo(ByValSize, PtrByteSize), PtrByteSize);
6940 
6941     for (unsigned I = 0, E = ByValSize; I < E; I += PtrByteSize) {
6942       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6943         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6944       else
6945         report_fatal_error(
6946             "Pass-by-value arguments are only supported in registers.");
6947     }
6948     return false;
6949   }
6950 
6951   // Arguments always reserve parameter save area.
6952   switch (ValVT.SimpleTy) {
6953   default:
6954     report_fatal_error("Unhandled value type for argument.");
6955   case MVT::i64:
6956     // i64 arguments should have been split to i32 for PPC32.
6957     assert(IsPPC64 && "PPC32 should have split i64 values.");
6958     LLVM_FALLTHROUGH;
6959   case MVT::i1:
6960   case MVT::i32: {
6961     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
6962     // AIX integer arguments are always passed in register width.
6963     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6964       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6965                                   : CCValAssign::LocInfo::ZExt;
6966     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6967       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6968     else
6969       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6970 
6971     return false;
6972   }
6973   case MVT::f32:
6974   case MVT::f64: {
6975     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6976     const unsigned StoreSize = LocVT.getStoreSize();
6977     // Floats are always 4-byte aligned in the PSA on AIX.
6978     // This includes f64 in 64-bit mode for ABI compatibility.
6979     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6980     unsigned FReg = State.AllocateReg(FPR);
6981     if (FReg)
6982       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6983 
6984     // Reserve and initialize GPRs or initialize the PSA as required.
6985     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6986       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6987         assert(FReg && "An FPR should be available when a GPR is reserved.");
6988         if (State.isVarArg()) {
6989           // Successfully reserved GPRs are only initialized for vararg calls.
6990           // Custom handling is required for:
6991           //   f64 in PPC32 needs to be split into 2 GPRs.
6992           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6993           State.addLoc(
6994               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6995         }
6996       } else {
6997         // If there are insufficient GPRs, the PSA needs to be initialized.
6998         // Initialization occurs even if an FPR was initialized for
6999         // compatibility with the AIX XL compiler. The full memory for the
7000         // argument will be initialized even if a prior word is saved in GPR.
7001         // A custom memLoc is used when the argument also passes in FPR so
7002         // that the callee handling can skip over it easily.
7003         State.addLoc(
7004             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7005                                              LocInfo)
7006                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7007         break;
7008       }
7009     }
7010 
7011     return false;
7012   }
7013   }
7014   return true;
7015 }
7016 
7017 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7018                                                     bool IsPPC64) {
7019   assert((IsPPC64 || SVT != MVT::i64) &&
7020          "i64 should have been split for 32-bit codegen.");
7021 
7022   switch (SVT) {
7023   default:
7024     report_fatal_error("Unexpected value type for formal argument");
7025   case MVT::i1:
7026   case MVT::i32:
7027   case MVT::i64:
7028     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7029   case MVT::f32:
7030     return &PPC::F4RCRegClass;
7031   case MVT::f64:
7032     return &PPC::F8RCRegClass;
7033   }
7034 }
7035 
7036 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7037                                         SelectionDAG &DAG, SDValue ArgValue,
7038                                         MVT LocVT, const SDLoc &dl) {
7039   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7040   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7041 
7042   if (Flags.isSExt())
7043     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7044                            DAG.getValueType(ValVT));
7045   else if (Flags.isZExt())
7046     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7047                            DAG.getValueType(ValVT));
7048 
7049   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7050 }
7051 
7052 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7053   const unsigned LASize = FL->getLinkageSize();
7054 
7055   if (PPC::GPRCRegClass.contains(Reg)) {
7056     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7057            "Reg must be a valid argument register!");
7058     return LASize + 4 * (Reg - PPC::R3);
7059   }
7060 
7061   if (PPC::G8RCRegClass.contains(Reg)) {
7062     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7063            "Reg must be a valid argument register!");
7064     return LASize + 8 * (Reg - PPC::X3);
7065   }
7066 
7067   llvm_unreachable("Only general purpose registers expected.");
7068 }
7069 
7070 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7071     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7072     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7073     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7074 
7075   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7076           CallConv == CallingConv::Fast) &&
7077          "Unexpected calling convention!");
7078 
7079   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7080     report_fatal_error("Tail call support is unimplemented on AIX.");
7081 
7082   if (useSoftFloat())
7083     report_fatal_error("Soft float support is unimplemented on AIX.");
7084 
7085   const PPCSubtarget &Subtarget =
7086       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7087   if (Subtarget.hasQPX())
7088     report_fatal_error("QPX support is not supported on AIX.");
7089 
7090   const bool IsPPC64 = Subtarget.isPPC64();
7091   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7092 
7093   // Assign locations to all of the incoming arguments.
7094   SmallVector<CCValAssign, 16> ArgLocs;
7095   MachineFunction &MF = DAG.getMachineFunction();
7096   MachineFrameInfo &MFI = MF.getFrameInfo();
7097   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7098 
7099   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7100   // Reserve space for the linkage area on the stack.
7101   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7102   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7103   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7104 
7105   SmallVector<SDValue, 8> MemOps;
7106 
7107   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7108     CCValAssign &VA = ArgLocs[I++];
7109     MVT LocVT = VA.getLocVT();
7110     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7111 
7112     // For compatibility with the AIX XL compiler, the float args in the
7113     // parameter save area are initialized even if the argument is available
7114     // in register.  The caller is required to initialize both the register
7115     // and memory, however, the callee can choose to expect it in either.
7116     // The memloc is dismissed here because the argument is retrieved from
7117     // the register.
7118     if (VA.isMemLoc() && VA.needsCustom())
7119       continue;
7120 
7121     if (Flags.isByVal() && VA.isMemLoc()) {
7122       if (Flags.getByValSize() != 0)
7123         report_fatal_error(
7124             "ByVal arguments passed on stack not implemented yet");
7125 
7126       const int FI = MF.getFrameInfo().CreateFixedObject(
7127           PtrByteSize, VA.getLocMemOffset(), /* IsImmutable */ false,
7128           /* IsAliased */ true);
7129       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7130       InVals.push_back(FIN);
7131 
7132       continue;
7133     }
7134 
7135     if (Flags.isByVal()) {
7136       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7137 
7138       const MCPhysReg ArgReg = VA.getLocReg();
7139       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7140 
7141       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7142         report_fatal_error("Over aligned byvals not supported yet.");
7143 
7144       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7145       const int FI = MF.getFrameInfo().CreateFixedObject(
7146           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7147           /* IsAliased */ true);
7148       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7149       InVals.push_back(FIN);
7150 
7151       // Add live ins for all the RegLocs for the same ByVal.
7152       const TargetRegisterClass *RegClass =
7153           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7154 
7155       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7156                                                unsigned Offset) {
7157         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7158         // Since the callers side has left justified the aggregate in the
7159         // register, we can simply store the entire register into the stack
7160         // slot.
7161         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7162         // The store to the fixedstack object is needed becuase accessing a
7163         // field of the ByVal will use a gep and load. Ideally we will optimize
7164         // to extracting the value from the register directly, and elide the
7165         // stores when the arguments address is not taken, but that will need to
7166         // be future work.
7167         SDValue Store =
7168             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7169                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7170                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7171 
7172         MemOps.push_back(Store);
7173       };
7174 
7175       unsigned Offset = 0;
7176       HandleRegLoc(VA.getLocReg(), Offset);
7177       Offset += PtrByteSize;
7178       for (; Offset != StackSize; Offset += PtrByteSize) {
7179         assert(I != End &&
7180                "Expecting enough RegLocs to copy entire ByVal arg.");
7181 
7182         if (!ArgLocs[I].isRegLoc())
7183           report_fatal_error("Passing ByVals split between registers and stack "
7184                              "not yet implemented.");
7185 
7186         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7187                "Expecting more RegLocs for ByVal argument.");
7188 
7189         const CCValAssign RL = ArgLocs[I++];
7190         HandleRegLoc(RL.getLocReg(), Offset);
7191       }
7192       continue;
7193     }
7194 
7195     EVT ValVT = VA.getValVT();
7196     if (VA.isRegLoc() && !VA.needsCustom()) {
7197       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7198       unsigned VReg =
7199           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7200       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7201       if (ValVT.isScalarInteger() &&
7202           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7203         ArgValue =
7204             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7205       }
7206       InVals.push_back(ArgValue);
7207       continue;
7208     }
7209     if (VA.isMemLoc()) {
7210       const unsigned LocSize = LocVT.getStoreSize();
7211       const unsigned ValSize = ValVT.getStoreSize();
7212       assert((ValSize <= LocSize) &&
7213              "Object size is larger than size of MemLoc");
7214       int CurArgOffset = VA.getLocMemOffset();
7215       // Objects are right-justified because AIX is big-endian.
7216       if (LocSize > ValSize)
7217         CurArgOffset += LocSize - ValSize;
7218       // Potential tail calls could cause overwriting of argument stack slots.
7219       const bool IsImmutable =
7220           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7221             (CallConv == CallingConv::Fast));
7222       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7223       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7224       SDValue ArgValue =
7225           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7226       InVals.push_back(ArgValue);
7227       continue;
7228     }
7229   }
7230 
7231   // On AIX a minimum of 8 words is saved to the parameter save area.
7232   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7233   // Area that is at least reserved in the caller of this function.
7234   unsigned CallerReservedArea =
7235       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7236 
7237   // Set the size that is at least reserved in caller of this function. Tail
7238   // call optimized function's reserved stack space needs to be aligned so
7239   // that taking the difference between two stack areas will result in an
7240   // aligned stack.
7241   CallerReservedArea =
7242       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7243   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7244   FuncInfo->setMinReservedArea(CallerReservedArea);
7245 
7246   if (isVarArg) {
7247     FuncInfo->setVarArgsFrameIndex(
7248         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7249     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7250 
7251     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7252                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7253 
7254     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7255                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7256     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7257 
7258     // The fixed integer arguments of a variadic function are stored to the
7259     // VarArgsFrameIndex on the stack so that they may be loaded by
7260     // dereferencing the result of va_next.
7261     for (unsigned GPRIndex =
7262              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7263          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7264 
7265       const unsigned VReg =
7266           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7267                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7268 
7269       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7270       SDValue Store =
7271           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7272       MemOps.push_back(Store);
7273       // Increment the address for the next argument to store.
7274       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7275       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7276     }
7277   }
7278 
7279   if (!MemOps.empty())
7280     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7281 
7282   return Chain;
7283 }
7284 
7285 SDValue PPCTargetLowering::LowerCall_AIX(
7286     SDValue Chain, SDValue Callee, CallFlags CFlags,
7287     const SmallVectorImpl<ISD::OutputArg> &Outs,
7288     const SmallVectorImpl<SDValue> &OutVals,
7289     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7290     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7291     const CallBase *CB) const {
7292 
7293   assert((CFlags.CallConv == CallingConv::C ||
7294           CFlags.CallConv == CallingConv::Cold ||
7295           CFlags.CallConv == CallingConv::Fast) &&
7296          "Unexpected calling convention!");
7297 
7298   if (CFlags.IsPatchPoint)
7299     report_fatal_error("This call type is unimplemented on AIX.");
7300 
7301   const PPCSubtarget& Subtarget =
7302       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7303   if (Subtarget.hasQPX())
7304     report_fatal_error("QPX is not supported on AIX.");
7305   if (Subtarget.hasAltivec())
7306     report_fatal_error("Altivec support is unimplemented on AIX.");
7307 
7308   MachineFunction &MF = DAG.getMachineFunction();
7309   SmallVector<CCValAssign, 16> ArgLocs;
7310   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7311                  *DAG.getContext());
7312 
7313   // Reserve space for the linkage save area (LSA) on the stack.
7314   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7315   //   [SP][CR][LR][2 x reserved][TOC].
7316   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7317   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7318   const bool IsPPC64 = Subtarget.isPPC64();
7319   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7320   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7321   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7322   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7323 
7324   // The prolog code of the callee may store up to 8 GPR argument registers to
7325   // the stack, allowing va_start to index over them in memory if the callee
7326   // is variadic.
7327   // Because we cannot tell if this is needed on the caller side, we have to
7328   // conservatively assume that it is needed.  As such, make sure we have at
7329   // least enough stack space for the caller to store the 8 GPRs.
7330   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7331   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7332                                      CCInfo.getNextStackOffset());
7333 
7334   // Adjust the stack pointer for the new arguments...
7335   // These operations are automatically eliminated by the prolog/epilog pass.
7336   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7337   SDValue CallSeqStart = Chain;
7338 
7339   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7340   SmallVector<SDValue, 8> MemOpChains;
7341 
7342   // Set up a copy of the stack pointer for loading and storing any
7343   // arguments that may not fit in the registers available for argument
7344   // passing.
7345   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7346                                    : DAG.getRegister(PPC::R1, MVT::i32);
7347 
7348   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7349     const unsigned ValNo = ArgLocs[I].getValNo();
7350     SDValue Arg = OutVals[ValNo];
7351     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7352 
7353     if (Flags.isByVal()) {
7354       const unsigned ByValSize = Flags.getByValSize();
7355 
7356       // Nothing to do for zero-sized ByVals on the caller side.
7357       if (!ByValSize) {
7358         ++I;
7359         continue;
7360       }
7361 
7362       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7363         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7364                               (LoadOffset != 0)
7365                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7366                                   : Arg,
7367                               MachinePointerInfo(), VT);
7368       };
7369 
7370       unsigned LoadOffset = 0;
7371 
7372       // Initialize registers, which are fully occupied by the by-val argument.
7373       while (I != E && LoadOffset + PtrByteSize <= ByValSize) {
7374         SDValue Load = GetLoad(PtrVT, LoadOffset);
7375         MemOpChains.push_back(Load.getValue(1));
7376         LoadOffset += PtrByteSize;
7377         const CCValAssign &ByValVA = ArgLocs[I++];
7378         assert(ByValVA.isRegLoc() && ByValVA.getValNo() == ValNo &&
7379                "Unexpected location for pass-by-value argument.");
7380         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7381       }
7382 
7383       if (LoadOffset == ByValSize)
7384         continue;
7385 
7386       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7387       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7388              "Unexpected register residue for by-value argument.");
7389 
7390       // Initialize the final register residue.
7391       // Any residue that occupies the final by-val arg register must be
7392       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7393       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7394       // 2 and 1 byte loads.
7395       SDValue ResidueVal;
7396       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7397         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7398         const MVT VT =
7399             N == 1 ? MVT::i8
7400                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7401         SDValue Load = GetLoad(VT, LoadOffset);
7402         MemOpChains.push_back(Load.getValue(1));
7403         LoadOffset += N;
7404         Bytes += N;
7405 
7406         // By-val arguments are passed left-justfied in register.
7407         // Every load here needs to be shifted, otherwise a full register load
7408         // should have been used.
7409         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7410                "Unexpected load emitted during handling of pass-by-value "
7411                "argument.");
7412         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7413         EVT ShiftAmountTy =
7414             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7415         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7416         SDValue ShiftedLoad =
7417             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7418         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7419                                               ShiftedLoad)
7420                                 : ShiftedLoad;
7421       }
7422 
7423       const CCValAssign &ByValVA = ArgLocs[I++];
7424       assert(ByValVA.isRegLoc() && ByValVA.getValNo() == ValNo &&
7425              "Additional register location expected for by-value argument.");
7426       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7427       continue;
7428     }
7429 
7430     CCValAssign &VA = ArgLocs[I++];
7431     const MVT LocVT = VA.getLocVT();
7432     const MVT ValVT = VA.getValVT();
7433 
7434     switch (VA.getLocInfo()) {
7435     default:
7436       report_fatal_error("Unexpected argument extension type.");
7437     case CCValAssign::Full:
7438       break;
7439     case CCValAssign::ZExt:
7440       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7441       break;
7442     case CCValAssign::SExt:
7443       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7444       break;
7445     }
7446 
7447     if (VA.isRegLoc() && !VA.needsCustom()) {
7448       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7449       continue;
7450     }
7451 
7452     if (VA.isMemLoc()) {
7453       SDValue PtrOff =
7454           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7455       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7456       MemOpChains.push_back(
7457           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7458 
7459       continue;
7460     }
7461 
7462     // Custom handling is used for GPR initializations for vararg float
7463     // arguments.
7464     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7465            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7466            "Unexpected register handling for calling convention.");
7467 
7468     SDValue ArgAsInt =
7469         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7470 
7471     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7472       // f32 in 32-bit GPR
7473       // f64 in 64-bit GPR
7474       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7475     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7476       // f32 in 64-bit GPR.
7477       RegsToPass.push_back(std::make_pair(
7478           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7479     else {
7480       // f64 in two 32-bit GPRs
7481       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7482       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7483              "Unexpected custom register for argument!");
7484       CCValAssign &GPR1 = VA;
7485       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7486                                      DAG.getConstant(32, dl, MVT::i8));
7487       RegsToPass.push_back(std::make_pair(
7488           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7489 
7490       if (I != E) {
7491         // If only 1 GPR was available, there will only be one custom GPR and
7492         // the argument will also pass in memory.
7493         CCValAssign &PeekArg = ArgLocs[I];
7494         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7495           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7496           CCValAssign &GPR2 = ArgLocs[I++];
7497           RegsToPass.push_back(std::make_pair(
7498               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7499         }
7500       }
7501     }
7502   }
7503 
7504   if (!MemOpChains.empty())
7505     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7506 
7507   // For indirect calls, we need to save the TOC base to the stack for
7508   // restoration after the call.
7509   if (CFlags.IsIndirect) {
7510     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7511     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7512     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7513     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7514     const unsigned TOCSaveOffset =
7515         Subtarget.getFrameLowering()->getTOCSaveOffset();
7516 
7517     setUsesTOCBasePtr(DAG);
7518     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7519     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7520     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7521     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7522     Chain = DAG.getStore(
7523         Val.getValue(1), dl, Val, AddPtr,
7524         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7525   }
7526 
7527   // Build a sequence of copy-to-reg nodes chained together with token chain
7528   // and flag operands which copy the outgoing args into the appropriate regs.
7529   SDValue InFlag;
7530   for (auto Reg : RegsToPass) {
7531     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7532     InFlag = Chain.getValue(1);
7533   }
7534 
7535   const int SPDiff = 0;
7536   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7537                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7538 }
7539 
7540 bool
7541 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7542                                   MachineFunction &MF, bool isVarArg,
7543                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7544                                   LLVMContext &Context) const {
7545   SmallVector<CCValAssign, 16> RVLocs;
7546   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7547   return CCInfo.CheckReturn(
7548       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7549                 ? RetCC_PPC_Cold
7550                 : RetCC_PPC);
7551 }
7552 
7553 SDValue
7554 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7555                                bool isVarArg,
7556                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7557                                const SmallVectorImpl<SDValue> &OutVals,
7558                                const SDLoc &dl, SelectionDAG &DAG) const {
7559   SmallVector<CCValAssign, 16> RVLocs;
7560   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7561                  *DAG.getContext());
7562   CCInfo.AnalyzeReturn(Outs,
7563                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7564                            ? RetCC_PPC_Cold
7565                            : RetCC_PPC);
7566 
7567   SDValue Flag;
7568   SmallVector<SDValue, 4> RetOps(1, Chain);
7569 
7570   // Copy the result values into the output registers.
7571   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7572     CCValAssign &VA = RVLocs[i];
7573     assert(VA.isRegLoc() && "Can only return in registers!");
7574 
7575     SDValue Arg = OutVals[RealResIdx];
7576 
7577     switch (VA.getLocInfo()) {
7578     default: llvm_unreachable("Unknown loc info!");
7579     case CCValAssign::Full: break;
7580     case CCValAssign::AExt:
7581       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7582       break;
7583     case CCValAssign::ZExt:
7584       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7585       break;
7586     case CCValAssign::SExt:
7587       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7588       break;
7589     }
7590     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7591       bool isLittleEndian = Subtarget.isLittleEndian();
7592       // Legalize ret f64 -> ret 2 x i32.
7593       SDValue SVal =
7594           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7595                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7596       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7597       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7598       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7599                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7600       Flag = Chain.getValue(1);
7601       VA = RVLocs[++i]; // skip ahead to next loc
7602       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7603     } else
7604       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7605     Flag = Chain.getValue(1);
7606     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7607   }
7608 
7609   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7610   const MCPhysReg *I =
7611     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7612   if (I) {
7613     for (; *I; ++I) {
7614 
7615       if (PPC::G8RCRegClass.contains(*I))
7616         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7617       else if (PPC::F8RCRegClass.contains(*I))
7618         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7619       else if (PPC::CRRCRegClass.contains(*I))
7620         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7621       else if (PPC::VRRCRegClass.contains(*I))
7622         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7623       else
7624         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7625     }
7626   }
7627 
7628   RetOps[0] = Chain;  // Update chain.
7629 
7630   // Add the flag if we have it.
7631   if (Flag.getNode())
7632     RetOps.push_back(Flag);
7633 
7634   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7635 }
7636 
7637 SDValue
7638 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7639                                                 SelectionDAG &DAG) const {
7640   SDLoc dl(Op);
7641 
7642   // Get the correct type for integers.
7643   EVT IntVT = Op.getValueType();
7644 
7645   // Get the inputs.
7646   SDValue Chain = Op.getOperand(0);
7647   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7648   // Build a DYNAREAOFFSET node.
7649   SDValue Ops[2] = {Chain, FPSIdx};
7650   SDVTList VTs = DAG.getVTList(IntVT);
7651   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7652 }
7653 
7654 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7655                                              SelectionDAG &DAG) const {
7656   // When we pop the dynamic allocation we need to restore the SP link.
7657   SDLoc dl(Op);
7658 
7659   // Get the correct type for pointers.
7660   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7661 
7662   // Construct the stack pointer operand.
7663   bool isPPC64 = Subtarget.isPPC64();
7664   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7665   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7666 
7667   // Get the operands for the STACKRESTORE.
7668   SDValue Chain = Op.getOperand(0);
7669   SDValue SaveSP = Op.getOperand(1);
7670 
7671   // Load the old link SP.
7672   SDValue LoadLinkSP =
7673       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7674 
7675   // Restore the stack pointer.
7676   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7677 
7678   // Store the old link SP.
7679   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7680 }
7681 
7682 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7683   MachineFunction &MF = DAG.getMachineFunction();
7684   bool isPPC64 = Subtarget.isPPC64();
7685   EVT PtrVT = getPointerTy(MF.getDataLayout());
7686 
7687   // Get current frame pointer save index.  The users of this index will be
7688   // primarily DYNALLOC instructions.
7689   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7690   int RASI = FI->getReturnAddrSaveIndex();
7691 
7692   // If the frame pointer save index hasn't been defined yet.
7693   if (!RASI) {
7694     // Find out what the fix offset of the frame pointer save area.
7695     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7696     // Allocate the frame index for frame pointer save area.
7697     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7698     // Save the result.
7699     FI->setReturnAddrSaveIndex(RASI);
7700   }
7701   return DAG.getFrameIndex(RASI, PtrVT);
7702 }
7703 
7704 SDValue
7705 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7706   MachineFunction &MF = DAG.getMachineFunction();
7707   bool isPPC64 = Subtarget.isPPC64();
7708   EVT PtrVT = getPointerTy(MF.getDataLayout());
7709 
7710   // Get current frame pointer save index.  The users of this index will be
7711   // primarily DYNALLOC instructions.
7712   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7713   int FPSI = FI->getFramePointerSaveIndex();
7714 
7715   // If the frame pointer save index hasn't been defined yet.
7716   if (!FPSI) {
7717     // Find out what the fix offset of the frame pointer save area.
7718     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7719     // Allocate the frame index for frame pointer save area.
7720     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7721     // Save the result.
7722     FI->setFramePointerSaveIndex(FPSI);
7723   }
7724   return DAG.getFrameIndex(FPSI, PtrVT);
7725 }
7726 
7727 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7728                                                    SelectionDAG &DAG) const {
7729   // Get the inputs.
7730   SDValue Chain = Op.getOperand(0);
7731   SDValue Size  = Op.getOperand(1);
7732   SDLoc dl(Op);
7733 
7734   // Get the correct type for pointers.
7735   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7736   // Negate the size.
7737   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7738                                 DAG.getConstant(0, dl, PtrVT), Size);
7739   // Construct a node for the frame pointer save index.
7740   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7741   // Build a DYNALLOC node.
7742   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7743   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7744   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7745 }
7746 
7747 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7748                                                      SelectionDAG &DAG) const {
7749   MachineFunction &MF = DAG.getMachineFunction();
7750 
7751   bool isPPC64 = Subtarget.isPPC64();
7752   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7753 
7754   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7755   return DAG.getFrameIndex(FI, PtrVT);
7756 }
7757 
7758 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7759                                                SelectionDAG &DAG) const {
7760   SDLoc DL(Op);
7761   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7762                      DAG.getVTList(MVT::i32, MVT::Other),
7763                      Op.getOperand(0), Op.getOperand(1));
7764 }
7765 
7766 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7767                                                 SelectionDAG &DAG) const {
7768   SDLoc DL(Op);
7769   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7770                      Op.getOperand(0), Op.getOperand(1));
7771 }
7772 
7773 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7774   if (Op.getValueType().isVector())
7775     return LowerVectorLoad(Op, DAG);
7776 
7777   assert(Op.getValueType() == MVT::i1 &&
7778          "Custom lowering only for i1 loads");
7779 
7780   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7781 
7782   SDLoc dl(Op);
7783   LoadSDNode *LD = cast<LoadSDNode>(Op);
7784 
7785   SDValue Chain = LD->getChain();
7786   SDValue BasePtr = LD->getBasePtr();
7787   MachineMemOperand *MMO = LD->getMemOperand();
7788 
7789   SDValue NewLD =
7790       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7791                      BasePtr, MVT::i8, MMO);
7792   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7793 
7794   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7795   return DAG.getMergeValues(Ops, dl);
7796 }
7797 
7798 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7799   if (Op.getOperand(1).getValueType().isVector())
7800     return LowerVectorStore(Op, DAG);
7801 
7802   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7803          "Custom lowering only for i1 stores");
7804 
7805   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7806 
7807   SDLoc dl(Op);
7808   StoreSDNode *ST = cast<StoreSDNode>(Op);
7809 
7810   SDValue Chain = ST->getChain();
7811   SDValue BasePtr = ST->getBasePtr();
7812   SDValue Value = ST->getValue();
7813   MachineMemOperand *MMO = ST->getMemOperand();
7814 
7815   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7816                       Value);
7817   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7818 }
7819 
7820 // FIXME: Remove this once the ANDI glue bug is fixed:
7821 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7822   assert(Op.getValueType() == MVT::i1 &&
7823          "Custom lowering only for i1 results");
7824 
7825   SDLoc DL(Op);
7826   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7827 }
7828 
7829 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7830                                                SelectionDAG &DAG) const {
7831 
7832   // Implements a vector truncate that fits in a vector register as a shuffle.
7833   // We want to legalize vector truncates down to where the source fits in
7834   // a vector register (and target is therefore smaller than vector register
7835   // size).  At that point legalization will try to custom lower the sub-legal
7836   // result and get here - where we can contain the truncate as a single target
7837   // operation.
7838 
7839   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7840   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7841   //
7842   // We will implement it for big-endian ordering as this (where x denotes
7843   // undefined):
7844   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7845   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7846   //
7847   // The same operation in little-endian ordering will be:
7848   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7849   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7850 
7851   assert(Op.getValueType().isVector() && "Vector type expected.");
7852 
7853   SDLoc DL(Op);
7854   SDValue N1 = Op.getOperand(0);
7855   unsigned SrcSize = N1.getValueType().getSizeInBits();
7856   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7857   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7858 
7859   EVT TrgVT = Op.getValueType();
7860   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7861   EVT EltVT = TrgVT.getVectorElementType();
7862   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7863   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7864 
7865   // First list the elements we want to keep.
7866   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7867   SmallVector<int, 16> ShuffV;
7868   if (Subtarget.isLittleEndian())
7869     for (unsigned i = 0; i < TrgNumElts; ++i)
7870       ShuffV.push_back(i * SizeMult);
7871   else
7872     for (unsigned i = 1; i <= TrgNumElts; ++i)
7873       ShuffV.push_back(i * SizeMult - 1);
7874 
7875   // Populate the remaining elements with undefs.
7876   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7877     // ShuffV.push_back(i + WideNumElts);
7878     ShuffV.push_back(WideNumElts + 1);
7879 
7880   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7881   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7882 }
7883 
7884 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7885 /// possible.
7886 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7887   // Not FP? Not a fsel.
7888   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7889       !Op.getOperand(2).getValueType().isFloatingPoint())
7890     return Op;
7891 
7892   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7893 
7894   EVT ResVT = Op.getValueType();
7895   EVT CmpVT = Op.getOperand(0).getValueType();
7896   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7897   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7898   SDLoc dl(Op);
7899 
7900   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7901   // presence of infinities.
7902   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7903     switch (CC) {
7904     default:
7905       break;
7906     case ISD::SETOGT:
7907     case ISD::SETGT:
7908       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7909     case ISD::SETOLT:
7910     case ISD::SETLT:
7911       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7912     }
7913   }
7914 
7915   // We might be able to do better than this under some circumstances, but in
7916   // general, fsel-based lowering of select is a finite-math-only optimization.
7917   // For more information, see section F.3 of the 2.06 ISA specification.
7918   // With ISA 3.0
7919   if (!DAG.getTarget().Options.NoInfsFPMath ||
7920       !DAG.getTarget().Options.NoNaNsFPMath)
7921     return Op;
7922 
7923   // TODO: Propagate flags from the select rather than global settings.
7924   SDNodeFlags Flags;
7925   Flags.setNoInfs(true);
7926   Flags.setNoNaNs(true);
7927 
7928   // If the RHS of the comparison is a 0.0, we don't need to do the
7929   // subtraction at all.
7930   SDValue Sel1;
7931   if (isFloatingPointZero(RHS))
7932     switch (CC) {
7933     default: break;       // SETUO etc aren't handled by fsel.
7934     case ISD::SETNE:
7935       std::swap(TV, FV);
7936       LLVM_FALLTHROUGH;
7937     case ISD::SETEQ:
7938       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7939         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7940       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7941       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7942         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7943       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7944                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7945     case ISD::SETULT:
7946     case ISD::SETLT:
7947       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7948       LLVM_FALLTHROUGH;
7949     case ISD::SETOGE:
7950     case ISD::SETGE:
7951       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7952         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7953       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7954     case ISD::SETUGT:
7955     case ISD::SETGT:
7956       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7957       LLVM_FALLTHROUGH;
7958     case ISD::SETOLE:
7959     case ISD::SETLE:
7960       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7961         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7962       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7963                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7964     }
7965 
7966   SDValue Cmp;
7967   switch (CC) {
7968   default: break;       // SETUO etc aren't handled by fsel.
7969   case ISD::SETNE:
7970     std::swap(TV, FV);
7971     LLVM_FALLTHROUGH;
7972   case ISD::SETEQ:
7973     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7974     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7975       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7976     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7977     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7978       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7979     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7980                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7981   case ISD::SETULT:
7982   case ISD::SETLT:
7983     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7984     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7985       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7986     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7987   case ISD::SETOGE:
7988   case ISD::SETGE:
7989     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7990     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7991       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7992     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7993   case ISD::SETUGT:
7994   case ISD::SETGT:
7995     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7996     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7997       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7998     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7999   case ISD::SETOLE:
8000   case ISD::SETLE:
8001     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8002     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8003       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8004     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8005   }
8006   return Op;
8007 }
8008 
8009 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8010                                                SelectionDAG &DAG,
8011                                                const SDLoc &dl) const {
8012   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8013   SDValue Src = Op.getOperand(0);
8014   if (Src.getValueType() == MVT::f32)
8015     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8016 
8017   SDValue Tmp;
8018   switch (Op.getSimpleValueType().SimpleTy) {
8019   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8020   case MVT::i32:
8021     Tmp = DAG.getNode(
8022         Op.getOpcode() == ISD::FP_TO_SINT
8023             ? PPCISD::FCTIWZ
8024             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8025         dl, MVT::f64, Src);
8026     break;
8027   case MVT::i64:
8028     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8029            "i64 FP_TO_UINT is supported only with FPCVT");
8030     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8031                                                         PPCISD::FCTIDUZ,
8032                       dl, MVT::f64, Src);
8033     break;
8034   }
8035 
8036   // Convert the FP value to an int value through memory.
8037   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8038     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8039   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8040   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8041   MachinePointerInfo MPI =
8042       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8043 
8044   // Emit a store to the stack slot.
8045   SDValue Chain;
8046   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8047   if (i32Stack) {
8048     MachineFunction &MF = DAG.getMachineFunction();
8049     Alignment = Align(4);
8050     MachineMemOperand *MMO =
8051         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8052     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8053     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8054               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8055   } else
8056     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8057 
8058   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8059   // add in a bias on big endian.
8060   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8061     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8062                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8063     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8064   }
8065 
8066   RLI.Chain = Chain;
8067   RLI.Ptr = FIPtr;
8068   RLI.MPI = MPI;
8069   RLI.Alignment = Alignment;
8070 }
8071 
8072 /// Custom lowers floating point to integer conversions to use
8073 /// the direct move instructions available in ISA 2.07 to avoid the
8074 /// need for load/store combinations.
8075 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8076                                                     SelectionDAG &DAG,
8077                                                     const SDLoc &dl) const {
8078   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8079   SDValue Src = Op.getOperand(0);
8080 
8081   if (Src.getValueType() == MVT::f32)
8082     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8083 
8084   SDValue Tmp;
8085   switch (Op.getSimpleValueType().SimpleTy) {
8086   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8087   case MVT::i32:
8088     Tmp = DAG.getNode(
8089         Op.getOpcode() == ISD::FP_TO_SINT
8090             ? PPCISD::FCTIWZ
8091             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8092         dl, MVT::f64, Src);
8093     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8094     break;
8095   case MVT::i64:
8096     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8097            "i64 FP_TO_UINT is supported only with FPCVT");
8098     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8099                                                         PPCISD::FCTIDUZ,
8100                       dl, MVT::f64, Src);
8101     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8102     break;
8103   }
8104   return Tmp;
8105 }
8106 
8107 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8108                                           const SDLoc &dl) const {
8109 
8110   // FP to INT conversions are legal for f128.
8111   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8112     return Op;
8113 
8114   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8115   // PPC (the libcall is not available).
8116   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8117     if (Op.getValueType() == MVT::i32) {
8118       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8119         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8120                                  MVT::f64, Op.getOperand(0),
8121                                  DAG.getIntPtrConstant(0, dl));
8122         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8123                                  MVT::f64, Op.getOperand(0),
8124                                  DAG.getIntPtrConstant(1, dl));
8125 
8126         // Add the two halves of the long double in round-to-zero mode.
8127         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8128 
8129         // Now use a smaller FP_TO_SINT.
8130         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8131       }
8132       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8133         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8134         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8135         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8136         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8137         // FIXME: generated code sucks.
8138         // TODO: Are there fast-math-flags to propagate to this FSUB?
8139         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8140                                    Op.getOperand(0), Tmp);
8141         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8142         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8143                            DAG.getConstant(0x80000000, dl, MVT::i32));
8144         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8145                                     Op.getOperand(0));
8146         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8147                                ISD::SETGE);
8148       }
8149     }
8150 
8151     return SDValue();
8152   }
8153 
8154   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8155     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8156 
8157   ReuseLoadInfo RLI;
8158   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8159 
8160   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8161                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8162 }
8163 
8164 // We're trying to insert a regular store, S, and then a load, L. If the
8165 // incoming value, O, is a load, we might just be able to have our load use the
8166 // address used by O. However, we don't know if anything else will store to
8167 // that address before we can load from it. To prevent this situation, we need
8168 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8169 // the same chain operand as O, we create a token factor from the chain results
8170 // of O and L, and we replace all uses of O's chain result with that token
8171 // factor (see spliceIntoChain below for this last part).
8172 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8173                                             ReuseLoadInfo &RLI,
8174                                             SelectionDAG &DAG,
8175                                             ISD::LoadExtType ET) const {
8176   SDLoc dl(Op);
8177   if (ET == ISD::NON_EXTLOAD &&
8178       (Op.getOpcode() == ISD::FP_TO_UINT ||
8179        Op.getOpcode() == ISD::FP_TO_SINT) &&
8180       isOperationLegalOrCustom(Op.getOpcode(),
8181                                Op.getOperand(0).getValueType())) {
8182 
8183     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8184     return true;
8185   }
8186 
8187   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8188   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8189       LD->isNonTemporal())
8190     return false;
8191   if (LD->getMemoryVT() != MemVT)
8192     return false;
8193 
8194   RLI.Ptr = LD->getBasePtr();
8195   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8196     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8197            "Non-pre-inc AM on PPC?");
8198     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8199                           LD->getOffset());
8200   }
8201 
8202   RLI.Chain = LD->getChain();
8203   RLI.MPI = LD->getPointerInfo();
8204   RLI.IsDereferenceable = LD->isDereferenceable();
8205   RLI.IsInvariant = LD->isInvariant();
8206   RLI.Alignment = LD->getAlign();
8207   RLI.AAInfo = LD->getAAInfo();
8208   RLI.Ranges = LD->getRanges();
8209 
8210   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8211   return true;
8212 }
8213 
8214 // Given the head of the old chain, ResChain, insert a token factor containing
8215 // it and NewResChain, and make users of ResChain now be users of that token
8216 // factor.
8217 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8218 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8219                                         SDValue NewResChain,
8220                                         SelectionDAG &DAG) const {
8221   if (!ResChain)
8222     return;
8223 
8224   SDLoc dl(NewResChain);
8225 
8226   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8227                            NewResChain, DAG.getUNDEF(MVT::Other));
8228   assert(TF.getNode() != NewResChain.getNode() &&
8229          "A new TF really is required here");
8230 
8231   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8232   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8233 }
8234 
8235 /// Analyze profitability of direct move
8236 /// prefer float load to int load plus direct move
8237 /// when there is no integer use of int load
8238 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8239   SDNode *Origin = Op.getOperand(0).getNode();
8240   if (Origin->getOpcode() != ISD::LOAD)
8241     return true;
8242 
8243   // If there is no LXSIBZX/LXSIHZX, like Power8,
8244   // prefer direct move if the memory size is 1 or 2 bytes.
8245   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8246   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8247     return true;
8248 
8249   for (SDNode::use_iterator UI = Origin->use_begin(),
8250                             UE = Origin->use_end();
8251        UI != UE; ++UI) {
8252 
8253     // Only look at the users of the loaded value.
8254     if (UI.getUse().get().getResNo() != 0)
8255       continue;
8256 
8257     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8258         UI->getOpcode() != ISD::UINT_TO_FP)
8259       return true;
8260   }
8261 
8262   return false;
8263 }
8264 
8265 /// Custom lowers integer to floating point conversions to use
8266 /// the direct move instructions available in ISA 2.07 to avoid the
8267 /// need for load/store combinations.
8268 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8269                                                     SelectionDAG &DAG,
8270                                                     const SDLoc &dl) const {
8271   assert((Op.getValueType() == MVT::f32 ||
8272           Op.getValueType() == MVT::f64) &&
8273          "Invalid floating point type as target of conversion");
8274   assert(Subtarget.hasFPCVT() &&
8275          "Int to FP conversions with direct moves require FPCVT");
8276   SDValue FP;
8277   SDValue Src = Op.getOperand(0);
8278   bool SinglePrec = Op.getValueType() == MVT::f32;
8279   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8280   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8281   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8282                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8283 
8284   if (WordInt) {
8285     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8286                      dl, MVT::f64, Src);
8287     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8288   }
8289   else {
8290     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8291     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8292   }
8293 
8294   return FP;
8295 }
8296 
8297 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8298 
8299   EVT VecVT = Vec.getValueType();
8300   assert(VecVT.isVector() && "Expected a vector type.");
8301   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8302 
8303   EVT EltVT = VecVT.getVectorElementType();
8304   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8305   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8306 
8307   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8308   SmallVector<SDValue, 16> Ops(NumConcat);
8309   Ops[0] = Vec;
8310   SDValue UndefVec = DAG.getUNDEF(VecVT);
8311   for (unsigned i = 1; i < NumConcat; ++i)
8312     Ops[i] = UndefVec;
8313 
8314   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8315 }
8316 
8317 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8318                                                 const SDLoc &dl) const {
8319 
8320   unsigned Opc = Op.getOpcode();
8321   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8322          "Unexpected conversion type");
8323   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8324          "Supports conversions to v2f64/v4f32 only.");
8325 
8326   bool SignedConv = Opc == ISD::SINT_TO_FP;
8327   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8328 
8329   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8330   EVT WideVT = Wide.getValueType();
8331   unsigned WideNumElts = WideVT.getVectorNumElements();
8332   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8333 
8334   SmallVector<int, 16> ShuffV;
8335   for (unsigned i = 0; i < WideNumElts; ++i)
8336     ShuffV.push_back(i + WideNumElts);
8337 
8338   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8339   int SaveElts = FourEltRes ? 4 : 2;
8340   if (Subtarget.isLittleEndian())
8341     for (int i = 0; i < SaveElts; i++)
8342       ShuffV[i * Stride] = i;
8343   else
8344     for (int i = 1; i <= SaveElts; i++)
8345       ShuffV[i * Stride - 1] = i - 1;
8346 
8347   SDValue ShuffleSrc2 =
8348       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8349   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8350 
8351   SDValue Extend;
8352   if (SignedConv) {
8353     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8354     EVT ExtVT = Op.getOperand(0).getValueType();
8355     if (Subtarget.hasP9Altivec())
8356       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8357                                IntermediateVT.getVectorNumElements());
8358 
8359     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8360                          DAG.getValueType(ExtVT));
8361   } else
8362     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8363 
8364   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8365 }
8366 
8367 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8368                                           SelectionDAG &DAG) const {
8369   SDLoc dl(Op);
8370 
8371   EVT InVT = Op.getOperand(0).getValueType();
8372   EVT OutVT = Op.getValueType();
8373   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8374       isOperationCustom(Op.getOpcode(), InVT))
8375     return LowerINT_TO_FPVector(Op, DAG, dl);
8376 
8377   // Conversions to f128 are legal.
8378   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8379     return Op;
8380 
8381   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8382     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8383       return SDValue();
8384 
8385     SDValue Value = Op.getOperand(0);
8386     // The values are now known to be -1 (false) or 1 (true). To convert this
8387     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8388     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8389     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8390 
8391     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8392 
8393     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8394 
8395     if (Op.getValueType() != MVT::v4f64)
8396       Value = DAG.getNode(ISD::FP_ROUND, dl,
8397                           Op.getValueType(), Value,
8398                           DAG.getIntPtrConstant(1, dl));
8399     return Value;
8400   }
8401 
8402   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8403   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8404     return SDValue();
8405 
8406   if (Op.getOperand(0).getValueType() == MVT::i1)
8407     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8408                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8409                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8410 
8411   // If we have direct moves, we can do all the conversion, skip the store/load
8412   // however, without FPCVT we can't do most conversions.
8413   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8414       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8415     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8416 
8417   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8418          "UINT_TO_FP is supported only with FPCVT");
8419 
8420   // If we have FCFIDS, then use it when converting to single-precision.
8421   // Otherwise, convert to double-precision and then round.
8422   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8423                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8424                                                             : PPCISD::FCFIDS)
8425                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8426                                                             : PPCISD::FCFID);
8427   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8428                   ? MVT::f32
8429                   : MVT::f64;
8430 
8431   if (Op.getOperand(0).getValueType() == MVT::i64) {
8432     SDValue SINT = Op.getOperand(0);
8433     // When converting to single-precision, we actually need to convert
8434     // to double-precision first and then round to single-precision.
8435     // To avoid double-rounding effects during that operation, we have
8436     // to prepare the input operand.  Bits that might be truncated when
8437     // converting to double-precision are replaced by a bit that won't
8438     // be lost at this stage, but is below the single-precision rounding
8439     // position.
8440     //
8441     // However, if -enable-unsafe-fp-math is in effect, accept double
8442     // rounding to avoid the extra overhead.
8443     if (Op.getValueType() == MVT::f32 &&
8444         !Subtarget.hasFPCVT() &&
8445         !DAG.getTarget().Options.UnsafeFPMath) {
8446 
8447       // Twiddle input to make sure the low 11 bits are zero.  (If this
8448       // is the case, we are guaranteed the value will fit into the 53 bit
8449       // mantissa of an IEEE double-precision value without rounding.)
8450       // If any of those low 11 bits were not zero originally, make sure
8451       // bit 12 (value 2048) is set instead, so that the final rounding
8452       // to single-precision gets the correct result.
8453       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8454                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8455       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8456                           Round, DAG.getConstant(2047, dl, MVT::i64));
8457       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8458       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8459                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8460 
8461       // However, we cannot use that value unconditionally: if the magnitude
8462       // of the input value is small, the bit-twiddling we did above might
8463       // end up visibly changing the output.  Fortunately, in that case, we
8464       // don't need to twiddle bits since the original input will convert
8465       // exactly to double-precision floating-point already.  Therefore,
8466       // construct a conditional to use the original value if the top 11
8467       // bits are all sign-bit copies, and use the rounded value computed
8468       // above otherwise.
8469       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8470                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8471       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8472                          Cond, DAG.getConstant(1, dl, MVT::i64));
8473       Cond = DAG.getSetCC(
8474           dl,
8475           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8476           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8477 
8478       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8479     }
8480 
8481     ReuseLoadInfo RLI;
8482     SDValue Bits;
8483 
8484     MachineFunction &MF = DAG.getMachineFunction();
8485     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8486       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8487                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8488       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8489     } else if (Subtarget.hasLFIWAX() &&
8490                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8491       MachineMemOperand *MMO =
8492         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8493                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8494       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8495       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8496                                      DAG.getVTList(MVT::f64, MVT::Other),
8497                                      Ops, MVT::i32, MMO);
8498       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8499     } else if (Subtarget.hasFPCVT() &&
8500                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8501       MachineMemOperand *MMO =
8502         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8503                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8504       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8505       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8506                                      DAG.getVTList(MVT::f64, MVT::Other),
8507                                      Ops, MVT::i32, MMO);
8508       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8509     } else if (((Subtarget.hasLFIWAX() &&
8510                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8511                 (Subtarget.hasFPCVT() &&
8512                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8513                SINT.getOperand(0).getValueType() == MVT::i32) {
8514       MachineFrameInfo &MFI = MF.getFrameInfo();
8515       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8516 
8517       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8518       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8519 
8520       SDValue Store =
8521           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8522                        MachinePointerInfo::getFixedStack(
8523                            DAG.getMachineFunction(), FrameIdx));
8524 
8525       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8526              "Expected an i32 store");
8527 
8528       RLI.Ptr = FIdx;
8529       RLI.Chain = Store;
8530       RLI.MPI =
8531           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8532       RLI.Alignment = Align(4);
8533 
8534       MachineMemOperand *MMO =
8535         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8536                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8537       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8538       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8539                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8540                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8541                                      Ops, MVT::i32, MMO);
8542     } else
8543       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8544 
8545     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8546 
8547     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8548       FP = DAG.getNode(ISD::FP_ROUND, dl,
8549                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8550     return FP;
8551   }
8552 
8553   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8554          "Unhandled INT_TO_FP type in custom expander!");
8555   // Since we only generate this in 64-bit mode, we can take advantage of
8556   // 64-bit registers.  In particular, sign extend the input value into the
8557   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8558   // then lfd it and fcfid it.
8559   MachineFunction &MF = DAG.getMachineFunction();
8560   MachineFrameInfo &MFI = MF.getFrameInfo();
8561   EVT PtrVT = getPointerTy(MF.getDataLayout());
8562 
8563   SDValue Ld;
8564   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8565     ReuseLoadInfo RLI;
8566     bool ReusingLoad;
8567     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8568                                             DAG))) {
8569       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8570       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8571 
8572       SDValue Store =
8573           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8574                        MachinePointerInfo::getFixedStack(
8575                            DAG.getMachineFunction(), FrameIdx));
8576 
8577       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8578              "Expected an i32 store");
8579 
8580       RLI.Ptr = FIdx;
8581       RLI.Chain = Store;
8582       RLI.MPI =
8583           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8584       RLI.Alignment = Align(4);
8585     }
8586 
8587     MachineMemOperand *MMO =
8588       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8589                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8590     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8591     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8592                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8593                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8594                                  Ops, MVT::i32, MMO);
8595     if (ReusingLoad)
8596       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8597   } else {
8598     assert(Subtarget.isPPC64() &&
8599            "i32->FP without LFIWAX supported only on PPC64");
8600 
8601     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8602     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8603 
8604     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8605                                 Op.getOperand(0));
8606 
8607     // STD the extended value into the stack slot.
8608     SDValue Store = DAG.getStore(
8609         DAG.getEntryNode(), dl, Ext64, FIdx,
8610         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8611 
8612     // Load the value as a double.
8613     Ld = DAG.getLoad(
8614         MVT::f64, dl, Store, FIdx,
8615         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8616   }
8617 
8618   // FCFID it and return it.
8619   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8620   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8621     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8622                      DAG.getIntPtrConstant(0, dl));
8623   return FP;
8624 }
8625 
8626 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8627                                             SelectionDAG &DAG) const {
8628   SDLoc dl(Op);
8629   /*
8630    The rounding mode is in bits 30:31 of FPSR, and has the following
8631    settings:
8632      00 Round to nearest
8633      01 Round to 0
8634      10 Round to +inf
8635      11 Round to -inf
8636 
8637   FLT_ROUNDS, on the other hand, expects the following:
8638     -1 Undefined
8639      0 Round to 0
8640      1 Round to nearest
8641      2 Round to +inf
8642      3 Round to -inf
8643 
8644   To perform the conversion, we do:
8645     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8646   */
8647 
8648   MachineFunction &MF = DAG.getMachineFunction();
8649   EVT VT = Op.getValueType();
8650   EVT PtrVT = getPointerTy(MF.getDataLayout());
8651 
8652   // Save FP Control Word to register
8653   SDValue Chain = Op.getOperand(0);
8654   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8655   Chain = MFFS.getValue(1);
8656 
8657   // Save FP register to stack slot
8658   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8659   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8660   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8661 
8662   // Load FP Control Word from low 32 bits of stack slot.
8663   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8664   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8665   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8666   Chain = CWD.getValue(1);
8667 
8668   // Transform as necessary
8669   SDValue CWD1 =
8670     DAG.getNode(ISD::AND, dl, MVT::i32,
8671                 CWD, DAG.getConstant(3, dl, MVT::i32));
8672   SDValue CWD2 =
8673     DAG.getNode(ISD::SRL, dl, MVT::i32,
8674                 DAG.getNode(ISD::AND, dl, MVT::i32,
8675                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8676                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8677                             DAG.getConstant(3, dl, MVT::i32)),
8678                 DAG.getConstant(1, dl, MVT::i32));
8679 
8680   SDValue RetVal =
8681     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8682 
8683   RetVal =
8684       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8685                   dl, VT, RetVal);
8686 
8687   return DAG.getMergeValues({RetVal, Chain}, dl);
8688 }
8689 
8690 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8691   EVT VT = Op.getValueType();
8692   unsigned BitWidth = VT.getSizeInBits();
8693   SDLoc dl(Op);
8694   assert(Op.getNumOperands() == 3 &&
8695          VT == Op.getOperand(1).getValueType() &&
8696          "Unexpected SHL!");
8697 
8698   // Expand into a bunch of logical ops.  Note that these ops
8699   // depend on the PPC behavior for oversized shift amounts.
8700   SDValue Lo = Op.getOperand(0);
8701   SDValue Hi = Op.getOperand(1);
8702   SDValue Amt = Op.getOperand(2);
8703   EVT AmtVT = Amt.getValueType();
8704 
8705   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8706                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8707   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8708   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8709   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8710   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8711                              DAG.getConstant(-BitWidth, dl, AmtVT));
8712   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8713   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8714   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8715   SDValue OutOps[] = { OutLo, OutHi };
8716   return DAG.getMergeValues(OutOps, dl);
8717 }
8718 
8719 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8720   EVT VT = Op.getValueType();
8721   SDLoc dl(Op);
8722   unsigned BitWidth = VT.getSizeInBits();
8723   assert(Op.getNumOperands() == 3 &&
8724          VT == Op.getOperand(1).getValueType() &&
8725          "Unexpected SRL!");
8726 
8727   // Expand into a bunch of logical ops.  Note that these ops
8728   // depend on the PPC behavior for oversized shift amounts.
8729   SDValue Lo = Op.getOperand(0);
8730   SDValue Hi = Op.getOperand(1);
8731   SDValue Amt = Op.getOperand(2);
8732   EVT AmtVT = Amt.getValueType();
8733 
8734   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8735                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8736   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8737   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8738   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8739   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8740                              DAG.getConstant(-BitWidth, dl, AmtVT));
8741   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8742   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8743   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8744   SDValue OutOps[] = { OutLo, OutHi };
8745   return DAG.getMergeValues(OutOps, dl);
8746 }
8747 
8748 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8749   SDLoc dl(Op);
8750   EVT VT = Op.getValueType();
8751   unsigned BitWidth = VT.getSizeInBits();
8752   assert(Op.getNumOperands() == 3 &&
8753          VT == Op.getOperand(1).getValueType() &&
8754          "Unexpected SRA!");
8755 
8756   // Expand into a bunch of logical ops, followed by a select_cc.
8757   SDValue Lo = Op.getOperand(0);
8758   SDValue Hi = Op.getOperand(1);
8759   SDValue Amt = Op.getOperand(2);
8760   EVT AmtVT = Amt.getValueType();
8761 
8762   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8763                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8764   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8765   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8766   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8767   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8768                              DAG.getConstant(-BitWidth, dl, AmtVT));
8769   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8770   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8771   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8772                                   Tmp4, Tmp6, ISD::SETLE);
8773   SDValue OutOps[] = { OutLo, OutHi };
8774   return DAG.getMergeValues(OutOps, dl);
8775 }
8776 
8777 //===----------------------------------------------------------------------===//
8778 // Vector related lowering.
8779 //
8780 
8781 /// BuildSplatI - Build a canonical splati of Val with an element size of
8782 /// SplatSize.  Cast the result to VT.
8783 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8784                            SelectionDAG &DAG, const SDLoc &dl) {
8785   static const MVT VTys[] = { // canonical VT to use for each size.
8786     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8787   };
8788 
8789   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8790 
8791   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8792   if (Val == -1)
8793     SplatSize = 1;
8794 
8795   EVT CanonicalVT = VTys[SplatSize-1];
8796 
8797   // Build a canonical splat for this value.
8798   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8799 }
8800 
8801 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8802 /// specified intrinsic ID.
8803 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8804                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8805   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8806   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8807                      DAG.getConstant(IID, dl, MVT::i32), Op);
8808 }
8809 
8810 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8811 /// specified intrinsic ID.
8812 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8813                                 SelectionDAG &DAG, const SDLoc &dl,
8814                                 EVT DestVT = MVT::Other) {
8815   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8816   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8817                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8818 }
8819 
8820 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8821 /// specified intrinsic ID.
8822 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8823                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8824                                 EVT DestVT = MVT::Other) {
8825   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8826   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8827                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8828 }
8829 
8830 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8831 /// amount.  The result has the specified value type.
8832 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8833                            SelectionDAG &DAG, const SDLoc &dl) {
8834   // Force LHS/RHS to be the right type.
8835   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8836   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8837 
8838   int Ops[16];
8839   for (unsigned i = 0; i != 16; ++i)
8840     Ops[i] = i + Amt;
8841   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8842   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8843 }
8844 
8845 /// Do we have an efficient pattern in a .td file for this node?
8846 ///
8847 /// \param V - pointer to the BuildVectorSDNode being matched
8848 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8849 ///
8850 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8851 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8852 /// the opposite is true (expansion is beneficial) are:
8853 /// - The node builds a vector out of integers that are not 32 or 64-bits
8854 /// - The node builds a vector out of constants
8855 /// - The node is a "load-and-splat"
8856 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8857 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8858                                             bool HasDirectMove,
8859                                             bool HasP8Vector) {
8860   EVT VecVT = V->getValueType(0);
8861   bool RightType = VecVT == MVT::v2f64 ||
8862     (HasP8Vector && VecVT == MVT::v4f32) ||
8863     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8864   if (!RightType)
8865     return false;
8866 
8867   bool IsSplat = true;
8868   bool IsLoad = false;
8869   SDValue Op0 = V->getOperand(0);
8870 
8871   // This function is called in a block that confirms the node is not a constant
8872   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8873   // different constants.
8874   if (V->isConstant())
8875     return false;
8876   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8877     if (V->getOperand(i).isUndef())
8878       return false;
8879     // We want to expand nodes that represent load-and-splat even if the
8880     // loaded value is a floating point truncation or conversion to int.
8881     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8882         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8883          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8884         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8885          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8886         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8887          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8888       IsLoad = true;
8889     // If the operands are different or the input is not a load and has more
8890     // uses than just this BV node, then it isn't a splat.
8891     if (V->getOperand(i) != Op0 ||
8892         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8893       IsSplat = false;
8894   }
8895   return !(IsSplat && IsLoad);
8896 }
8897 
8898 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8899 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8900 
8901   SDLoc dl(Op);
8902   SDValue Op0 = Op->getOperand(0);
8903 
8904   if (!EnableQuadPrecision ||
8905       (Op.getValueType() != MVT::f128 ) ||
8906       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8907       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8908       (Op0.getOperand(1).getValueType() != MVT::i64))
8909     return SDValue();
8910 
8911   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8912                      Op0.getOperand(1));
8913 }
8914 
8915 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8916   const SDValue *InputLoad = &Op;
8917   if (InputLoad->getOpcode() == ISD::BITCAST)
8918     InputLoad = &InputLoad->getOperand(0);
8919   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8920     InputLoad = &InputLoad->getOperand(0);
8921   if (InputLoad->getOpcode() != ISD::LOAD)
8922     return nullptr;
8923   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8924   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8925 }
8926 
8927 // If this is a case we can't handle, return null and let the default
8928 // expansion code take care of it.  If we CAN select this case, and if it
8929 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8930 // this case more efficiently than a constant pool load, lower it to the
8931 // sequence of ops that should be used.
8932 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8933                                              SelectionDAG &DAG) const {
8934   SDLoc dl(Op);
8935   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8936   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8937 
8938   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8939     // We first build an i32 vector, load it into a QPX register,
8940     // then convert it to a floating-point vector and compare it
8941     // to a zero vector to get the boolean result.
8942     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8943     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8944     MachinePointerInfo PtrInfo =
8945         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8946     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8947     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8948 
8949     assert(BVN->getNumOperands() == 4 &&
8950       "BUILD_VECTOR for v4i1 does not have 4 operands");
8951 
8952     bool IsConst = true;
8953     for (unsigned i = 0; i < 4; ++i) {
8954       if (BVN->getOperand(i).isUndef()) continue;
8955       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8956         IsConst = false;
8957         break;
8958       }
8959     }
8960 
8961     if (IsConst) {
8962       Constant *One =
8963         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8964       Constant *NegOne =
8965         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8966 
8967       Constant *CV[4];
8968       for (unsigned i = 0; i < 4; ++i) {
8969         if (BVN->getOperand(i).isUndef())
8970           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8971         else if (isNullConstant(BVN->getOperand(i)))
8972           CV[i] = NegOne;
8973         else
8974           CV[i] = One;
8975       }
8976 
8977       Constant *CP = ConstantVector::get(CV);
8978       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8979                                           16 /* alignment */);
8980 
8981       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8982       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8983       return DAG.getMemIntrinsicNode(
8984           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8985           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8986     }
8987 
8988     SmallVector<SDValue, 4> Stores;
8989     for (unsigned i = 0; i < 4; ++i) {
8990       if (BVN->getOperand(i).isUndef()) continue;
8991 
8992       unsigned Offset = 4*i;
8993       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8994       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8995 
8996       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8997       if (StoreSize > 4) {
8998         Stores.push_back(
8999             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9000                               PtrInfo.getWithOffset(Offset), MVT::i32));
9001       } else {
9002         SDValue StoreValue = BVN->getOperand(i);
9003         if (StoreSize < 4)
9004           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9005 
9006         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9007                                       PtrInfo.getWithOffset(Offset)));
9008       }
9009     }
9010 
9011     SDValue StoreChain;
9012     if (!Stores.empty())
9013       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9014     else
9015       StoreChain = DAG.getEntryNode();
9016 
9017     // Now load from v4i32 into the QPX register; this will extend it to
9018     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9019     // is typed as v4f64 because the QPX register integer states are not
9020     // explicitly represented.
9021 
9022     SDValue Ops[] = {StoreChain,
9023                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9024                      FIdx};
9025     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9026 
9027     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9028       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9029     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9030       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9031       LoadedVect);
9032 
9033     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9034 
9035     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9036   }
9037 
9038   // All other QPX vectors are handled by generic code.
9039   if (Subtarget.hasQPX())
9040     return SDValue();
9041 
9042   // Check if this is a splat of a constant value.
9043   APInt APSplatBits, APSplatUndef;
9044   unsigned SplatBitSize;
9045   bool HasAnyUndefs;
9046   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9047                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9048       SplatBitSize > 32) {
9049 
9050     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9051     // Handle load-and-splat patterns as we have instructions that will do this
9052     // in one go.
9053     if (InputLoad && DAG.isSplatValue(Op, true)) {
9054       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9055 
9056       // We have handling for 4 and 8 byte elements.
9057       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9058 
9059       // Checking for a single use of this load, we have to check for vector
9060       // width (128 bits) / ElementSize uses (since each operand of the
9061       // BUILD_VECTOR is a separate use of the value.
9062       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9063           ((Subtarget.hasVSX() && ElementSize == 64) ||
9064            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9065         SDValue Ops[] = {
9066           LD->getChain(),    // Chain
9067           LD->getBasePtr(),  // Ptr
9068           DAG.getValueType(Op.getValueType()) // VT
9069         };
9070         return
9071           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9072                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9073                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9074       }
9075     }
9076 
9077     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9078     // lowered to VSX instructions under certain conditions.
9079     // Without VSX, there is no pattern more efficient than expanding the node.
9080     if (Subtarget.hasVSX() &&
9081         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9082                                         Subtarget.hasP8Vector()))
9083       return Op;
9084     return SDValue();
9085   }
9086 
9087   unsigned SplatBits = APSplatBits.getZExtValue();
9088   unsigned SplatUndef = APSplatUndef.getZExtValue();
9089   unsigned SplatSize = SplatBitSize / 8;
9090 
9091   // First, handle single instruction cases.
9092 
9093   // All zeros?
9094   if (SplatBits == 0) {
9095     // Canonicalize all zero vectors to be v4i32.
9096     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9097       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9098       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9099     }
9100     return Op;
9101   }
9102 
9103   // We have XXSPLTIB for constant splats one byte wide
9104   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9105   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9106   if (Subtarget.hasP9Vector() && SplatSize == 1)
9107     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9108 
9109   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9110   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9111                     (32-SplatBitSize));
9112   if (SextVal >= -16 && SextVal <= 15)
9113     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9114 
9115   // Two instruction sequences.
9116 
9117   // If this value is in the range [-32,30] and is even, use:
9118   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9119   // If this value is in the range [17,31] and is odd, use:
9120   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9121   // If this value is in the range [-31,-17] and is odd, use:
9122   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9123   // Note the last two are three-instruction sequences.
9124   if (SextVal >= -32 && SextVal <= 31) {
9125     // To avoid having these optimizations undone by constant folding,
9126     // we convert to a pseudo that will be expanded later into one of
9127     // the above forms.
9128     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9129     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9130               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9131     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9132     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9133     if (VT == Op.getValueType())
9134       return RetVal;
9135     else
9136       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9137   }
9138 
9139   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9140   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9141   // for fneg/fabs.
9142   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9143     // Make -1 and vspltisw -1:
9144     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9145 
9146     // Make the VSLW intrinsic, computing 0x8000_0000.
9147     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9148                                    OnesV, DAG, dl);
9149 
9150     // xor by OnesV to invert it.
9151     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9152     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9153   }
9154 
9155   // Check to see if this is a wide variety of vsplti*, binop self cases.
9156   static const signed char SplatCsts[] = {
9157     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9158     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9159   };
9160 
9161   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9162     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9163     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9164     int i = SplatCsts[idx];
9165 
9166     // Figure out what shift amount will be used by altivec if shifted by i in
9167     // this splat size.
9168     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9169 
9170     // vsplti + shl self.
9171     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9172       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9173       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9174         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9175         Intrinsic::ppc_altivec_vslw
9176       };
9177       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9178       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9179     }
9180 
9181     // vsplti + srl self.
9182     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9183       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9184       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9185         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9186         Intrinsic::ppc_altivec_vsrw
9187       };
9188       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9189       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9190     }
9191 
9192     // vsplti + sra self.
9193     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9194       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9195       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9196         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9197         Intrinsic::ppc_altivec_vsraw
9198       };
9199       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9200       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9201     }
9202 
9203     // vsplti + rol self.
9204     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9205                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9206       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9207       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9208         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9209         Intrinsic::ppc_altivec_vrlw
9210       };
9211       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9212       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9213     }
9214 
9215     // t = vsplti c, result = vsldoi t, t, 1
9216     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9217       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9218       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9219       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9220     }
9221     // t = vsplti c, result = vsldoi t, t, 2
9222     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9223       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9224       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9225       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9226     }
9227     // t = vsplti c, result = vsldoi t, t, 3
9228     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9229       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9230       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9231       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9232     }
9233   }
9234 
9235   return SDValue();
9236 }
9237 
9238 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9239 /// the specified operations to build the shuffle.
9240 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9241                                       SDValue RHS, SelectionDAG &DAG,
9242                                       const SDLoc &dl) {
9243   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9244   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9245   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9246 
9247   enum {
9248     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9249     OP_VMRGHW,
9250     OP_VMRGLW,
9251     OP_VSPLTISW0,
9252     OP_VSPLTISW1,
9253     OP_VSPLTISW2,
9254     OP_VSPLTISW3,
9255     OP_VSLDOI4,
9256     OP_VSLDOI8,
9257     OP_VSLDOI12
9258   };
9259 
9260   if (OpNum == OP_COPY) {
9261     if (LHSID == (1*9+2)*9+3) return LHS;
9262     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9263     return RHS;
9264   }
9265 
9266   SDValue OpLHS, OpRHS;
9267   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9268   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9269 
9270   int ShufIdxs[16];
9271   switch (OpNum) {
9272   default: llvm_unreachable("Unknown i32 permute!");
9273   case OP_VMRGHW:
9274     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9275     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9276     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9277     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9278     break;
9279   case OP_VMRGLW:
9280     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9281     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9282     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9283     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9284     break;
9285   case OP_VSPLTISW0:
9286     for (unsigned i = 0; i != 16; ++i)
9287       ShufIdxs[i] = (i&3)+0;
9288     break;
9289   case OP_VSPLTISW1:
9290     for (unsigned i = 0; i != 16; ++i)
9291       ShufIdxs[i] = (i&3)+4;
9292     break;
9293   case OP_VSPLTISW2:
9294     for (unsigned i = 0; i != 16; ++i)
9295       ShufIdxs[i] = (i&3)+8;
9296     break;
9297   case OP_VSPLTISW3:
9298     for (unsigned i = 0; i != 16; ++i)
9299       ShufIdxs[i] = (i&3)+12;
9300     break;
9301   case OP_VSLDOI4:
9302     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9303   case OP_VSLDOI8:
9304     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9305   case OP_VSLDOI12:
9306     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9307   }
9308   EVT VT = OpLHS.getValueType();
9309   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9310   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9311   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9312   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9313 }
9314 
9315 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9316 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9317 /// SDValue.
9318 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9319                                            SelectionDAG &DAG) const {
9320   const unsigned BytesInVector = 16;
9321   bool IsLE = Subtarget.isLittleEndian();
9322   SDLoc dl(N);
9323   SDValue V1 = N->getOperand(0);
9324   SDValue V2 = N->getOperand(1);
9325   unsigned ShiftElts = 0, InsertAtByte = 0;
9326   bool Swap = false;
9327 
9328   // Shifts required to get the byte we want at element 7.
9329   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9330                                    0, 15, 14, 13, 12, 11, 10, 9};
9331   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9332                                 1, 2,  3,  4,  5,  6,  7,  8};
9333 
9334   ArrayRef<int> Mask = N->getMask();
9335   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9336 
9337   // For each mask element, find out if we're just inserting something
9338   // from V2 into V1 or vice versa.
9339   // Possible permutations inserting an element from V2 into V1:
9340   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9341   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9342   //   ...
9343   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9344   // Inserting from V1 into V2 will be similar, except mask range will be
9345   // [16,31].
9346 
9347   bool FoundCandidate = false;
9348   // If both vector operands for the shuffle are the same vector, the mask
9349   // will contain only elements from the first one and the second one will be
9350   // undef.
9351   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9352   // Go through the mask of half-words to find an element that's being moved
9353   // from one vector to the other.
9354   for (unsigned i = 0; i < BytesInVector; ++i) {
9355     unsigned CurrentElement = Mask[i];
9356     // If 2nd operand is undefined, we should only look for element 7 in the
9357     // Mask.
9358     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9359       continue;
9360 
9361     bool OtherElementsInOrder = true;
9362     // Examine the other elements in the Mask to see if they're in original
9363     // order.
9364     for (unsigned j = 0; j < BytesInVector; ++j) {
9365       if (j == i)
9366         continue;
9367       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9368       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9369       // in which we always assume we're always picking from the 1st operand.
9370       int MaskOffset =
9371           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9372       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9373         OtherElementsInOrder = false;
9374         break;
9375       }
9376     }
9377     // If other elements are in original order, we record the number of shifts
9378     // we need to get the element we want into element 7. Also record which byte
9379     // in the vector we should insert into.
9380     if (OtherElementsInOrder) {
9381       // If 2nd operand is undefined, we assume no shifts and no swapping.
9382       if (V2.isUndef()) {
9383         ShiftElts = 0;
9384         Swap = false;
9385       } else {
9386         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9387         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9388                          : BigEndianShifts[CurrentElement & 0xF];
9389         Swap = CurrentElement < BytesInVector;
9390       }
9391       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9392       FoundCandidate = true;
9393       break;
9394     }
9395   }
9396 
9397   if (!FoundCandidate)
9398     return SDValue();
9399 
9400   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9401   // optionally with VECSHL if shift is required.
9402   if (Swap)
9403     std::swap(V1, V2);
9404   if (V2.isUndef())
9405     V2 = V1;
9406   if (ShiftElts) {
9407     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9408                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9409     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9410                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9411   }
9412   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9413                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9414 }
9415 
9416 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9417 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9418 /// SDValue.
9419 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9420                                            SelectionDAG &DAG) const {
9421   const unsigned NumHalfWords = 8;
9422   const unsigned BytesInVector = NumHalfWords * 2;
9423   // Check that the shuffle is on half-words.
9424   if (!isNByteElemShuffleMask(N, 2, 1))
9425     return SDValue();
9426 
9427   bool IsLE = Subtarget.isLittleEndian();
9428   SDLoc dl(N);
9429   SDValue V1 = N->getOperand(0);
9430   SDValue V2 = N->getOperand(1);
9431   unsigned ShiftElts = 0, InsertAtByte = 0;
9432   bool Swap = false;
9433 
9434   // Shifts required to get the half-word we want at element 3.
9435   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9436   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9437 
9438   uint32_t Mask = 0;
9439   uint32_t OriginalOrderLow = 0x1234567;
9440   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9441   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9442   // 32-bit space, only need 4-bit nibbles per element.
9443   for (unsigned i = 0; i < NumHalfWords; ++i) {
9444     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9445     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9446   }
9447 
9448   // For each mask element, find out if we're just inserting something
9449   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9450   // from V2 into V1:
9451   //   X, 1, 2, 3, 4, 5, 6, 7
9452   //   0, X, 2, 3, 4, 5, 6, 7
9453   //   0, 1, X, 3, 4, 5, 6, 7
9454   //   0, 1, 2, X, 4, 5, 6, 7
9455   //   0, 1, 2, 3, X, 5, 6, 7
9456   //   0, 1, 2, 3, 4, X, 6, 7
9457   //   0, 1, 2, 3, 4, 5, X, 7
9458   //   0, 1, 2, 3, 4, 5, 6, X
9459   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9460 
9461   bool FoundCandidate = false;
9462   // Go through the mask of half-words to find an element that's being moved
9463   // from one vector to the other.
9464   for (unsigned i = 0; i < NumHalfWords; ++i) {
9465     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9466     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9467     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9468     uint32_t TargetOrder = 0x0;
9469 
9470     // If both vector operands for the shuffle are the same vector, the mask
9471     // will contain only elements from the first one and the second one will be
9472     // undef.
9473     if (V2.isUndef()) {
9474       ShiftElts = 0;
9475       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9476       TargetOrder = OriginalOrderLow;
9477       Swap = false;
9478       // Skip if not the correct element or mask of other elements don't equal
9479       // to our expected order.
9480       if (MaskOneElt == VINSERTHSrcElem &&
9481           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9482         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9483         FoundCandidate = true;
9484         break;
9485       }
9486     } else { // If both operands are defined.
9487       // Target order is [8,15] if the current mask is between [0,7].
9488       TargetOrder =
9489           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9490       // Skip if mask of other elements don't equal our expected order.
9491       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9492         // We only need the last 3 bits for the number of shifts.
9493         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9494                          : BigEndianShifts[MaskOneElt & 0x7];
9495         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9496         Swap = MaskOneElt < NumHalfWords;
9497         FoundCandidate = true;
9498         break;
9499       }
9500     }
9501   }
9502 
9503   if (!FoundCandidate)
9504     return SDValue();
9505 
9506   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9507   // optionally with VECSHL if shift is required.
9508   if (Swap)
9509     std::swap(V1, V2);
9510   if (V2.isUndef())
9511     V2 = V1;
9512   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9513   if (ShiftElts) {
9514     // Double ShiftElts because we're left shifting on v16i8 type.
9515     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9516                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9517     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9518     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9519                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9520     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9521   }
9522   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9523   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9524                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9525   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9526 }
9527 
9528 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9529 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9530 /// return the code it can be lowered into.  Worst case, it can always be
9531 /// lowered into a vperm.
9532 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9533                                                SelectionDAG &DAG) const {
9534   SDLoc dl(Op);
9535   SDValue V1 = Op.getOperand(0);
9536   SDValue V2 = Op.getOperand(1);
9537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9538   EVT VT = Op.getValueType();
9539   bool isLittleEndian = Subtarget.isLittleEndian();
9540 
9541   unsigned ShiftElts, InsertAtByte;
9542   bool Swap = false;
9543 
9544   // If this is a load-and-splat, we can do that with a single instruction
9545   // in some cases. However if the load has multiple uses, we don't want to
9546   // combine it because that will just produce multiple loads.
9547   const SDValue *InputLoad = getNormalLoadInput(V1);
9548   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9549       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9550       InputLoad->hasOneUse()) {
9551     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9552     int SplatIdx =
9553       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9554 
9555     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9556     // For 4-byte load-and-splat, we need Power9.
9557     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9558       uint64_t Offset = 0;
9559       if (IsFourByte)
9560         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9561       else
9562         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9563       SDValue BasePtr = LD->getBasePtr();
9564       if (Offset != 0)
9565         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9566                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9567       SDValue Ops[] = {
9568         LD->getChain(),    // Chain
9569         BasePtr,           // BasePtr
9570         DAG.getValueType(Op.getValueType()) // VT
9571       };
9572       SDVTList VTL =
9573         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9574       SDValue LdSplt =
9575         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9576                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9577       if (LdSplt.getValueType() != SVOp->getValueType(0))
9578         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9579       return LdSplt;
9580     }
9581   }
9582   if (Subtarget.hasP9Vector() &&
9583       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9584                            isLittleEndian)) {
9585     if (Swap)
9586       std::swap(V1, V2);
9587     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9588     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9589     if (ShiftElts) {
9590       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9591                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9592       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9593                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9594       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9595     }
9596     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9597                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9598     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9599   }
9600 
9601   if (Subtarget.hasP9Altivec()) {
9602     SDValue NewISDNode;
9603     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9604       return NewISDNode;
9605 
9606     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9607       return NewISDNode;
9608   }
9609 
9610   if (Subtarget.hasVSX() &&
9611       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9612     if (Swap)
9613       std::swap(V1, V2);
9614     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9615     SDValue Conv2 =
9616         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9617 
9618     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9619                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9620     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9621   }
9622 
9623   if (Subtarget.hasVSX() &&
9624     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9625     if (Swap)
9626       std::swap(V1, V2);
9627     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9628     SDValue Conv2 =
9629         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9630 
9631     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9632                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9633     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9634   }
9635 
9636   if (Subtarget.hasP9Vector()) {
9637      if (PPC::isXXBRHShuffleMask(SVOp)) {
9638       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9639       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9640       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9641     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9642       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9643       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9644       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9645     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9646       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9647       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9648       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9649     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9650       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9651       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9652       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9653     }
9654   }
9655 
9656   if (Subtarget.hasVSX()) {
9657     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9658       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9659 
9660       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9661       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9662                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9663       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9664     }
9665 
9666     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9667     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9668       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9669       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9670       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9671     }
9672   }
9673 
9674   if (Subtarget.hasQPX()) {
9675     if (VT.getVectorNumElements() != 4)
9676       return SDValue();
9677 
9678     if (V2.isUndef()) V2 = V1;
9679 
9680     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9681     if (AlignIdx != -1) {
9682       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9683                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9684     } else if (SVOp->isSplat()) {
9685       int SplatIdx = SVOp->getSplatIndex();
9686       if (SplatIdx >= 4) {
9687         std::swap(V1, V2);
9688         SplatIdx -= 4;
9689       }
9690 
9691       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9692                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9693     }
9694 
9695     // Lower this into a qvgpci/qvfperm pair.
9696 
9697     // Compute the qvgpci literal
9698     unsigned idx = 0;
9699     for (unsigned i = 0; i < 4; ++i) {
9700       int m = SVOp->getMaskElt(i);
9701       unsigned mm = m >= 0 ? (unsigned) m : i;
9702       idx |= mm << (3-i)*3;
9703     }
9704 
9705     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9706                              DAG.getConstant(idx, dl, MVT::i32));
9707     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9708   }
9709 
9710   // Cases that are handled by instructions that take permute immediates
9711   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9712   // selected by the instruction selector.
9713   if (V2.isUndef()) {
9714     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9715         PPC::isSplatShuffleMask(SVOp, 2) ||
9716         PPC::isSplatShuffleMask(SVOp, 4) ||
9717         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9718         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9719         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9720         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9721         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9722         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9723         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9724         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9725         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9726         (Subtarget.hasP8Altivec() && (
9727          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9728          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9729          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9730       return Op;
9731     }
9732   }
9733 
9734   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9735   // and produce a fixed permutation.  If any of these match, do not lower to
9736   // VPERM.
9737   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9738   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9739       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9740       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9741       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9742       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9743       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9744       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9745       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9746       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9747       (Subtarget.hasP8Altivec() && (
9748        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9749        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9750        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9751     return Op;
9752 
9753   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9754   // perfect shuffle table to emit an optimal matching sequence.
9755   ArrayRef<int> PermMask = SVOp->getMask();
9756 
9757   unsigned PFIndexes[4];
9758   bool isFourElementShuffle = true;
9759   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9760     unsigned EltNo = 8;   // Start out undef.
9761     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9762       if (PermMask[i*4+j] < 0)
9763         continue;   // Undef, ignore it.
9764 
9765       unsigned ByteSource = PermMask[i*4+j];
9766       if ((ByteSource & 3) != j) {
9767         isFourElementShuffle = false;
9768         break;
9769       }
9770 
9771       if (EltNo == 8) {
9772         EltNo = ByteSource/4;
9773       } else if (EltNo != ByteSource/4) {
9774         isFourElementShuffle = false;
9775         break;
9776       }
9777     }
9778     PFIndexes[i] = EltNo;
9779   }
9780 
9781   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9782   // perfect shuffle vector to determine if it is cost effective to do this as
9783   // discrete instructions, or whether we should use a vperm.
9784   // For now, we skip this for little endian until such time as we have a
9785   // little-endian perfect shuffle table.
9786   if (isFourElementShuffle && !isLittleEndian) {
9787     // Compute the index in the perfect shuffle table.
9788     unsigned PFTableIndex =
9789       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9790 
9791     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9792     unsigned Cost  = (PFEntry >> 30);
9793 
9794     // Determining when to avoid vperm is tricky.  Many things affect the cost
9795     // of vperm, particularly how many times the perm mask needs to be computed.
9796     // For example, if the perm mask can be hoisted out of a loop or is already
9797     // used (perhaps because there are multiple permutes with the same shuffle
9798     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9799     // the loop requires an extra register.
9800     //
9801     // As a compromise, we only emit discrete instructions if the shuffle can be
9802     // generated in 3 or fewer operations.  When we have loop information
9803     // available, if this block is within a loop, we should avoid using vperm
9804     // for 3-operation perms and use a constant pool load instead.
9805     if (Cost < 3)
9806       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9807   }
9808 
9809   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9810   // vector that will get spilled to the constant pool.
9811   if (V2.isUndef()) V2 = V1;
9812 
9813   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9814   // that it is in input element units, not in bytes.  Convert now.
9815 
9816   // For little endian, the order of the input vectors is reversed, and
9817   // the permutation mask is complemented with respect to 31.  This is
9818   // necessary to produce proper semantics with the big-endian-biased vperm
9819   // instruction.
9820   EVT EltVT = V1.getValueType().getVectorElementType();
9821   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9822 
9823   SmallVector<SDValue, 16> ResultMask;
9824   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9825     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9826 
9827     for (unsigned j = 0; j != BytesPerElement; ++j)
9828       if (isLittleEndian)
9829         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9830                                              dl, MVT::i32));
9831       else
9832         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9833                                              MVT::i32));
9834   }
9835 
9836   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9837   if (isLittleEndian)
9838     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9839                        V2, V1, VPermMask);
9840   else
9841     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9842                        V1, V2, VPermMask);
9843 }
9844 
9845 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9846 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9847 /// information about the intrinsic.
9848 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9849                                  bool &isDot, const PPCSubtarget &Subtarget) {
9850   unsigned IntrinsicID =
9851       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9852   CompareOpc = -1;
9853   isDot = false;
9854   switch (IntrinsicID) {
9855   default:
9856     return false;
9857   // Comparison predicates.
9858   case Intrinsic::ppc_altivec_vcmpbfp_p:
9859     CompareOpc = 966;
9860     isDot = true;
9861     break;
9862   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9863     CompareOpc = 198;
9864     isDot = true;
9865     break;
9866   case Intrinsic::ppc_altivec_vcmpequb_p:
9867     CompareOpc = 6;
9868     isDot = true;
9869     break;
9870   case Intrinsic::ppc_altivec_vcmpequh_p:
9871     CompareOpc = 70;
9872     isDot = true;
9873     break;
9874   case Intrinsic::ppc_altivec_vcmpequw_p:
9875     CompareOpc = 134;
9876     isDot = true;
9877     break;
9878   case Intrinsic::ppc_altivec_vcmpequd_p:
9879     if (Subtarget.hasP8Altivec()) {
9880       CompareOpc = 199;
9881       isDot = true;
9882     } else
9883       return false;
9884     break;
9885   case Intrinsic::ppc_altivec_vcmpneb_p:
9886   case Intrinsic::ppc_altivec_vcmpneh_p:
9887   case Intrinsic::ppc_altivec_vcmpnew_p:
9888   case Intrinsic::ppc_altivec_vcmpnezb_p:
9889   case Intrinsic::ppc_altivec_vcmpnezh_p:
9890   case Intrinsic::ppc_altivec_vcmpnezw_p:
9891     if (Subtarget.hasP9Altivec()) {
9892       switch (IntrinsicID) {
9893       default:
9894         llvm_unreachable("Unknown comparison intrinsic.");
9895       case Intrinsic::ppc_altivec_vcmpneb_p:
9896         CompareOpc = 7;
9897         break;
9898       case Intrinsic::ppc_altivec_vcmpneh_p:
9899         CompareOpc = 71;
9900         break;
9901       case Intrinsic::ppc_altivec_vcmpnew_p:
9902         CompareOpc = 135;
9903         break;
9904       case Intrinsic::ppc_altivec_vcmpnezb_p:
9905         CompareOpc = 263;
9906         break;
9907       case Intrinsic::ppc_altivec_vcmpnezh_p:
9908         CompareOpc = 327;
9909         break;
9910       case Intrinsic::ppc_altivec_vcmpnezw_p:
9911         CompareOpc = 391;
9912         break;
9913       }
9914       isDot = true;
9915     } else
9916       return false;
9917     break;
9918   case Intrinsic::ppc_altivec_vcmpgefp_p:
9919     CompareOpc = 454;
9920     isDot = true;
9921     break;
9922   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9923     CompareOpc = 710;
9924     isDot = true;
9925     break;
9926   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9927     CompareOpc = 774;
9928     isDot = true;
9929     break;
9930   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9931     CompareOpc = 838;
9932     isDot = true;
9933     break;
9934   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9935     CompareOpc = 902;
9936     isDot = true;
9937     break;
9938   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9939     if (Subtarget.hasP8Altivec()) {
9940       CompareOpc = 967;
9941       isDot = true;
9942     } else
9943       return false;
9944     break;
9945   case Intrinsic::ppc_altivec_vcmpgtub_p:
9946     CompareOpc = 518;
9947     isDot = true;
9948     break;
9949   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9950     CompareOpc = 582;
9951     isDot = true;
9952     break;
9953   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9954     CompareOpc = 646;
9955     isDot = true;
9956     break;
9957   case Intrinsic::ppc_altivec_vcmpgtud_p:
9958     if (Subtarget.hasP8Altivec()) {
9959       CompareOpc = 711;
9960       isDot = true;
9961     } else
9962       return false;
9963     break;
9964 
9965   // VSX predicate comparisons use the same infrastructure
9966   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9967   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9968   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9969   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9970   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9971   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9972     if (Subtarget.hasVSX()) {
9973       switch (IntrinsicID) {
9974       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9975         CompareOpc = 99;
9976         break;
9977       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9978         CompareOpc = 115;
9979         break;
9980       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9981         CompareOpc = 107;
9982         break;
9983       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9984         CompareOpc = 67;
9985         break;
9986       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9987         CompareOpc = 83;
9988         break;
9989       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9990         CompareOpc = 75;
9991         break;
9992       }
9993       isDot = true;
9994     } else
9995       return false;
9996     break;
9997 
9998   // Normal Comparisons.
9999   case Intrinsic::ppc_altivec_vcmpbfp:
10000     CompareOpc = 966;
10001     break;
10002   case Intrinsic::ppc_altivec_vcmpeqfp:
10003     CompareOpc = 198;
10004     break;
10005   case Intrinsic::ppc_altivec_vcmpequb:
10006     CompareOpc = 6;
10007     break;
10008   case Intrinsic::ppc_altivec_vcmpequh:
10009     CompareOpc = 70;
10010     break;
10011   case Intrinsic::ppc_altivec_vcmpequw:
10012     CompareOpc = 134;
10013     break;
10014   case Intrinsic::ppc_altivec_vcmpequd:
10015     if (Subtarget.hasP8Altivec())
10016       CompareOpc = 199;
10017     else
10018       return false;
10019     break;
10020   case Intrinsic::ppc_altivec_vcmpneb:
10021   case Intrinsic::ppc_altivec_vcmpneh:
10022   case Intrinsic::ppc_altivec_vcmpnew:
10023   case Intrinsic::ppc_altivec_vcmpnezb:
10024   case Intrinsic::ppc_altivec_vcmpnezh:
10025   case Intrinsic::ppc_altivec_vcmpnezw:
10026     if (Subtarget.hasP9Altivec())
10027       switch (IntrinsicID) {
10028       default:
10029         llvm_unreachable("Unknown comparison intrinsic.");
10030       case Intrinsic::ppc_altivec_vcmpneb:
10031         CompareOpc = 7;
10032         break;
10033       case Intrinsic::ppc_altivec_vcmpneh:
10034         CompareOpc = 71;
10035         break;
10036       case Intrinsic::ppc_altivec_vcmpnew:
10037         CompareOpc = 135;
10038         break;
10039       case Intrinsic::ppc_altivec_vcmpnezb:
10040         CompareOpc = 263;
10041         break;
10042       case Intrinsic::ppc_altivec_vcmpnezh:
10043         CompareOpc = 327;
10044         break;
10045       case Intrinsic::ppc_altivec_vcmpnezw:
10046         CompareOpc = 391;
10047         break;
10048       }
10049     else
10050       return false;
10051     break;
10052   case Intrinsic::ppc_altivec_vcmpgefp:
10053     CompareOpc = 454;
10054     break;
10055   case Intrinsic::ppc_altivec_vcmpgtfp:
10056     CompareOpc = 710;
10057     break;
10058   case Intrinsic::ppc_altivec_vcmpgtsb:
10059     CompareOpc = 774;
10060     break;
10061   case Intrinsic::ppc_altivec_vcmpgtsh:
10062     CompareOpc = 838;
10063     break;
10064   case Intrinsic::ppc_altivec_vcmpgtsw:
10065     CompareOpc = 902;
10066     break;
10067   case Intrinsic::ppc_altivec_vcmpgtsd:
10068     if (Subtarget.hasP8Altivec())
10069       CompareOpc = 967;
10070     else
10071       return false;
10072     break;
10073   case Intrinsic::ppc_altivec_vcmpgtub:
10074     CompareOpc = 518;
10075     break;
10076   case Intrinsic::ppc_altivec_vcmpgtuh:
10077     CompareOpc = 582;
10078     break;
10079   case Intrinsic::ppc_altivec_vcmpgtuw:
10080     CompareOpc = 646;
10081     break;
10082   case Intrinsic::ppc_altivec_vcmpgtud:
10083     if (Subtarget.hasP8Altivec())
10084       CompareOpc = 711;
10085     else
10086       return false;
10087     break;
10088   }
10089   return true;
10090 }
10091 
10092 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10093 /// lower, do it, otherwise return null.
10094 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10095                                                    SelectionDAG &DAG) const {
10096   unsigned IntrinsicID =
10097     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10098 
10099   SDLoc dl(Op);
10100 
10101   if (IntrinsicID == Intrinsic::thread_pointer) {
10102     // Reads the thread pointer register, used for __builtin_thread_pointer.
10103     if (Subtarget.isPPC64())
10104       return DAG.getRegister(PPC::X13, MVT::i64);
10105     return DAG.getRegister(PPC::R2, MVT::i32);
10106   }
10107 
10108   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10109   // opcode number of the comparison.
10110   int CompareOpc;
10111   bool isDot;
10112   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10113     return SDValue();    // Don't custom lower most intrinsics.
10114 
10115   // If this is a non-dot comparison, make the VCMP node and we are done.
10116   if (!isDot) {
10117     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10118                               Op.getOperand(1), Op.getOperand(2),
10119                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10120     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10121   }
10122 
10123   // Create the PPCISD altivec 'dot' comparison node.
10124   SDValue Ops[] = {
10125     Op.getOperand(2),  // LHS
10126     Op.getOperand(3),  // RHS
10127     DAG.getConstant(CompareOpc, dl, MVT::i32)
10128   };
10129   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10130   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10131 
10132   // Now that we have the comparison, emit a copy from the CR to a GPR.
10133   // This is flagged to the above dot comparison.
10134   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10135                                 DAG.getRegister(PPC::CR6, MVT::i32),
10136                                 CompNode.getValue(1));
10137 
10138   // Unpack the result based on how the target uses it.
10139   unsigned BitNo;   // Bit # of CR6.
10140   bool InvertBit;   // Invert result?
10141   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10142   default:  // Can't happen, don't crash on invalid number though.
10143   case 0:   // Return the value of the EQ bit of CR6.
10144     BitNo = 0; InvertBit = false;
10145     break;
10146   case 1:   // Return the inverted value of the EQ bit of CR6.
10147     BitNo = 0; InvertBit = true;
10148     break;
10149   case 2:   // Return the value of the LT bit of CR6.
10150     BitNo = 2; InvertBit = false;
10151     break;
10152   case 3:   // Return the inverted value of the LT bit of CR6.
10153     BitNo = 2; InvertBit = true;
10154     break;
10155   }
10156 
10157   // Shift the bit into the low position.
10158   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10159                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10160   // Isolate the bit.
10161   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10162                       DAG.getConstant(1, dl, MVT::i32));
10163 
10164   // If we are supposed to, toggle the bit.
10165   if (InvertBit)
10166     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10167                         DAG.getConstant(1, dl, MVT::i32));
10168   return Flags;
10169 }
10170 
10171 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10172                                                SelectionDAG &DAG) const {
10173   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10174   // the beginning of the argument list.
10175   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10176   SDLoc DL(Op);
10177   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10178   case Intrinsic::ppc_cfence: {
10179     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10180     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10181     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10182                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10183                                                   Op.getOperand(ArgStart + 1)),
10184                                       Op.getOperand(0)),
10185                    0);
10186   }
10187   default:
10188     break;
10189   }
10190   return SDValue();
10191 }
10192 
10193 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10194   // Check for a DIV with the same operands as this REM.
10195   for (auto UI : Op.getOperand(1)->uses()) {
10196     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10197         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10198       if (UI->getOperand(0) == Op.getOperand(0) &&
10199           UI->getOperand(1) == Op.getOperand(1))
10200         return SDValue();
10201   }
10202   return Op;
10203 }
10204 
10205 // Lower scalar BSWAP64 to xxbrd.
10206 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10207   SDLoc dl(Op);
10208   // MTVSRDD
10209   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10210                    Op.getOperand(0));
10211   // XXBRD
10212   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10213   // MFVSRD
10214   int VectorIndex = 0;
10215   if (Subtarget.isLittleEndian())
10216     VectorIndex = 1;
10217   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10218                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10219   return Op;
10220 }
10221 
10222 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10223 // compared to a value that is atomically loaded (atomic loads zero-extend).
10224 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10225                                                 SelectionDAG &DAG) const {
10226   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10227          "Expecting an atomic compare-and-swap here.");
10228   SDLoc dl(Op);
10229   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10230   EVT MemVT = AtomicNode->getMemoryVT();
10231   if (MemVT.getSizeInBits() >= 32)
10232     return Op;
10233 
10234   SDValue CmpOp = Op.getOperand(2);
10235   // If this is already correctly zero-extended, leave it alone.
10236   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10237   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10238     return Op;
10239 
10240   // Clear the high bits of the compare operand.
10241   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10242   SDValue NewCmpOp =
10243     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10244                 DAG.getConstant(MaskVal, dl, MVT::i32));
10245 
10246   // Replace the existing compare operand with the properly zero-extended one.
10247   SmallVector<SDValue, 4> Ops;
10248   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10249     Ops.push_back(AtomicNode->getOperand(i));
10250   Ops[2] = NewCmpOp;
10251   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10252   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10253   auto NodeTy =
10254     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10255   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10256 }
10257 
10258 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10259                                                  SelectionDAG &DAG) const {
10260   SDLoc dl(Op);
10261   // Create a stack slot that is 16-byte aligned.
10262   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10263   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10264   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10265   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10266 
10267   // Store the input value into Value#0 of the stack slot.
10268   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10269                                MachinePointerInfo());
10270   // Load it out.
10271   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10272 }
10273 
10274 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10275                                                   SelectionDAG &DAG) const {
10276   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10277          "Should only be called for ISD::INSERT_VECTOR_ELT");
10278 
10279   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10280   // We have legal lowering for constant indices but not for variable ones.
10281   if (!C)
10282     return SDValue();
10283 
10284   EVT VT = Op.getValueType();
10285   SDLoc dl(Op);
10286   SDValue V1 = Op.getOperand(0);
10287   SDValue V2 = Op.getOperand(1);
10288   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10289   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10290     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10291     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10292     unsigned InsertAtElement = C->getZExtValue();
10293     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10294     if (Subtarget.isLittleEndian()) {
10295       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10296     }
10297     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10298                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10299   }
10300   return Op;
10301 }
10302 
10303 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10304                                                    SelectionDAG &DAG) const {
10305   SDLoc dl(Op);
10306   SDNode *N = Op.getNode();
10307 
10308   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10309          "Unknown extract_vector_elt type");
10310 
10311   SDValue Value = N->getOperand(0);
10312 
10313   // The first part of this is like the store lowering except that we don't
10314   // need to track the chain.
10315 
10316   // The values are now known to be -1 (false) or 1 (true). To convert this
10317   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10318   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10319   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10320 
10321   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10322   // understand how to form the extending load.
10323   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10324 
10325   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10326 
10327   // Now convert to an integer and store.
10328   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10329     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10330     Value);
10331 
10332   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10333   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10334   MachinePointerInfo PtrInfo =
10335       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10336   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10337   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10338 
10339   SDValue StoreChain = DAG.getEntryNode();
10340   SDValue Ops[] = {StoreChain,
10341                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10342                    Value, FIdx};
10343   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10344 
10345   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10346     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10347 
10348   // Extract the value requested.
10349   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10350   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10351   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10352 
10353   SDValue IntVal =
10354       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10355 
10356   if (!Subtarget.useCRBits())
10357     return IntVal;
10358 
10359   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10360 }
10361 
10362 /// Lowering for QPX v4i1 loads
10363 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10364                                            SelectionDAG &DAG) const {
10365   SDLoc dl(Op);
10366   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10367   SDValue LoadChain = LN->getChain();
10368   SDValue BasePtr = LN->getBasePtr();
10369 
10370   if (Op.getValueType() == MVT::v4f64 ||
10371       Op.getValueType() == MVT::v4f32) {
10372     EVT MemVT = LN->getMemoryVT();
10373     unsigned Alignment = LN->getAlignment();
10374 
10375     // If this load is properly aligned, then it is legal.
10376     if (Alignment >= MemVT.getStoreSize())
10377       return Op;
10378 
10379     EVT ScalarVT = Op.getValueType().getScalarType(),
10380         ScalarMemVT = MemVT.getScalarType();
10381     unsigned Stride = ScalarMemVT.getStoreSize();
10382 
10383     SDValue Vals[4], LoadChains[4];
10384     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10385       SDValue Load;
10386       if (ScalarVT != ScalarMemVT)
10387         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10388                               BasePtr,
10389                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10390                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10391                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10392       else
10393         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10394                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10395                            MinAlign(Alignment, Idx * Stride),
10396                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10397 
10398       if (Idx == 0 && LN->isIndexed()) {
10399         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10400                "Unknown addressing mode on vector load");
10401         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10402                                   LN->getAddressingMode());
10403       }
10404 
10405       Vals[Idx] = Load;
10406       LoadChains[Idx] = Load.getValue(1);
10407 
10408       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10409                             DAG.getConstant(Stride, dl,
10410                                             BasePtr.getValueType()));
10411     }
10412 
10413     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10414     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10415 
10416     if (LN->isIndexed()) {
10417       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10418       return DAG.getMergeValues(RetOps, dl);
10419     }
10420 
10421     SDValue RetOps[] = { Value, TF };
10422     return DAG.getMergeValues(RetOps, dl);
10423   }
10424 
10425   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10426   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10427 
10428   // To lower v4i1 from a byte array, we load the byte elements of the
10429   // vector and then reuse the BUILD_VECTOR logic.
10430 
10431   SDValue VectElmts[4], VectElmtChains[4];
10432   for (unsigned i = 0; i < 4; ++i) {
10433     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10434     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10435 
10436     VectElmts[i] = DAG.getExtLoad(
10437         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10438         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10439         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10440     VectElmtChains[i] = VectElmts[i].getValue(1);
10441   }
10442 
10443   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10444   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10445 
10446   SDValue RVals[] = { Value, LoadChain };
10447   return DAG.getMergeValues(RVals, dl);
10448 }
10449 
10450 /// Lowering for QPX v4i1 stores
10451 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10452                                             SelectionDAG &DAG) const {
10453   SDLoc dl(Op);
10454   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10455   SDValue StoreChain = SN->getChain();
10456   SDValue BasePtr = SN->getBasePtr();
10457   SDValue Value = SN->getValue();
10458 
10459   if (Value.getValueType() == MVT::v4f64 ||
10460       Value.getValueType() == MVT::v4f32) {
10461     EVT MemVT = SN->getMemoryVT();
10462     unsigned Alignment = SN->getAlignment();
10463 
10464     // If this store is properly aligned, then it is legal.
10465     if (Alignment >= MemVT.getStoreSize())
10466       return Op;
10467 
10468     EVT ScalarVT = Value.getValueType().getScalarType(),
10469         ScalarMemVT = MemVT.getScalarType();
10470     unsigned Stride = ScalarMemVT.getStoreSize();
10471 
10472     SDValue Stores[4];
10473     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10474       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10475                                DAG.getVectorIdxConstant(Idx, dl));
10476       SDValue Store;
10477       if (ScalarVT != ScalarMemVT)
10478         Store =
10479             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10480                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10481                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10482                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10483       else
10484         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10485                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10486                              MinAlign(Alignment, Idx * Stride),
10487                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10488 
10489       if (Idx == 0 && SN->isIndexed()) {
10490         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10491                "Unknown addressing mode on vector store");
10492         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10493                                     SN->getAddressingMode());
10494       }
10495 
10496       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10497                             DAG.getConstant(Stride, dl,
10498                                             BasePtr.getValueType()));
10499       Stores[Idx] = Store;
10500     }
10501 
10502     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10503 
10504     if (SN->isIndexed()) {
10505       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10506       return DAG.getMergeValues(RetOps, dl);
10507     }
10508 
10509     return TF;
10510   }
10511 
10512   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10513   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10514 
10515   // The values are now known to be -1 (false) or 1 (true). To convert this
10516   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10517   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10518   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10519 
10520   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10521   // understand how to form the extending load.
10522   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10523 
10524   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10525 
10526   // Now convert to an integer and store.
10527   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10528     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10529     Value);
10530 
10531   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10532   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10533   MachinePointerInfo PtrInfo =
10534       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10535   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10536   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10537 
10538   SDValue Ops[] = {StoreChain,
10539                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10540                    Value, FIdx};
10541   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10542 
10543   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10544     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10545 
10546   // Move data into the byte array.
10547   SDValue Loads[4], LoadChains[4];
10548   for (unsigned i = 0; i < 4; ++i) {
10549     unsigned Offset = 4*i;
10550     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10551     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10552 
10553     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10554                            PtrInfo.getWithOffset(Offset));
10555     LoadChains[i] = Loads[i].getValue(1);
10556   }
10557 
10558   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10559 
10560   SDValue Stores[4];
10561   for (unsigned i = 0; i < 4; ++i) {
10562     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10563     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10564 
10565     Stores[i] = DAG.getTruncStore(
10566         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10567         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10568         SN->getAAInfo());
10569   }
10570 
10571   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10572 
10573   return StoreChain;
10574 }
10575 
10576 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10577   SDLoc dl(Op);
10578   if (Op.getValueType() == MVT::v4i32) {
10579     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10580 
10581     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10582     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10583 
10584     SDValue RHSSwap =   // = vrlw RHS, 16
10585       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10586 
10587     // Shrinkify inputs to v8i16.
10588     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10589     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10590     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10591 
10592     // Low parts multiplied together, generating 32-bit results (we ignore the
10593     // top parts).
10594     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10595                                         LHS, RHS, DAG, dl, MVT::v4i32);
10596 
10597     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10598                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10599     // Shift the high parts up 16 bits.
10600     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10601                               Neg16, DAG, dl);
10602     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10603   } else if (Op.getValueType() == MVT::v16i8) {
10604     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10605     bool isLittleEndian = Subtarget.isLittleEndian();
10606 
10607     // Multiply the even 8-bit parts, producing 16-bit sums.
10608     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10609                                            LHS, RHS, DAG, dl, MVT::v8i16);
10610     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10611 
10612     // Multiply the odd 8-bit parts, producing 16-bit sums.
10613     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10614                                           LHS, RHS, DAG, dl, MVT::v8i16);
10615     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10616 
10617     // Merge the results together.  Because vmuleub and vmuloub are
10618     // instructions with a big-endian bias, we must reverse the
10619     // element numbering and reverse the meaning of "odd" and "even"
10620     // when generating little endian code.
10621     int Ops[16];
10622     for (unsigned i = 0; i != 8; ++i) {
10623       if (isLittleEndian) {
10624         Ops[i*2  ] = 2*i;
10625         Ops[i*2+1] = 2*i+16;
10626       } else {
10627         Ops[i*2  ] = 2*i+1;
10628         Ops[i*2+1] = 2*i+1+16;
10629       }
10630     }
10631     if (isLittleEndian)
10632       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10633     else
10634       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10635   } else {
10636     llvm_unreachable("Unknown mul to lower!");
10637   }
10638 }
10639 
10640 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10641 
10642   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10643 
10644   EVT VT = Op.getValueType();
10645   assert(VT.isVector() &&
10646          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10647   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10648           VT == MVT::v16i8) &&
10649          "Unexpected vector element type!");
10650   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10651          "Current subtarget doesn't support smax v2i64!");
10652 
10653   // For vector abs, it can be lowered to:
10654   // abs x
10655   // ==>
10656   // y = -x
10657   // smax(x, y)
10658 
10659   SDLoc dl(Op);
10660   SDValue X = Op.getOperand(0);
10661   SDValue Zero = DAG.getConstant(0, dl, VT);
10662   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10663 
10664   // SMAX patch https://reviews.llvm.org/D47332
10665   // hasn't landed yet, so use intrinsic first here.
10666   // TODO: Should use SMAX directly once SMAX patch landed
10667   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10668   if (VT == MVT::v2i64)
10669     BifID = Intrinsic::ppc_altivec_vmaxsd;
10670   else if (VT == MVT::v8i16)
10671     BifID = Intrinsic::ppc_altivec_vmaxsh;
10672   else if (VT == MVT::v16i8)
10673     BifID = Intrinsic::ppc_altivec_vmaxsb;
10674 
10675   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10676 }
10677 
10678 // Custom lowering for fpext vf32 to v2f64
10679 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10680 
10681   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10682          "Should only be called for ISD::FP_EXTEND");
10683 
10684   // We only want to custom lower an extend from v2f32 to v2f64.
10685   if (Op.getValueType() != MVT::v2f64 ||
10686       Op.getOperand(0).getValueType() != MVT::v2f32)
10687     return SDValue();
10688 
10689   SDLoc dl(Op);
10690   SDValue Op0 = Op.getOperand(0);
10691 
10692   switch (Op0.getOpcode()) {
10693   default:
10694     return SDValue();
10695   case ISD::EXTRACT_SUBVECTOR: {
10696     assert(Op0.getNumOperands() == 2 &&
10697            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10698            "Node should have 2 operands with second one being a constant!");
10699 
10700     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10701       return SDValue();
10702 
10703     // Custom lower is only done for high or low doubleword.
10704     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10705     if (Idx % 2 != 0)
10706       return SDValue();
10707 
10708     // Since input is v4f32, at this point Idx is either 0 or 2.
10709     // Shift to get the doubleword position we want.
10710     int DWord = Idx >> 1;
10711 
10712     // High and low word positions are different on little endian.
10713     if (Subtarget.isLittleEndian())
10714       DWord ^= 0x1;
10715 
10716     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10717                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10718   }
10719   case ISD::FADD:
10720   case ISD::FMUL:
10721   case ISD::FSUB: {
10722     SDValue NewLoad[2];
10723     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10724       // Ensure both input are loads.
10725       SDValue LdOp = Op0.getOperand(i);
10726       if (LdOp.getOpcode() != ISD::LOAD)
10727         return SDValue();
10728       // Generate new load node.
10729       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10730       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10731       NewLoad[i] = DAG.getMemIntrinsicNode(
10732           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10733           LD->getMemoryVT(), LD->getMemOperand());
10734     }
10735     SDValue NewOp =
10736         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10737                     NewLoad[1], Op0.getNode()->getFlags());
10738     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10739                        DAG.getConstant(0, dl, MVT::i32));
10740   }
10741   case ISD::LOAD: {
10742     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10743     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10744     SDValue NewLd = DAG.getMemIntrinsicNode(
10745         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10746         LD->getMemoryVT(), LD->getMemOperand());
10747     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10748                        DAG.getConstant(0, dl, MVT::i32));
10749   }
10750   }
10751   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10752 }
10753 
10754 /// LowerOperation - Provide custom lowering hooks for some operations.
10755 ///
10756 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10757   switch (Op.getOpcode()) {
10758   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10759   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10760   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10761   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10762   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10763   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10764   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10765   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10766   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10767 
10768   // Variable argument lowering.
10769   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10770   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10771   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10772 
10773   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10774   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10775   case ISD::GET_DYNAMIC_AREA_OFFSET:
10776     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10777 
10778   // Exception handling lowering.
10779   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10780   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10781   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10782 
10783   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10784   case ISD::STORE:              return LowerSTORE(Op, DAG);
10785   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10786   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10787   case ISD::FP_TO_UINT:
10788   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10789   case ISD::UINT_TO_FP:
10790   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10791   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10792 
10793   // Lower 64-bit shifts.
10794   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10795   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10796   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10797 
10798   // Vector-related lowering.
10799   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10800   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10801   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10802   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10803   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10804   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10805   case ISD::MUL:                return LowerMUL(Op, DAG);
10806   case ISD::ABS:                return LowerABS(Op, DAG);
10807   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10808 
10809   // For counter-based loop handling.
10810   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10811 
10812   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10813 
10814   // Frame & Return address.
10815   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10816   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10817 
10818   case ISD::INTRINSIC_VOID:
10819     return LowerINTRINSIC_VOID(Op, DAG);
10820   case ISD::SREM:
10821   case ISD::UREM:
10822     return LowerREM(Op, DAG);
10823   case ISD::BSWAP:
10824     return LowerBSWAP(Op, DAG);
10825   case ISD::ATOMIC_CMP_SWAP:
10826     return LowerATOMIC_CMP_SWAP(Op, DAG);
10827   }
10828 }
10829 
10830 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10831                                            SmallVectorImpl<SDValue>&Results,
10832                                            SelectionDAG &DAG) const {
10833   SDLoc dl(N);
10834   switch (N->getOpcode()) {
10835   default:
10836     llvm_unreachable("Do not know how to custom type legalize this operation!");
10837   case ISD::READCYCLECOUNTER: {
10838     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10839     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10840 
10841     Results.push_back(
10842         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10843     Results.push_back(RTB.getValue(2));
10844     break;
10845   }
10846   case ISD::INTRINSIC_W_CHAIN: {
10847     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10848         Intrinsic::loop_decrement)
10849       break;
10850 
10851     assert(N->getValueType(0) == MVT::i1 &&
10852            "Unexpected result type for CTR decrement intrinsic");
10853     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10854                                  N->getValueType(0));
10855     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10856     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10857                                  N->getOperand(1));
10858 
10859     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10860     Results.push_back(NewInt.getValue(1));
10861     break;
10862   }
10863   case ISD::VAARG: {
10864     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10865       return;
10866 
10867     EVT VT = N->getValueType(0);
10868 
10869     if (VT == MVT::i64) {
10870       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10871 
10872       Results.push_back(NewNode);
10873       Results.push_back(NewNode.getValue(1));
10874     }
10875     return;
10876   }
10877   case ISD::FP_TO_SINT:
10878   case ISD::FP_TO_UINT:
10879     // LowerFP_TO_INT() can only handle f32 and f64.
10880     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10881       return;
10882     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10883     return;
10884   case ISD::TRUNCATE: {
10885     EVT TrgVT = N->getValueType(0);
10886     EVT OpVT = N->getOperand(0).getValueType();
10887     if (TrgVT.isVector() &&
10888         isOperationCustom(N->getOpcode(), TrgVT) &&
10889         OpVT.getSizeInBits() <= 128 &&
10890         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10891       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10892     return;
10893   }
10894   case ISD::BITCAST:
10895     // Don't handle bitcast here.
10896     return;
10897   }
10898 }
10899 
10900 //===----------------------------------------------------------------------===//
10901 //  Other Lowering Code
10902 //===----------------------------------------------------------------------===//
10903 
10904 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10905   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10906   Function *Func = Intrinsic::getDeclaration(M, Id);
10907   return Builder.CreateCall(Func, {});
10908 }
10909 
10910 // The mappings for emitLeading/TrailingFence is taken from
10911 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10912 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10913                                                  Instruction *Inst,
10914                                                  AtomicOrdering Ord) const {
10915   if (Ord == AtomicOrdering::SequentiallyConsistent)
10916     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10917   if (isReleaseOrStronger(Ord))
10918     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10919   return nullptr;
10920 }
10921 
10922 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10923                                                   Instruction *Inst,
10924                                                   AtomicOrdering Ord) const {
10925   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10926     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10927     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10928     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10929     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10930       return Builder.CreateCall(
10931           Intrinsic::getDeclaration(
10932               Builder.GetInsertBlock()->getParent()->getParent(),
10933               Intrinsic::ppc_cfence, {Inst->getType()}),
10934           {Inst});
10935     // FIXME: Can use isync for rmw operation.
10936     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10937   }
10938   return nullptr;
10939 }
10940 
10941 MachineBasicBlock *
10942 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10943                                     unsigned AtomicSize,
10944                                     unsigned BinOpcode,
10945                                     unsigned CmpOpcode,
10946                                     unsigned CmpPred) const {
10947   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10948   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10949 
10950   auto LoadMnemonic = PPC::LDARX;
10951   auto StoreMnemonic = PPC::STDCX;
10952   switch (AtomicSize) {
10953   default:
10954     llvm_unreachable("Unexpected size of atomic entity");
10955   case 1:
10956     LoadMnemonic = PPC::LBARX;
10957     StoreMnemonic = PPC::STBCX;
10958     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10959     break;
10960   case 2:
10961     LoadMnemonic = PPC::LHARX;
10962     StoreMnemonic = PPC::STHCX;
10963     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10964     break;
10965   case 4:
10966     LoadMnemonic = PPC::LWARX;
10967     StoreMnemonic = PPC::STWCX;
10968     break;
10969   case 8:
10970     LoadMnemonic = PPC::LDARX;
10971     StoreMnemonic = PPC::STDCX;
10972     break;
10973   }
10974 
10975   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10976   MachineFunction *F = BB->getParent();
10977   MachineFunction::iterator It = ++BB->getIterator();
10978 
10979   Register dest = MI.getOperand(0).getReg();
10980   Register ptrA = MI.getOperand(1).getReg();
10981   Register ptrB = MI.getOperand(2).getReg();
10982   Register incr = MI.getOperand(3).getReg();
10983   DebugLoc dl = MI.getDebugLoc();
10984 
10985   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10986   MachineBasicBlock *loop2MBB =
10987     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10988   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10989   F->insert(It, loopMBB);
10990   if (CmpOpcode)
10991     F->insert(It, loop2MBB);
10992   F->insert(It, exitMBB);
10993   exitMBB->splice(exitMBB->begin(), BB,
10994                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10995   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10996 
10997   MachineRegisterInfo &RegInfo = F->getRegInfo();
10998   Register TmpReg = (!BinOpcode) ? incr :
10999     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11000                                            : &PPC::GPRCRegClass);
11001 
11002   //  thisMBB:
11003   //   ...
11004   //   fallthrough --> loopMBB
11005   BB->addSuccessor(loopMBB);
11006 
11007   //  loopMBB:
11008   //   l[wd]arx dest, ptr
11009   //   add r0, dest, incr
11010   //   st[wd]cx. r0, ptr
11011   //   bne- loopMBB
11012   //   fallthrough --> exitMBB
11013 
11014   // For max/min...
11015   //  loopMBB:
11016   //   l[wd]arx dest, ptr
11017   //   cmpl?[wd] incr, dest
11018   //   bgt exitMBB
11019   //  loop2MBB:
11020   //   st[wd]cx. dest, ptr
11021   //   bne- loopMBB
11022   //   fallthrough --> exitMBB
11023 
11024   BB = loopMBB;
11025   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11026     .addReg(ptrA).addReg(ptrB);
11027   if (BinOpcode)
11028     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11029   if (CmpOpcode) {
11030     // Signed comparisons of byte or halfword values must be sign-extended.
11031     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11032       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11033       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11034               ExtReg).addReg(dest);
11035       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11036         .addReg(incr).addReg(ExtReg);
11037     } else
11038       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11039         .addReg(incr).addReg(dest);
11040 
11041     BuildMI(BB, dl, TII->get(PPC::BCC))
11042       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11043     BB->addSuccessor(loop2MBB);
11044     BB->addSuccessor(exitMBB);
11045     BB = loop2MBB;
11046   }
11047   BuildMI(BB, dl, TII->get(StoreMnemonic))
11048     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11049   BuildMI(BB, dl, TII->get(PPC::BCC))
11050     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11051   BB->addSuccessor(loopMBB);
11052   BB->addSuccessor(exitMBB);
11053 
11054   //  exitMBB:
11055   //   ...
11056   BB = exitMBB;
11057   return BB;
11058 }
11059 
11060 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11061     MachineInstr &MI, MachineBasicBlock *BB,
11062     bool is8bit, // operation
11063     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11064   // If we support part-word atomic mnemonics, just use them
11065   if (Subtarget.hasPartwordAtomics())
11066     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11067                             CmpPred);
11068 
11069   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11070   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11071   // In 64 bit mode we have to use 64 bits for addresses, even though the
11072   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11073   // registers without caring whether they're 32 or 64, but here we're
11074   // doing actual arithmetic on the addresses.
11075   bool is64bit = Subtarget.isPPC64();
11076   bool isLittleEndian = Subtarget.isLittleEndian();
11077   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11078 
11079   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11080   MachineFunction *F = BB->getParent();
11081   MachineFunction::iterator It = ++BB->getIterator();
11082 
11083   Register dest = MI.getOperand(0).getReg();
11084   Register ptrA = MI.getOperand(1).getReg();
11085   Register ptrB = MI.getOperand(2).getReg();
11086   Register incr = MI.getOperand(3).getReg();
11087   DebugLoc dl = MI.getDebugLoc();
11088 
11089   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11090   MachineBasicBlock *loop2MBB =
11091       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11092   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11093   F->insert(It, loopMBB);
11094   if (CmpOpcode)
11095     F->insert(It, loop2MBB);
11096   F->insert(It, exitMBB);
11097   exitMBB->splice(exitMBB->begin(), BB,
11098                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11099   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11100 
11101   MachineRegisterInfo &RegInfo = F->getRegInfo();
11102   const TargetRegisterClass *RC =
11103       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11104   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11105 
11106   Register PtrReg = RegInfo.createVirtualRegister(RC);
11107   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11108   Register ShiftReg =
11109       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11110   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11111   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11112   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11113   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11114   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11115   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11116   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11117   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11118   Register Ptr1Reg;
11119   Register TmpReg =
11120       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11121 
11122   //  thisMBB:
11123   //   ...
11124   //   fallthrough --> loopMBB
11125   BB->addSuccessor(loopMBB);
11126 
11127   // The 4-byte load must be aligned, while a char or short may be
11128   // anywhere in the word.  Hence all this nasty bookkeeping code.
11129   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11130   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11131   //   xori shift, shift1, 24 [16]
11132   //   rlwinm ptr, ptr1, 0, 0, 29
11133   //   slw incr2, incr, shift
11134   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11135   //   slw mask, mask2, shift
11136   //  loopMBB:
11137   //   lwarx tmpDest, ptr
11138   //   add tmp, tmpDest, incr2
11139   //   andc tmp2, tmpDest, mask
11140   //   and tmp3, tmp, mask
11141   //   or tmp4, tmp3, tmp2
11142   //   stwcx. tmp4, ptr
11143   //   bne- loopMBB
11144   //   fallthrough --> exitMBB
11145   //   srw dest, tmpDest, shift
11146   if (ptrA != ZeroReg) {
11147     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11148     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11149         .addReg(ptrA)
11150         .addReg(ptrB);
11151   } else {
11152     Ptr1Reg = ptrB;
11153   }
11154   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11155   // mode.
11156   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11157       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11158       .addImm(3)
11159       .addImm(27)
11160       .addImm(is8bit ? 28 : 27);
11161   if (!isLittleEndian)
11162     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11163         .addReg(Shift1Reg)
11164         .addImm(is8bit ? 24 : 16);
11165   if (is64bit)
11166     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11167         .addReg(Ptr1Reg)
11168         .addImm(0)
11169         .addImm(61);
11170   else
11171     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11172         .addReg(Ptr1Reg)
11173         .addImm(0)
11174         .addImm(0)
11175         .addImm(29);
11176   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11177   if (is8bit)
11178     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11179   else {
11180     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11181     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11182         .addReg(Mask3Reg)
11183         .addImm(65535);
11184   }
11185   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11186       .addReg(Mask2Reg)
11187       .addReg(ShiftReg);
11188 
11189   BB = loopMBB;
11190   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11191       .addReg(ZeroReg)
11192       .addReg(PtrReg);
11193   if (BinOpcode)
11194     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11195         .addReg(Incr2Reg)
11196         .addReg(TmpDestReg);
11197   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11198       .addReg(TmpDestReg)
11199       .addReg(MaskReg);
11200   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11201   if (CmpOpcode) {
11202     // For unsigned comparisons, we can directly compare the shifted values.
11203     // For signed comparisons we shift and sign extend.
11204     Register SReg = RegInfo.createVirtualRegister(GPRC);
11205     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11206         .addReg(TmpDestReg)
11207         .addReg(MaskReg);
11208     unsigned ValueReg = SReg;
11209     unsigned CmpReg = Incr2Reg;
11210     if (CmpOpcode == PPC::CMPW) {
11211       ValueReg = RegInfo.createVirtualRegister(GPRC);
11212       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11213           .addReg(SReg)
11214           .addReg(ShiftReg);
11215       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11216       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11217           .addReg(ValueReg);
11218       ValueReg = ValueSReg;
11219       CmpReg = incr;
11220     }
11221     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11222         .addReg(CmpReg)
11223         .addReg(ValueReg);
11224     BuildMI(BB, dl, TII->get(PPC::BCC))
11225         .addImm(CmpPred)
11226         .addReg(PPC::CR0)
11227         .addMBB(exitMBB);
11228     BB->addSuccessor(loop2MBB);
11229     BB->addSuccessor(exitMBB);
11230     BB = loop2MBB;
11231   }
11232   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11233   BuildMI(BB, dl, TII->get(PPC::STWCX))
11234       .addReg(Tmp4Reg)
11235       .addReg(ZeroReg)
11236       .addReg(PtrReg);
11237   BuildMI(BB, dl, TII->get(PPC::BCC))
11238       .addImm(PPC::PRED_NE)
11239       .addReg(PPC::CR0)
11240       .addMBB(loopMBB);
11241   BB->addSuccessor(loopMBB);
11242   BB->addSuccessor(exitMBB);
11243 
11244   //  exitMBB:
11245   //   ...
11246   BB = exitMBB;
11247   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11248       .addReg(TmpDestReg)
11249       .addReg(ShiftReg);
11250   return BB;
11251 }
11252 
11253 llvm::MachineBasicBlock *
11254 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11255                                     MachineBasicBlock *MBB) const {
11256   DebugLoc DL = MI.getDebugLoc();
11257   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11258   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11259 
11260   MachineFunction *MF = MBB->getParent();
11261   MachineRegisterInfo &MRI = MF->getRegInfo();
11262 
11263   const BasicBlock *BB = MBB->getBasicBlock();
11264   MachineFunction::iterator I = ++MBB->getIterator();
11265 
11266   Register DstReg = MI.getOperand(0).getReg();
11267   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11268   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11269   Register mainDstReg = MRI.createVirtualRegister(RC);
11270   Register restoreDstReg = MRI.createVirtualRegister(RC);
11271 
11272   MVT PVT = getPointerTy(MF->getDataLayout());
11273   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11274          "Invalid Pointer Size!");
11275   // For v = setjmp(buf), we generate
11276   //
11277   // thisMBB:
11278   //  SjLjSetup mainMBB
11279   //  bl mainMBB
11280   //  v_restore = 1
11281   //  b sinkMBB
11282   //
11283   // mainMBB:
11284   //  buf[LabelOffset] = LR
11285   //  v_main = 0
11286   //
11287   // sinkMBB:
11288   //  v = phi(main, restore)
11289   //
11290 
11291   MachineBasicBlock *thisMBB = MBB;
11292   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11293   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11294   MF->insert(I, mainMBB);
11295   MF->insert(I, sinkMBB);
11296 
11297   MachineInstrBuilder MIB;
11298 
11299   // Transfer the remainder of BB and its successor edges to sinkMBB.
11300   sinkMBB->splice(sinkMBB->begin(), MBB,
11301                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11302   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11303 
11304   // Note that the structure of the jmp_buf used here is not compatible
11305   // with that used by libc, and is not designed to be. Specifically, it
11306   // stores only those 'reserved' registers that LLVM does not otherwise
11307   // understand how to spill. Also, by convention, by the time this
11308   // intrinsic is called, Clang has already stored the frame address in the
11309   // first slot of the buffer and stack address in the third. Following the
11310   // X86 target code, we'll store the jump address in the second slot. We also
11311   // need to save the TOC pointer (R2) to handle jumps between shared
11312   // libraries, and that will be stored in the fourth slot. The thread
11313   // identifier (R13) is not affected.
11314 
11315   // thisMBB:
11316   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11317   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11318   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11319 
11320   // Prepare IP either in reg.
11321   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11322   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11323   Register BufReg = MI.getOperand(1).getReg();
11324 
11325   if (Subtarget.is64BitELFABI()) {
11326     setUsesTOCBasePtr(*MBB->getParent());
11327     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11328               .addReg(PPC::X2)
11329               .addImm(TOCOffset)
11330               .addReg(BufReg)
11331               .cloneMemRefs(MI);
11332   }
11333 
11334   // Naked functions never have a base pointer, and so we use r1. For all
11335   // other functions, this decision must be delayed until during PEI.
11336   unsigned BaseReg;
11337   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11338     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11339   else
11340     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11341 
11342   MIB = BuildMI(*thisMBB, MI, DL,
11343                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11344             .addReg(BaseReg)
11345             .addImm(BPOffset)
11346             .addReg(BufReg)
11347             .cloneMemRefs(MI);
11348 
11349   // Setup
11350   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11351   MIB.addRegMask(TRI->getNoPreservedMask());
11352 
11353   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11354 
11355   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11356           .addMBB(mainMBB);
11357   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11358 
11359   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11360   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11361 
11362   // mainMBB:
11363   //  mainDstReg = 0
11364   MIB =
11365       BuildMI(mainMBB, DL,
11366               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11367 
11368   // Store IP
11369   if (Subtarget.isPPC64()) {
11370     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11371             .addReg(LabelReg)
11372             .addImm(LabelOffset)
11373             .addReg(BufReg);
11374   } else {
11375     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11376             .addReg(LabelReg)
11377             .addImm(LabelOffset)
11378             .addReg(BufReg);
11379   }
11380   MIB.cloneMemRefs(MI);
11381 
11382   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11383   mainMBB->addSuccessor(sinkMBB);
11384 
11385   // sinkMBB:
11386   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11387           TII->get(PPC::PHI), DstReg)
11388     .addReg(mainDstReg).addMBB(mainMBB)
11389     .addReg(restoreDstReg).addMBB(thisMBB);
11390 
11391   MI.eraseFromParent();
11392   return sinkMBB;
11393 }
11394 
11395 MachineBasicBlock *
11396 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11397                                      MachineBasicBlock *MBB) const {
11398   DebugLoc DL = MI.getDebugLoc();
11399   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11400 
11401   MachineFunction *MF = MBB->getParent();
11402   MachineRegisterInfo &MRI = MF->getRegInfo();
11403 
11404   MVT PVT = getPointerTy(MF->getDataLayout());
11405   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11406          "Invalid Pointer Size!");
11407 
11408   const TargetRegisterClass *RC =
11409     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11410   Register Tmp = MRI.createVirtualRegister(RC);
11411   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11412   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11413   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11414   unsigned BP =
11415       (PVT == MVT::i64)
11416           ? PPC::X30
11417           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11418                                                               : PPC::R30);
11419 
11420   MachineInstrBuilder MIB;
11421 
11422   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11423   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11424   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11425   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11426 
11427   Register BufReg = MI.getOperand(0).getReg();
11428 
11429   // Reload FP (the jumped-to function may not have had a
11430   // frame pointer, and if so, then its r31 will be restored
11431   // as necessary).
11432   if (PVT == MVT::i64) {
11433     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11434             .addImm(0)
11435             .addReg(BufReg);
11436   } else {
11437     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11438             .addImm(0)
11439             .addReg(BufReg);
11440   }
11441   MIB.cloneMemRefs(MI);
11442 
11443   // Reload IP
11444   if (PVT == MVT::i64) {
11445     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11446             .addImm(LabelOffset)
11447             .addReg(BufReg);
11448   } else {
11449     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11450             .addImm(LabelOffset)
11451             .addReg(BufReg);
11452   }
11453   MIB.cloneMemRefs(MI);
11454 
11455   // Reload SP
11456   if (PVT == MVT::i64) {
11457     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11458             .addImm(SPOffset)
11459             .addReg(BufReg);
11460   } else {
11461     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11462             .addImm(SPOffset)
11463             .addReg(BufReg);
11464   }
11465   MIB.cloneMemRefs(MI);
11466 
11467   // Reload BP
11468   if (PVT == MVT::i64) {
11469     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11470             .addImm(BPOffset)
11471             .addReg(BufReg);
11472   } else {
11473     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11474             .addImm(BPOffset)
11475             .addReg(BufReg);
11476   }
11477   MIB.cloneMemRefs(MI);
11478 
11479   // Reload TOC
11480   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11481     setUsesTOCBasePtr(*MBB->getParent());
11482     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11483               .addImm(TOCOffset)
11484               .addReg(BufReg)
11485               .cloneMemRefs(MI);
11486   }
11487 
11488   // Jump
11489   BuildMI(*MBB, MI, DL,
11490           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11491   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11492 
11493   MI.eraseFromParent();
11494   return MBB;
11495 }
11496 
11497 MachineBasicBlock *
11498 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11499                                                MachineBasicBlock *BB) const {
11500   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11501       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11502     if (Subtarget.is64BitELFABI() &&
11503         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11504         !Subtarget.isUsingPCRelativeCalls()) {
11505       // Call lowering should have added an r2 operand to indicate a dependence
11506       // on the TOC base pointer value. It can't however, because there is no
11507       // way to mark the dependence as implicit there, and so the stackmap code
11508       // will confuse it with a regular operand. Instead, add the dependence
11509       // here.
11510       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11511     }
11512 
11513     return emitPatchPoint(MI, BB);
11514   }
11515 
11516   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11517       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11518     return emitEHSjLjSetJmp(MI, BB);
11519   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11520              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11521     return emitEHSjLjLongJmp(MI, BB);
11522   }
11523 
11524   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11525 
11526   // To "insert" these instructions we actually have to insert their
11527   // control-flow patterns.
11528   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11529   MachineFunction::iterator It = ++BB->getIterator();
11530 
11531   MachineFunction *F = BB->getParent();
11532 
11533   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11534       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11535       MI.getOpcode() == PPC::SELECT_I8) {
11536     SmallVector<MachineOperand, 2> Cond;
11537     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11538         MI.getOpcode() == PPC::SELECT_CC_I8)
11539       Cond.push_back(MI.getOperand(4));
11540     else
11541       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11542     Cond.push_back(MI.getOperand(1));
11543 
11544     DebugLoc dl = MI.getDebugLoc();
11545     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11546                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11547   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11548              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11549              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11550              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11551              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11552              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11553              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11554              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11555              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11556              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11557              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11558              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11559              MI.getOpcode() == PPC::SELECT_F4 ||
11560              MI.getOpcode() == PPC::SELECT_F8 ||
11561              MI.getOpcode() == PPC::SELECT_F16 ||
11562              MI.getOpcode() == PPC::SELECT_QFRC ||
11563              MI.getOpcode() == PPC::SELECT_QSRC ||
11564              MI.getOpcode() == PPC::SELECT_QBRC ||
11565              MI.getOpcode() == PPC::SELECT_SPE ||
11566              MI.getOpcode() == PPC::SELECT_SPE4 ||
11567              MI.getOpcode() == PPC::SELECT_VRRC ||
11568              MI.getOpcode() == PPC::SELECT_VSFRC ||
11569              MI.getOpcode() == PPC::SELECT_VSSRC ||
11570              MI.getOpcode() == PPC::SELECT_VSRC) {
11571     // The incoming instruction knows the destination vreg to set, the
11572     // condition code register to branch on, the true/false values to
11573     // select between, and a branch opcode to use.
11574 
11575     //  thisMBB:
11576     //  ...
11577     //   TrueVal = ...
11578     //   cmpTY ccX, r1, r2
11579     //   bCC copy1MBB
11580     //   fallthrough --> copy0MBB
11581     MachineBasicBlock *thisMBB = BB;
11582     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11583     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11584     DebugLoc dl = MI.getDebugLoc();
11585     F->insert(It, copy0MBB);
11586     F->insert(It, sinkMBB);
11587 
11588     // Transfer the remainder of BB and its successor edges to sinkMBB.
11589     sinkMBB->splice(sinkMBB->begin(), BB,
11590                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11591     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11592 
11593     // Next, add the true and fallthrough blocks as its successors.
11594     BB->addSuccessor(copy0MBB);
11595     BB->addSuccessor(sinkMBB);
11596 
11597     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11598         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11599         MI.getOpcode() == PPC::SELECT_F16 ||
11600         MI.getOpcode() == PPC::SELECT_SPE4 ||
11601         MI.getOpcode() == PPC::SELECT_SPE ||
11602         MI.getOpcode() == PPC::SELECT_QFRC ||
11603         MI.getOpcode() == PPC::SELECT_QSRC ||
11604         MI.getOpcode() == PPC::SELECT_QBRC ||
11605         MI.getOpcode() == PPC::SELECT_VRRC ||
11606         MI.getOpcode() == PPC::SELECT_VSFRC ||
11607         MI.getOpcode() == PPC::SELECT_VSSRC ||
11608         MI.getOpcode() == PPC::SELECT_VSRC) {
11609       BuildMI(BB, dl, TII->get(PPC::BC))
11610           .addReg(MI.getOperand(1).getReg())
11611           .addMBB(sinkMBB);
11612     } else {
11613       unsigned SelectPred = MI.getOperand(4).getImm();
11614       BuildMI(BB, dl, TII->get(PPC::BCC))
11615           .addImm(SelectPred)
11616           .addReg(MI.getOperand(1).getReg())
11617           .addMBB(sinkMBB);
11618     }
11619 
11620     //  copy0MBB:
11621     //   %FalseValue = ...
11622     //   # fallthrough to sinkMBB
11623     BB = copy0MBB;
11624 
11625     // Update machine-CFG edges
11626     BB->addSuccessor(sinkMBB);
11627 
11628     //  sinkMBB:
11629     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11630     //  ...
11631     BB = sinkMBB;
11632     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11633         .addReg(MI.getOperand(3).getReg())
11634         .addMBB(copy0MBB)
11635         .addReg(MI.getOperand(2).getReg())
11636         .addMBB(thisMBB);
11637   } else if (MI.getOpcode() == PPC::ReadTB) {
11638     // To read the 64-bit time-base register on a 32-bit target, we read the
11639     // two halves. Should the counter have wrapped while it was being read, we
11640     // need to try again.
11641     // ...
11642     // readLoop:
11643     // mfspr Rx,TBU # load from TBU
11644     // mfspr Ry,TB  # load from TB
11645     // mfspr Rz,TBU # load from TBU
11646     // cmpw crX,Rx,Rz # check if 'old'='new'
11647     // bne readLoop   # branch if they're not equal
11648     // ...
11649 
11650     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11651     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11652     DebugLoc dl = MI.getDebugLoc();
11653     F->insert(It, readMBB);
11654     F->insert(It, sinkMBB);
11655 
11656     // Transfer the remainder of BB and its successor edges to sinkMBB.
11657     sinkMBB->splice(sinkMBB->begin(), BB,
11658                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11659     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11660 
11661     BB->addSuccessor(readMBB);
11662     BB = readMBB;
11663 
11664     MachineRegisterInfo &RegInfo = F->getRegInfo();
11665     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11666     Register LoReg = MI.getOperand(0).getReg();
11667     Register HiReg = MI.getOperand(1).getReg();
11668 
11669     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11670     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11671     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11672 
11673     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11674 
11675     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11676         .addReg(HiReg)
11677         .addReg(ReadAgainReg);
11678     BuildMI(BB, dl, TII->get(PPC::BCC))
11679         .addImm(PPC::PRED_NE)
11680         .addReg(CmpReg)
11681         .addMBB(readMBB);
11682 
11683     BB->addSuccessor(readMBB);
11684     BB->addSuccessor(sinkMBB);
11685   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11686     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11687   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11688     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11689   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11690     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11691   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11692     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11693 
11694   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11695     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11696   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11697     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11698   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11699     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11700   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11701     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11702 
11703   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11704     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11705   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11706     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11707   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11708     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11709   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11710     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11711 
11712   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11713     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11714   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11715     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11716   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11717     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11718   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11719     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11720 
11721   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11722     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11723   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11724     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11725   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11726     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11727   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11728     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11729 
11730   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11731     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11732   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11733     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11734   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11735     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11736   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11737     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11738 
11739   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11740     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11741   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11742     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11743   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11744     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11745   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11746     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11747 
11748   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11749     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11750   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11751     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11752   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11753     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11754   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11755     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11756 
11757   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11758     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11759   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11760     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11761   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11762     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11763   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11764     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11765 
11766   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11767     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11768   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11769     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11770   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11771     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11772   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11773     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11774 
11775   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11776     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11777   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11778     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11779   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11780     BB = EmitAtomicBinary(MI, BB, 4, 0);
11781   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11782     BB = EmitAtomicBinary(MI, BB, 8, 0);
11783   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11784            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11785            (Subtarget.hasPartwordAtomics() &&
11786             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11787            (Subtarget.hasPartwordAtomics() &&
11788             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11789     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11790 
11791     auto LoadMnemonic = PPC::LDARX;
11792     auto StoreMnemonic = PPC::STDCX;
11793     switch (MI.getOpcode()) {
11794     default:
11795       llvm_unreachable("Compare and swap of unknown size");
11796     case PPC::ATOMIC_CMP_SWAP_I8:
11797       LoadMnemonic = PPC::LBARX;
11798       StoreMnemonic = PPC::STBCX;
11799       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11800       break;
11801     case PPC::ATOMIC_CMP_SWAP_I16:
11802       LoadMnemonic = PPC::LHARX;
11803       StoreMnemonic = PPC::STHCX;
11804       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11805       break;
11806     case PPC::ATOMIC_CMP_SWAP_I32:
11807       LoadMnemonic = PPC::LWARX;
11808       StoreMnemonic = PPC::STWCX;
11809       break;
11810     case PPC::ATOMIC_CMP_SWAP_I64:
11811       LoadMnemonic = PPC::LDARX;
11812       StoreMnemonic = PPC::STDCX;
11813       break;
11814     }
11815     Register dest = MI.getOperand(0).getReg();
11816     Register ptrA = MI.getOperand(1).getReg();
11817     Register ptrB = MI.getOperand(2).getReg();
11818     Register oldval = MI.getOperand(3).getReg();
11819     Register newval = MI.getOperand(4).getReg();
11820     DebugLoc dl = MI.getDebugLoc();
11821 
11822     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11823     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11824     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11825     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11826     F->insert(It, loop1MBB);
11827     F->insert(It, loop2MBB);
11828     F->insert(It, midMBB);
11829     F->insert(It, exitMBB);
11830     exitMBB->splice(exitMBB->begin(), BB,
11831                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11832     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11833 
11834     //  thisMBB:
11835     //   ...
11836     //   fallthrough --> loopMBB
11837     BB->addSuccessor(loop1MBB);
11838 
11839     // loop1MBB:
11840     //   l[bhwd]arx dest, ptr
11841     //   cmp[wd] dest, oldval
11842     //   bne- midMBB
11843     // loop2MBB:
11844     //   st[bhwd]cx. newval, ptr
11845     //   bne- loopMBB
11846     //   b exitBB
11847     // midMBB:
11848     //   st[bhwd]cx. dest, ptr
11849     // exitBB:
11850     BB = loop1MBB;
11851     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11852     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11853         .addReg(oldval)
11854         .addReg(dest);
11855     BuildMI(BB, dl, TII->get(PPC::BCC))
11856         .addImm(PPC::PRED_NE)
11857         .addReg(PPC::CR0)
11858         .addMBB(midMBB);
11859     BB->addSuccessor(loop2MBB);
11860     BB->addSuccessor(midMBB);
11861 
11862     BB = loop2MBB;
11863     BuildMI(BB, dl, TII->get(StoreMnemonic))
11864         .addReg(newval)
11865         .addReg(ptrA)
11866         .addReg(ptrB);
11867     BuildMI(BB, dl, TII->get(PPC::BCC))
11868         .addImm(PPC::PRED_NE)
11869         .addReg(PPC::CR0)
11870         .addMBB(loop1MBB);
11871     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11872     BB->addSuccessor(loop1MBB);
11873     BB->addSuccessor(exitMBB);
11874 
11875     BB = midMBB;
11876     BuildMI(BB, dl, TII->get(StoreMnemonic))
11877         .addReg(dest)
11878         .addReg(ptrA)
11879         .addReg(ptrB);
11880     BB->addSuccessor(exitMBB);
11881 
11882     //  exitMBB:
11883     //   ...
11884     BB = exitMBB;
11885   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11886              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11887     // We must use 64-bit registers for addresses when targeting 64-bit,
11888     // since we're actually doing arithmetic on them.  Other registers
11889     // can be 32-bit.
11890     bool is64bit = Subtarget.isPPC64();
11891     bool isLittleEndian = Subtarget.isLittleEndian();
11892     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11893 
11894     Register dest = MI.getOperand(0).getReg();
11895     Register ptrA = MI.getOperand(1).getReg();
11896     Register ptrB = MI.getOperand(2).getReg();
11897     Register oldval = MI.getOperand(3).getReg();
11898     Register newval = MI.getOperand(4).getReg();
11899     DebugLoc dl = MI.getDebugLoc();
11900 
11901     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11902     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11903     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11904     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11905     F->insert(It, loop1MBB);
11906     F->insert(It, loop2MBB);
11907     F->insert(It, midMBB);
11908     F->insert(It, exitMBB);
11909     exitMBB->splice(exitMBB->begin(), BB,
11910                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11911     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11912 
11913     MachineRegisterInfo &RegInfo = F->getRegInfo();
11914     const TargetRegisterClass *RC =
11915         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11916     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11917 
11918     Register PtrReg = RegInfo.createVirtualRegister(RC);
11919     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11920     Register ShiftReg =
11921         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11922     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11923     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11924     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11925     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11926     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11927     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11928     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11929     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11930     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11931     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11932     Register Ptr1Reg;
11933     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11934     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11935     //  thisMBB:
11936     //   ...
11937     //   fallthrough --> loopMBB
11938     BB->addSuccessor(loop1MBB);
11939 
11940     // The 4-byte load must be aligned, while a char or short may be
11941     // anywhere in the word.  Hence all this nasty bookkeeping code.
11942     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11943     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11944     //   xori shift, shift1, 24 [16]
11945     //   rlwinm ptr, ptr1, 0, 0, 29
11946     //   slw newval2, newval, shift
11947     //   slw oldval2, oldval,shift
11948     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11949     //   slw mask, mask2, shift
11950     //   and newval3, newval2, mask
11951     //   and oldval3, oldval2, mask
11952     // loop1MBB:
11953     //   lwarx tmpDest, ptr
11954     //   and tmp, tmpDest, mask
11955     //   cmpw tmp, oldval3
11956     //   bne- midMBB
11957     // loop2MBB:
11958     //   andc tmp2, tmpDest, mask
11959     //   or tmp4, tmp2, newval3
11960     //   stwcx. tmp4, ptr
11961     //   bne- loop1MBB
11962     //   b exitBB
11963     // midMBB:
11964     //   stwcx. tmpDest, ptr
11965     // exitBB:
11966     //   srw dest, tmpDest, shift
11967     if (ptrA != ZeroReg) {
11968       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11969       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11970           .addReg(ptrA)
11971           .addReg(ptrB);
11972     } else {
11973       Ptr1Reg = ptrB;
11974     }
11975 
11976     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11977     // mode.
11978     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11979         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11980         .addImm(3)
11981         .addImm(27)
11982         .addImm(is8bit ? 28 : 27);
11983     if (!isLittleEndian)
11984       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11985           .addReg(Shift1Reg)
11986           .addImm(is8bit ? 24 : 16);
11987     if (is64bit)
11988       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11989           .addReg(Ptr1Reg)
11990           .addImm(0)
11991           .addImm(61);
11992     else
11993       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11994           .addReg(Ptr1Reg)
11995           .addImm(0)
11996           .addImm(0)
11997           .addImm(29);
11998     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11999         .addReg(newval)
12000         .addReg(ShiftReg);
12001     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12002         .addReg(oldval)
12003         .addReg(ShiftReg);
12004     if (is8bit)
12005       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12006     else {
12007       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12008       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12009           .addReg(Mask3Reg)
12010           .addImm(65535);
12011     }
12012     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12013         .addReg(Mask2Reg)
12014         .addReg(ShiftReg);
12015     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12016         .addReg(NewVal2Reg)
12017         .addReg(MaskReg);
12018     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12019         .addReg(OldVal2Reg)
12020         .addReg(MaskReg);
12021 
12022     BB = loop1MBB;
12023     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12024         .addReg(ZeroReg)
12025         .addReg(PtrReg);
12026     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12027         .addReg(TmpDestReg)
12028         .addReg(MaskReg);
12029     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12030         .addReg(TmpReg)
12031         .addReg(OldVal3Reg);
12032     BuildMI(BB, dl, TII->get(PPC::BCC))
12033         .addImm(PPC::PRED_NE)
12034         .addReg(PPC::CR0)
12035         .addMBB(midMBB);
12036     BB->addSuccessor(loop2MBB);
12037     BB->addSuccessor(midMBB);
12038 
12039     BB = loop2MBB;
12040     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12041         .addReg(TmpDestReg)
12042         .addReg(MaskReg);
12043     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12044         .addReg(Tmp2Reg)
12045         .addReg(NewVal3Reg);
12046     BuildMI(BB, dl, TII->get(PPC::STWCX))
12047         .addReg(Tmp4Reg)
12048         .addReg(ZeroReg)
12049         .addReg(PtrReg);
12050     BuildMI(BB, dl, TII->get(PPC::BCC))
12051         .addImm(PPC::PRED_NE)
12052         .addReg(PPC::CR0)
12053         .addMBB(loop1MBB);
12054     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12055     BB->addSuccessor(loop1MBB);
12056     BB->addSuccessor(exitMBB);
12057 
12058     BB = midMBB;
12059     BuildMI(BB, dl, TII->get(PPC::STWCX))
12060         .addReg(TmpDestReg)
12061         .addReg(ZeroReg)
12062         .addReg(PtrReg);
12063     BB->addSuccessor(exitMBB);
12064 
12065     //  exitMBB:
12066     //   ...
12067     BB = exitMBB;
12068     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12069         .addReg(TmpReg)
12070         .addReg(ShiftReg);
12071   } else if (MI.getOpcode() == PPC::FADDrtz) {
12072     // This pseudo performs an FADD with rounding mode temporarily forced
12073     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12074     // is not modeled at the SelectionDAG level.
12075     Register Dest = MI.getOperand(0).getReg();
12076     Register Src1 = MI.getOperand(1).getReg();
12077     Register Src2 = MI.getOperand(2).getReg();
12078     DebugLoc dl = MI.getDebugLoc();
12079 
12080     MachineRegisterInfo &RegInfo = F->getRegInfo();
12081     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12082 
12083     // Save FPSCR value.
12084     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12085 
12086     // Set rounding mode to round-to-zero.
12087     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12088     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12089 
12090     // Perform addition.
12091     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12092 
12093     // Restore FPSCR value.
12094     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12095   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12096              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12097              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12098              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12099     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12100                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12101                           ? PPC::ANDI8_rec
12102                           : PPC::ANDI_rec;
12103     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12104                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12105 
12106     MachineRegisterInfo &RegInfo = F->getRegInfo();
12107     Register Dest = RegInfo.createVirtualRegister(
12108         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12109 
12110     DebugLoc Dl = MI.getDebugLoc();
12111     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12112         .addReg(MI.getOperand(1).getReg())
12113         .addImm(1);
12114     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12115             MI.getOperand(0).getReg())
12116         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12117   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12118     DebugLoc Dl = MI.getDebugLoc();
12119     MachineRegisterInfo &RegInfo = F->getRegInfo();
12120     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12121     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12122     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12123             MI.getOperand(0).getReg())
12124         .addReg(CRReg);
12125   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12126     DebugLoc Dl = MI.getDebugLoc();
12127     unsigned Imm = MI.getOperand(1).getImm();
12128     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12129     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12130             MI.getOperand(0).getReg())
12131         .addReg(PPC::CR0EQ);
12132   } else if (MI.getOpcode() == PPC::SETRNDi) {
12133     DebugLoc dl = MI.getDebugLoc();
12134     Register OldFPSCRReg = MI.getOperand(0).getReg();
12135 
12136     // Save FPSCR value.
12137     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12138 
12139     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12140     // the following settings:
12141     //   00 Round to nearest
12142     //   01 Round to 0
12143     //   10 Round to +inf
12144     //   11 Round to -inf
12145 
12146     // When the operand is immediate, using the two least significant bits of
12147     // the immediate to set the bits 62:63 of FPSCR.
12148     unsigned Mode = MI.getOperand(1).getImm();
12149     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12150       .addImm(31);
12151 
12152     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12153       .addImm(30);
12154   } else if (MI.getOpcode() == PPC::SETRND) {
12155     DebugLoc dl = MI.getDebugLoc();
12156 
12157     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12158     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12159     // If the target doesn't have DirectMove, we should use stack to do the
12160     // conversion, because the target doesn't have the instructions like mtvsrd
12161     // or mfvsrd to do this conversion directly.
12162     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12163       if (Subtarget.hasDirectMove()) {
12164         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12165           .addReg(SrcReg);
12166       } else {
12167         // Use stack to do the register copy.
12168         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12169         MachineRegisterInfo &RegInfo = F->getRegInfo();
12170         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12171         if (RC == &PPC::F8RCRegClass) {
12172           // Copy register from F8RCRegClass to G8RCRegclass.
12173           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12174                  "Unsupported RegClass.");
12175 
12176           StoreOp = PPC::STFD;
12177           LoadOp = PPC::LD;
12178         } else {
12179           // Copy register from G8RCRegClass to F8RCRegclass.
12180           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12181                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12182                  "Unsupported RegClass.");
12183         }
12184 
12185         MachineFrameInfo &MFI = F->getFrameInfo();
12186         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12187 
12188         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12189             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12190             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12191             MFI.getObjectAlign(FrameIdx));
12192 
12193         // Store the SrcReg into the stack.
12194         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12195           .addReg(SrcReg)
12196           .addImm(0)
12197           .addFrameIndex(FrameIdx)
12198           .addMemOperand(MMOStore);
12199 
12200         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12201             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12202             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12203             MFI.getObjectAlign(FrameIdx));
12204 
12205         // Load from the stack where SrcReg is stored, and save to DestReg,
12206         // so we have done the RegClass conversion from RegClass::SrcReg to
12207         // RegClass::DestReg.
12208         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12209           .addImm(0)
12210           .addFrameIndex(FrameIdx)
12211           .addMemOperand(MMOLoad);
12212       }
12213     };
12214 
12215     Register OldFPSCRReg = MI.getOperand(0).getReg();
12216 
12217     // Save FPSCR value.
12218     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12219 
12220     // When the operand is gprc register, use two least significant bits of the
12221     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12222     //
12223     // copy OldFPSCRTmpReg, OldFPSCRReg
12224     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12225     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12226     // copy NewFPSCRReg, NewFPSCRTmpReg
12227     // mtfsf 255, NewFPSCRReg
12228     MachineOperand SrcOp = MI.getOperand(1);
12229     MachineRegisterInfo &RegInfo = F->getRegInfo();
12230     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12231 
12232     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12233 
12234     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12235     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12236 
12237     // The first operand of INSERT_SUBREG should be a register which has
12238     // subregisters, we only care about its RegClass, so we should use an
12239     // IMPLICIT_DEF register.
12240     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12241     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12242       .addReg(ImDefReg)
12243       .add(SrcOp)
12244       .addImm(1);
12245 
12246     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12247     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12248       .addReg(OldFPSCRTmpReg)
12249       .addReg(ExtSrcReg)
12250       .addImm(0)
12251       .addImm(62);
12252 
12253     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12254     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12255 
12256     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12257     // bits of FPSCR.
12258     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12259       .addImm(255)
12260       .addReg(NewFPSCRReg)
12261       .addImm(0)
12262       .addImm(0);
12263   } else {
12264     llvm_unreachable("Unexpected instr type to insert");
12265   }
12266 
12267   MI.eraseFromParent(); // The pseudo instruction is gone now.
12268   return BB;
12269 }
12270 
12271 //===----------------------------------------------------------------------===//
12272 // Target Optimization Hooks
12273 //===----------------------------------------------------------------------===//
12274 
12275 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12276   // For the estimates, convergence is quadratic, so we essentially double the
12277   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12278   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12279   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12280   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12281   if (VT.getScalarType() == MVT::f64)
12282     RefinementSteps++;
12283   return RefinementSteps;
12284 }
12285 
12286 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12287                                            int Enabled, int &RefinementSteps,
12288                                            bool &UseOneConstNR,
12289                                            bool Reciprocal) const {
12290   EVT VT = Operand.getValueType();
12291   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12292       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12293       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12294       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12295       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12296       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12297     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12298       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12299 
12300     // The Newton-Raphson computation with a single constant does not provide
12301     // enough accuracy on some CPUs.
12302     UseOneConstNR = !Subtarget.needsTwoConstNR();
12303     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12304   }
12305   return SDValue();
12306 }
12307 
12308 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12309                                             int Enabled,
12310                                             int &RefinementSteps) const {
12311   EVT VT = Operand.getValueType();
12312   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12313       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12314       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12315       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12316       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12317       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12318     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12319       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12320     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12321   }
12322   return SDValue();
12323 }
12324 
12325 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12326   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12327   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12328   // enabled for division), this functionality is redundant with the default
12329   // combiner logic (once the division -> reciprocal/multiply transformation
12330   // has taken place). As a result, this matters more for older cores than for
12331   // newer ones.
12332 
12333   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12334   // reciprocal if there are two or more FDIVs (for embedded cores with only
12335   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12336   switch (Subtarget.getCPUDirective()) {
12337   default:
12338     return 3;
12339   case PPC::DIR_440:
12340   case PPC::DIR_A2:
12341   case PPC::DIR_E500:
12342   case PPC::DIR_E500mc:
12343   case PPC::DIR_E5500:
12344     return 2;
12345   }
12346 }
12347 
12348 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12349 // collapsed, and so we need to look through chains of them.
12350 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12351                                      int64_t& Offset, SelectionDAG &DAG) {
12352   if (DAG.isBaseWithConstantOffset(Loc)) {
12353     Base = Loc.getOperand(0);
12354     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12355 
12356     // The base might itself be a base plus an offset, and if so, accumulate
12357     // that as well.
12358     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12359   }
12360 }
12361 
12362 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12363                             unsigned Bytes, int Dist,
12364                             SelectionDAG &DAG) {
12365   if (VT.getSizeInBits() / 8 != Bytes)
12366     return false;
12367 
12368   SDValue BaseLoc = Base->getBasePtr();
12369   if (Loc.getOpcode() == ISD::FrameIndex) {
12370     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12371       return false;
12372     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12373     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12374     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12375     int FS  = MFI.getObjectSize(FI);
12376     int BFS = MFI.getObjectSize(BFI);
12377     if (FS != BFS || FS != (int)Bytes) return false;
12378     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12379   }
12380 
12381   SDValue Base1 = Loc, Base2 = BaseLoc;
12382   int64_t Offset1 = 0, Offset2 = 0;
12383   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12384   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12385   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12386     return true;
12387 
12388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12389   const GlobalValue *GV1 = nullptr;
12390   const GlobalValue *GV2 = nullptr;
12391   Offset1 = 0;
12392   Offset2 = 0;
12393   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12394   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12395   if (isGA1 && isGA2 && GV1 == GV2)
12396     return Offset1 == (Offset2 + Dist*Bytes);
12397   return false;
12398 }
12399 
12400 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12401 // not enforce equality of the chain operands.
12402 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12403                             unsigned Bytes, int Dist,
12404                             SelectionDAG &DAG) {
12405   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12406     EVT VT = LS->getMemoryVT();
12407     SDValue Loc = LS->getBasePtr();
12408     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12409   }
12410 
12411   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12412     EVT VT;
12413     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12414     default: return false;
12415     case Intrinsic::ppc_qpx_qvlfd:
12416     case Intrinsic::ppc_qpx_qvlfda:
12417       VT = MVT::v4f64;
12418       break;
12419     case Intrinsic::ppc_qpx_qvlfs:
12420     case Intrinsic::ppc_qpx_qvlfsa:
12421       VT = MVT::v4f32;
12422       break;
12423     case Intrinsic::ppc_qpx_qvlfcd:
12424     case Intrinsic::ppc_qpx_qvlfcda:
12425       VT = MVT::v2f64;
12426       break;
12427     case Intrinsic::ppc_qpx_qvlfcs:
12428     case Intrinsic::ppc_qpx_qvlfcsa:
12429       VT = MVT::v2f32;
12430       break;
12431     case Intrinsic::ppc_qpx_qvlfiwa:
12432     case Intrinsic::ppc_qpx_qvlfiwz:
12433     case Intrinsic::ppc_altivec_lvx:
12434     case Intrinsic::ppc_altivec_lvxl:
12435     case Intrinsic::ppc_vsx_lxvw4x:
12436     case Intrinsic::ppc_vsx_lxvw4x_be:
12437       VT = MVT::v4i32;
12438       break;
12439     case Intrinsic::ppc_vsx_lxvd2x:
12440     case Intrinsic::ppc_vsx_lxvd2x_be:
12441       VT = MVT::v2f64;
12442       break;
12443     case Intrinsic::ppc_altivec_lvebx:
12444       VT = MVT::i8;
12445       break;
12446     case Intrinsic::ppc_altivec_lvehx:
12447       VT = MVT::i16;
12448       break;
12449     case Intrinsic::ppc_altivec_lvewx:
12450       VT = MVT::i32;
12451       break;
12452     }
12453 
12454     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12455   }
12456 
12457   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12458     EVT VT;
12459     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12460     default: return false;
12461     case Intrinsic::ppc_qpx_qvstfd:
12462     case Intrinsic::ppc_qpx_qvstfda:
12463       VT = MVT::v4f64;
12464       break;
12465     case Intrinsic::ppc_qpx_qvstfs:
12466     case Intrinsic::ppc_qpx_qvstfsa:
12467       VT = MVT::v4f32;
12468       break;
12469     case Intrinsic::ppc_qpx_qvstfcd:
12470     case Intrinsic::ppc_qpx_qvstfcda:
12471       VT = MVT::v2f64;
12472       break;
12473     case Intrinsic::ppc_qpx_qvstfcs:
12474     case Intrinsic::ppc_qpx_qvstfcsa:
12475       VT = MVT::v2f32;
12476       break;
12477     case Intrinsic::ppc_qpx_qvstfiw:
12478     case Intrinsic::ppc_qpx_qvstfiwa:
12479     case Intrinsic::ppc_altivec_stvx:
12480     case Intrinsic::ppc_altivec_stvxl:
12481     case Intrinsic::ppc_vsx_stxvw4x:
12482       VT = MVT::v4i32;
12483       break;
12484     case Intrinsic::ppc_vsx_stxvd2x:
12485       VT = MVT::v2f64;
12486       break;
12487     case Intrinsic::ppc_vsx_stxvw4x_be:
12488       VT = MVT::v4i32;
12489       break;
12490     case Intrinsic::ppc_vsx_stxvd2x_be:
12491       VT = MVT::v2f64;
12492       break;
12493     case Intrinsic::ppc_altivec_stvebx:
12494       VT = MVT::i8;
12495       break;
12496     case Intrinsic::ppc_altivec_stvehx:
12497       VT = MVT::i16;
12498       break;
12499     case Intrinsic::ppc_altivec_stvewx:
12500       VT = MVT::i32;
12501       break;
12502     }
12503 
12504     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12505   }
12506 
12507   return false;
12508 }
12509 
12510 // Return true is there is a nearyby consecutive load to the one provided
12511 // (regardless of alignment). We search up and down the chain, looking though
12512 // token factors and other loads (but nothing else). As a result, a true result
12513 // indicates that it is safe to create a new consecutive load adjacent to the
12514 // load provided.
12515 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12516   SDValue Chain = LD->getChain();
12517   EVT VT = LD->getMemoryVT();
12518 
12519   SmallSet<SDNode *, 16> LoadRoots;
12520   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12521   SmallSet<SDNode *, 16> Visited;
12522 
12523   // First, search up the chain, branching to follow all token-factor operands.
12524   // If we find a consecutive load, then we're done, otherwise, record all
12525   // nodes just above the top-level loads and token factors.
12526   while (!Queue.empty()) {
12527     SDNode *ChainNext = Queue.pop_back_val();
12528     if (!Visited.insert(ChainNext).second)
12529       continue;
12530 
12531     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12532       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12533         return true;
12534 
12535       if (!Visited.count(ChainLD->getChain().getNode()))
12536         Queue.push_back(ChainLD->getChain().getNode());
12537     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12538       for (const SDUse &O : ChainNext->ops())
12539         if (!Visited.count(O.getNode()))
12540           Queue.push_back(O.getNode());
12541     } else
12542       LoadRoots.insert(ChainNext);
12543   }
12544 
12545   // Second, search down the chain, starting from the top-level nodes recorded
12546   // in the first phase. These top-level nodes are the nodes just above all
12547   // loads and token factors. Starting with their uses, recursively look though
12548   // all loads (just the chain uses) and token factors to find a consecutive
12549   // load.
12550   Visited.clear();
12551   Queue.clear();
12552 
12553   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12554        IE = LoadRoots.end(); I != IE; ++I) {
12555     Queue.push_back(*I);
12556 
12557     while (!Queue.empty()) {
12558       SDNode *LoadRoot = Queue.pop_back_val();
12559       if (!Visited.insert(LoadRoot).second)
12560         continue;
12561 
12562       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12563         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12564           return true;
12565 
12566       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12567            UE = LoadRoot->use_end(); UI != UE; ++UI)
12568         if (((isa<MemSDNode>(*UI) &&
12569             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12570             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12571           Queue.push_back(*UI);
12572     }
12573   }
12574 
12575   return false;
12576 }
12577 
12578 /// This function is called when we have proved that a SETCC node can be replaced
12579 /// by subtraction (and other supporting instructions) so that the result of
12580 /// comparison is kept in a GPR instead of CR. This function is purely for
12581 /// codegen purposes and has some flags to guide the codegen process.
12582 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12583                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12584   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12585 
12586   // Zero extend the operands to the largest legal integer. Originally, they
12587   // must be of a strictly smaller size.
12588   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12589                          DAG.getConstant(Size, DL, MVT::i32));
12590   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12591                          DAG.getConstant(Size, DL, MVT::i32));
12592 
12593   // Swap if needed. Depends on the condition code.
12594   if (Swap)
12595     std::swap(Op0, Op1);
12596 
12597   // Subtract extended integers.
12598   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12599 
12600   // Move the sign bit to the least significant position and zero out the rest.
12601   // Now the least significant bit carries the result of original comparison.
12602   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12603                              DAG.getConstant(Size - 1, DL, MVT::i32));
12604   auto Final = Shifted;
12605 
12606   // Complement the result if needed. Based on the condition code.
12607   if (Complement)
12608     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12609                         DAG.getConstant(1, DL, MVT::i64));
12610 
12611   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12612 }
12613 
12614 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12615                                                   DAGCombinerInfo &DCI) const {
12616   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12617 
12618   SelectionDAG &DAG = DCI.DAG;
12619   SDLoc DL(N);
12620 
12621   // Size of integers being compared has a critical role in the following
12622   // analysis, so we prefer to do this when all types are legal.
12623   if (!DCI.isAfterLegalizeDAG())
12624     return SDValue();
12625 
12626   // If all users of SETCC extend its value to a legal integer type
12627   // then we replace SETCC with a subtraction
12628   for (SDNode::use_iterator UI = N->use_begin(),
12629        UE = N->use_end(); UI != UE; ++UI) {
12630     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12631       return SDValue();
12632   }
12633 
12634   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12635   auto OpSize = N->getOperand(0).getValueSizeInBits();
12636 
12637   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12638 
12639   if (OpSize < Size) {
12640     switch (CC) {
12641     default: break;
12642     case ISD::SETULT:
12643       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12644     case ISD::SETULE:
12645       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12646     case ISD::SETUGT:
12647       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12648     case ISD::SETUGE:
12649       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12650     }
12651   }
12652 
12653   return SDValue();
12654 }
12655 
12656 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12657                                                   DAGCombinerInfo &DCI) const {
12658   SelectionDAG &DAG = DCI.DAG;
12659   SDLoc dl(N);
12660 
12661   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12662   // If we're tracking CR bits, we need to be careful that we don't have:
12663   //   trunc(binary-ops(zext(x), zext(y)))
12664   // or
12665   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12666   // such that we're unnecessarily moving things into GPRs when it would be
12667   // better to keep them in CR bits.
12668 
12669   // Note that trunc here can be an actual i1 trunc, or can be the effective
12670   // truncation that comes from a setcc or select_cc.
12671   if (N->getOpcode() == ISD::TRUNCATE &&
12672       N->getValueType(0) != MVT::i1)
12673     return SDValue();
12674 
12675   if (N->getOperand(0).getValueType() != MVT::i32 &&
12676       N->getOperand(0).getValueType() != MVT::i64)
12677     return SDValue();
12678 
12679   if (N->getOpcode() == ISD::SETCC ||
12680       N->getOpcode() == ISD::SELECT_CC) {
12681     // If we're looking at a comparison, then we need to make sure that the
12682     // high bits (all except for the first) don't matter the result.
12683     ISD::CondCode CC =
12684       cast<CondCodeSDNode>(N->getOperand(
12685         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12686     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12687 
12688     if (ISD::isSignedIntSetCC(CC)) {
12689       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12690           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12691         return SDValue();
12692     } else if (ISD::isUnsignedIntSetCC(CC)) {
12693       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12694                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12695           !DAG.MaskedValueIsZero(N->getOperand(1),
12696                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12697         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12698                                              : SDValue());
12699     } else {
12700       // This is neither a signed nor an unsigned comparison, just make sure
12701       // that the high bits are equal.
12702       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12703       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12704 
12705       // We don't really care about what is known about the first bit (if
12706       // anything), so clear it in all masks prior to comparing them.
12707       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12708       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12709 
12710       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12711         return SDValue();
12712     }
12713   }
12714 
12715   // We now know that the higher-order bits are irrelevant, we just need to
12716   // make sure that all of the intermediate operations are bit operations, and
12717   // all inputs are extensions.
12718   if (N->getOperand(0).getOpcode() != ISD::AND &&
12719       N->getOperand(0).getOpcode() != ISD::OR  &&
12720       N->getOperand(0).getOpcode() != ISD::XOR &&
12721       N->getOperand(0).getOpcode() != ISD::SELECT &&
12722       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12723       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12724       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12725       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12726       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12727     return SDValue();
12728 
12729   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12730       N->getOperand(1).getOpcode() != ISD::AND &&
12731       N->getOperand(1).getOpcode() != ISD::OR  &&
12732       N->getOperand(1).getOpcode() != ISD::XOR &&
12733       N->getOperand(1).getOpcode() != ISD::SELECT &&
12734       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12735       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12736       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12737       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12738       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12739     return SDValue();
12740 
12741   SmallVector<SDValue, 4> Inputs;
12742   SmallVector<SDValue, 8> BinOps, PromOps;
12743   SmallPtrSet<SDNode *, 16> Visited;
12744 
12745   for (unsigned i = 0; i < 2; ++i) {
12746     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12747           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12748           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12749           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12750         isa<ConstantSDNode>(N->getOperand(i)))
12751       Inputs.push_back(N->getOperand(i));
12752     else
12753       BinOps.push_back(N->getOperand(i));
12754 
12755     if (N->getOpcode() == ISD::TRUNCATE)
12756       break;
12757   }
12758 
12759   // Visit all inputs, collect all binary operations (and, or, xor and
12760   // select) that are all fed by extensions.
12761   while (!BinOps.empty()) {
12762     SDValue BinOp = BinOps.back();
12763     BinOps.pop_back();
12764 
12765     if (!Visited.insert(BinOp.getNode()).second)
12766       continue;
12767 
12768     PromOps.push_back(BinOp);
12769 
12770     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12771       // The condition of the select is not promoted.
12772       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12773         continue;
12774       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12775         continue;
12776 
12777       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12778             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12779             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12780            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12781           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12782         Inputs.push_back(BinOp.getOperand(i));
12783       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12784                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12785                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12786                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12787                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12788                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12789                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12790                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12791                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12792         BinOps.push_back(BinOp.getOperand(i));
12793       } else {
12794         // We have an input that is not an extension or another binary
12795         // operation; we'll abort this transformation.
12796         return SDValue();
12797       }
12798     }
12799   }
12800 
12801   // Make sure that this is a self-contained cluster of operations (which
12802   // is not quite the same thing as saying that everything has only one
12803   // use).
12804   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12805     if (isa<ConstantSDNode>(Inputs[i]))
12806       continue;
12807 
12808     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12809                               UE = Inputs[i].getNode()->use_end();
12810          UI != UE; ++UI) {
12811       SDNode *User = *UI;
12812       if (User != N && !Visited.count(User))
12813         return SDValue();
12814 
12815       // Make sure that we're not going to promote the non-output-value
12816       // operand(s) or SELECT or SELECT_CC.
12817       // FIXME: Although we could sometimes handle this, and it does occur in
12818       // practice that one of the condition inputs to the select is also one of
12819       // the outputs, we currently can't deal with this.
12820       if (User->getOpcode() == ISD::SELECT) {
12821         if (User->getOperand(0) == Inputs[i])
12822           return SDValue();
12823       } else if (User->getOpcode() == ISD::SELECT_CC) {
12824         if (User->getOperand(0) == Inputs[i] ||
12825             User->getOperand(1) == Inputs[i])
12826           return SDValue();
12827       }
12828     }
12829   }
12830 
12831   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12832     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12833                               UE = PromOps[i].getNode()->use_end();
12834          UI != UE; ++UI) {
12835       SDNode *User = *UI;
12836       if (User != N && !Visited.count(User))
12837         return SDValue();
12838 
12839       // Make sure that we're not going to promote the non-output-value
12840       // operand(s) or SELECT or SELECT_CC.
12841       // FIXME: Although we could sometimes handle this, and it does occur in
12842       // practice that one of the condition inputs to the select is also one of
12843       // the outputs, we currently can't deal with this.
12844       if (User->getOpcode() == ISD::SELECT) {
12845         if (User->getOperand(0) == PromOps[i])
12846           return SDValue();
12847       } else if (User->getOpcode() == ISD::SELECT_CC) {
12848         if (User->getOperand(0) == PromOps[i] ||
12849             User->getOperand(1) == PromOps[i])
12850           return SDValue();
12851       }
12852     }
12853   }
12854 
12855   // Replace all inputs with the extension operand.
12856   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12857     // Constants may have users outside the cluster of to-be-promoted nodes,
12858     // and so we need to replace those as we do the promotions.
12859     if (isa<ConstantSDNode>(Inputs[i]))
12860       continue;
12861     else
12862       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12863   }
12864 
12865   std::list<HandleSDNode> PromOpHandles;
12866   for (auto &PromOp : PromOps)
12867     PromOpHandles.emplace_back(PromOp);
12868 
12869   // Replace all operations (these are all the same, but have a different
12870   // (i1) return type). DAG.getNode will validate that the types of
12871   // a binary operator match, so go through the list in reverse so that
12872   // we've likely promoted both operands first. Any intermediate truncations or
12873   // extensions disappear.
12874   while (!PromOpHandles.empty()) {
12875     SDValue PromOp = PromOpHandles.back().getValue();
12876     PromOpHandles.pop_back();
12877 
12878     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12879         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12880         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12881         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12882       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12883           PromOp.getOperand(0).getValueType() != MVT::i1) {
12884         // The operand is not yet ready (see comment below).
12885         PromOpHandles.emplace_front(PromOp);
12886         continue;
12887       }
12888 
12889       SDValue RepValue = PromOp.getOperand(0);
12890       if (isa<ConstantSDNode>(RepValue))
12891         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12892 
12893       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12894       continue;
12895     }
12896 
12897     unsigned C;
12898     switch (PromOp.getOpcode()) {
12899     default:             C = 0; break;
12900     case ISD::SELECT:    C = 1; break;
12901     case ISD::SELECT_CC: C = 2; break;
12902     }
12903 
12904     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12905          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12906         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12907          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12908       // The to-be-promoted operands of this node have not yet been
12909       // promoted (this should be rare because we're going through the
12910       // list backward, but if one of the operands has several users in
12911       // this cluster of to-be-promoted nodes, it is possible).
12912       PromOpHandles.emplace_front(PromOp);
12913       continue;
12914     }
12915 
12916     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12917                                 PromOp.getNode()->op_end());
12918 
12919     // If there are any constant inputs, make sure they're replaced now.
12920     for (unsigned i = 0; i < 2; ++i)
12921       if (isa<ConstantSDNode>(Ops[C+i]))
12922         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12923 
12924     DAG.ReplaceAllUsesOfValueWith(PromOp,
12925       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12926   }
12927 
12928   // Now we're left with the initial truncation itself.
12929   if (N->getOpcode() == ISD::TRUNCATE)
12930     return N->getOperand(0);
12931 
12932   // Otherwise, this is a comparison. The operands to be compared have just
12933   // changed type (to i1), but everything else is the same.
12934   return SDValue(N, 0);
12935 }
12936 
12937 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12938                                                   DAGCombinerInfo &DCI) const {
12939   SelectionDAG &DAG = DCI.DAG;
12940   SDLoc dl(N);
12941 
12942   // If we're tracking CR bits, we need to be careful that we don't have:
12943   //   zext(binary-ops(trunc(x), trunc(y)))
12944   // or
12945   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12946   // such that we're unnecessarily moving things into CR bits that can more
12947   // efficiently stay in GPRs. Note that if we're not certain that the high
12948   // bits are set as required by the final extension, we still may need to do
12949   // some masking to get the proper behavior.
12950 
12951   // This same functionality is important on PPC64 when dealing with
12952   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12953   // the return values of functions. Because it is so similar, it is handled
12954   // here as well.
12955 
12956   if (N->getValueType(0) != MVT::i32 &&
12957       N->getValueType(0) != MVT::i64)
12958     return SDValue();
12959 
12960   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12961         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12962     return SDValue();
12963 
12964   if (N->getOperand(0).getOpcode() != ISD::AND &&
12965       N->getOperand(0).getOpcode() != ISD::OR  &&
12966       N->getOperand(0).getOpcode() != ISD::XOR &&
12967       N->getOperand(0).getOpcode() != ISD::SELECT &&
12968       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12969     return SDValue();
12970 
12971   SmallVector<SDValue, 4> Inputs;
12972   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12973   SmallPtrSet<SDNode *, 16> Visited;
12974 
12975   // Visit all inputs, collect all binary operations (and, or, xor and
12976   // select) that are all fed by truncations.
12977   while (!BinOps.empty()) {
12978     SDValue BinOp = BinOps.back();
12979     BinOps.pop_back();
12980 
12981     if (!Visited.insert(BinOp.getNode()).second)
12982       continue;
12983 
12984     PromOps.push_back(BinOp);
12985 
12986     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12987       // The condition of the select is not promoted.
12988       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12989         continue;
12990       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12991         continue;
12992 
12993       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12994           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12995         Inputs.push_back(BinOp.getOperand(i));
12996       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12997                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12998                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12999                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13000                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13001         BinOps.push_back(BinOp.getOperand(i));
13002       } else {
13003         // We have an input that is not a truncation or another binary
13004         // operation; we'll abort this transformation.
13005         return SDValue();
13006       }
13007     }
13008   }
13009 
13010   // The operands of a select that must be truncated when the select is
13011   // promoted because the operand is actually part of the to-be-promoted set.
13012   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13013 
13014   // Make sure that this is a self-contained cluster of operations (which
13015   // is not quite the same thing as saying that everything has only one
13016   // use).
13017   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13018     if (isa<ConstantSDNode>(Inputs[i]))
13019       continue;
13020 
13021     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13022                               UE = Inputs[i].getNode()->use_end();
13023          UI != UE; ++UI) {
13024       SDNode *User = *UI;
13025       if (User != N && !Visited.count(User))
13026         return SDValue();
13027 
13028       // If we're going to promote the non-output-value operand(s) or SELECT or
13029       // SELECT_CC, record them for truncation.
13030       if (User->getOpcode() == ISD::SELECT) {
13031         if (User->getOperand(0) == Inputs[i])
13032           SelectTruncOp[0].insert(std::make_pair(User,
13033                                     User->getOperand(0).getValueType()));
13034       } else if (User->getOpcode() == ISD::SELECT_CC) {
13035         if (User->getOperand(0) == Inputs[i])
13036           SelectTruncOp[0].insert(std::make_pair(User,
13037                                     User->getOperand(0).getValueType()));
13038         if (User->getOperand(1) == Inputs[i])
13039           SelectTruncOp[1].insert(std::make_pair(User,
13040                                     User->getOperand(1).getValueType()));
13041       }
13042     }
13043   }
13044 
13045   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13046     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13047                               UE = PromOps[i].getNode()->use_end();
13048          UI != UE; ++UI) {
13049       SDNode *User = *UI;
13050       if (User != N && !Visited.count(User))
13051         return SDValue();
13052 
13053       // If we're going to promote the non-output-value operand(s) or SELECT or
13054       // SELECT_CC, record them for truncation.
13055       if (User->getOpcode() == ISD::SELECT) {
13056         if (User->getOperand(0) == PromOps[i])
13057           SelectTruncOp[0].insert(std::make_pair(User,
13058                                     User->getOperand(0).getValueType()));
13059       } else if (User->getOpcode() == ISD::SELECT_CC) {
13060         if (User->getOperand(0) == PromOps[i])
13061           SelectTruncOp[0].insert(std::make_pair(User,
13062                                     User->getOperand(0).getValueType()));
13063         if (User->getOperand(1) == PromOps[i])
13064           SelectTruncOp[1].insert(std::make_pair(User,
13065                                     User->getOperand(1).getValueType()));
13066       }
13067     }
13068   }
13069 
13070   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13071   bool ReallyNeedsExt = false;
13072   if (N->getOpcode() != ISD::ANY_EXTEND) {
13073     // If all of the inputs are not already sign/zero extended, then
13074     // we'll still need to do that at the end.
13075     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13076       if (isa<ConstantSDNode>(Inputs[i]))
13077         continue;
13078 
13079       unsigned OpBits =
13080         Inputs[i].getOperand(0).getValueSizeInBits();
13081       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13082 
13083       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13084            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13085                                   APInt::getHighBitsSet(OpBits,
13086                                                         OpBits-PromBits))) ||
13087           (N->getOpcode() == ISD::SIGN_EXTEND &&
13088            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13089              (OpBits-(PromBits-1)))) {
13090         ReallyNeedsExt = true;
13091         break;
13092       }
13093     }
13094   }
13095 
13096   // Replace all inputs, either with the truncation operand, or a
13097   // truncation or extension to the final output type.
13098   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13099     // Constant inputs need to be replaced with the to-be-promoted nodes that
13100     // use them because they might have users outside of the cluster of
13101     // promoted nodes.
13102     if (isa<ConstantSDNode>(Inputs[i]))
13103       continue;
13104 
13105     SDValue InSrc = Inputs[i].getOperand(0);
13106     if (Inputs[i].getValueType() == N->getValueType(0))
13107       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13108     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13109       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13110         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13111     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13112       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13113         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13114     else
13115       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13116         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13117   }
13118 
13119   std::list<HandleSDNode> PromOpHandles;
13120   for (auto &PromOp : PromOps)
13121     PromOpHandles.emplace_back(PromOp);
13122 
13123   // Replace all operations (these are all the same, but have a different
13124   // (promoted) return type). DAG.getNode will validate that the types of
13125   // a binary operator match, so go through the list in reverse so that
13126   // we've likely promoted both operands first.
13127   while (!PromOpHandles.empty()) {
13128     SDValue PromOp = PromOpHandles.back().getValue();
13129     PromOpHandles.pop_back();
13130 
13131     unsigned C;
13132     switch (PromOp.getOpcode()) {
13133     default:             C = 0; break;
13134     case ISD::SELECT:    C = 1; break;
13135     case ISD::SELECT_CC: C = 2; break;
13136     }
13137 
13138     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13139          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13140         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13141          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13142       // The to-be-promoted operands of this node have not yet been
13143       // promoted (this should be rare because we're going through the
13144       // list backward, but if one of the operands has several users in
13145       // this cluster of to-be-promoted nodes, it is possible).
13146       PromOpHandles.emplace_front(PromOp);
13147       continue;
13148     }
13149 
13150     // For SELECT and SELECT_CC nodes, we do a similar check for any
13151     // to-be-promoted comparison inputs.
13152     if (PromOp.getOpcode() == ISD::SELECT ||
13153         PromOp.getOpcode() == ISD::SELECT_CC) {
13154       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13155            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13156           (SelectTruncOp[1].count(PromOp.getNode()) &&
13157            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13158         PromOpHandles.emplace_front(PromOp);
13159         continue;
13160       }
13161     }
13162 
13163     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13164                                 PromOp.getNode()->op_end());
13165 
13166     // If this node has constant inputs, then they'll need to be promoted here.
13167     for (unsigned i = 0; i < 2; ++i) {
13168       if (!isa<ConstantSDNode>(Ops[C+i]))
13169         continue;
13170       if (Ops[C+i].getValueType() == N->getValueType(0))
13171         continue;
13172 
13173       if (N->getOpcode() == ISD::SIGN_EXTEND)
13174         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13175       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13176         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13177       else
13178         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13179     }
13180 
13181     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13182     // truncate them again to the original value type.
13183     if (PromOp.getOpcode() == ISD::SELECT ||
13184         PromOp.getOpcode() == ISD::SELECT_CC) {
13185       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13186       if (SI0 != SelectTruncOp[0].end())
13187         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13188       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13189       if (SI1 != SelectTruncOp[1].end())
13190         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13191     }
13192 
13193     DAG.ReplaceAllUsesOfValueWith(PromOp,
13194       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13195   }
13196 
13197   // Now we're left with the initial extension itself.
13198   if (!ReallyNeedsExt)
13199     return N->getOperand(0);
13200 
13201   // To zero extend, just mask off everything except for the first bit (in the
13202   // i1 case).
13203   if (N->getOpcode() == ISD::ZERO_EXTEND)
13204     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13205                        DAG.getConstant(APInt::getLowBitsSet(
13206                                          N->getValueSizeInBits(0), PromBits),
13207                                        dl, N->getValueType(0)));
13208 
13209   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13210          "Invalid extension type");
13211   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13212   SDValue ShiftCst =
13213       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13214   return DAG.getNode(
13215       ISD::SRA, dl, N->getValueType(0),
13216       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13217       ShiftCst);
13218 }
13219 
13220 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13221                                         DAGCombinerInfo &DCI) const {
13222   assert(N->getOpcode() == ISD::SETCC &&
13223          "Should be called with a SETCC node");
13224 
13225   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13226   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13227     SDValue LHS = N->getOperand(0);
13228     SDValue RHS = N->getOperand(1);
13229 
13230     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13231     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13232         LHS.hasOneUse())
13233       std::swap(LHS, RHS);
13234 
13235     // x == 0-y --> x+y == 0
13236     // x != 0-y --> x+y != 0
13237     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13238         RHS.hasOneUse()) {
13239       SDLoc DL(N);
13240       SelectionDAG &DAG = DCI.DAG;
13241       EVT VT = N->getValueType(0);
13242       EVT OpVT = LHS.getValueType();
13243       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13244       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13245     }
13246   }
13247 
13248   return DAGCombineTruncBoolExt(N, DCI);
13249 }
13250 
13251 // Is this an extending load from an f32 to an f64?
13252 static bool isFPExtLoad(SDValue Op) {
13253   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13254     return LD->getExtensionType() == ISD::EXTLOAD &&
13255       Op.getValueType() == MVT::f64;
13256   return false;
13257 }
13258 
13259 /// Reduces the number of fp-to-int conversion when building a vector.
13260 ///
13261 /// If this vector is built out of floating to integer conversions,
13262 /// transform it to a vector built out of floating point values followed by a
13263 /// single floating to integer conversion of the vector.
13264 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13265 /// becomes (fptosi (build_vector ($A, $B, ...)))
13266 SDValue PPCTargetLowering::
13267 combineElementTruncationToVectorTruncation(SDNode *N,
13268                                            DAGCombinerInfo &DCI) const {
13269   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13270          "Should be called with a BUILD_VECTOR node");
13271 
13272   SelectionDAG &DAG = DCI.DAG;
13273   SDLoc dl(N);
13274 
13275   SDValue FirstInput = N->getOperand(0);
13276   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13277          "The input operand must be an fp-to-int conversion.");
13278 
13279   // This combine happens after legalization so the fp_to_[su]i nodes are
13280   // already converted to PPCSISD nodes.
13281   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13282   if (FirstConversion == PPCISD::FCTIDZ ||
13283       FirstConversion == PPCISD::FCTIDUZ ||
13284       FirstConversion == PPCISD::FCTIWZ ||
13285       FirstConversion == PPCISD::FCTIWUZ) {
13286     bool IsSplat = true;
13287     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13288       FirstConversion == PPCISD::FCTIWUZ;
13289     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13290     SmallVector<SDValue, 4> Ops;
13291     EVT TargetVT = N->getValueType(0);
13292     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13293       SDValue NextOp = N->getOperand(i);
13294       if (NextOp.getOpcode() != PPCISD::MFVSR)
13295         return SDValue();
13296       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13297       if (NextConversion != FirstConversion)
13298         return SDValue();
13299       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13300       // This is not valid if the input was originally double precision. It is
13301       // also not profitable to do unless this is an extending load in which
13302       // case doing this combine will allow us to combine consecutive loads.
13303       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13304         return SDValue();
13305       if (N->getOperand(i) != FirstInput)
13306         IsSplat = false;
13307     }
13308 
13309     // If this is a splat, we leave it as-is since there will be only a single
13310     // fp-to-int conversion followed by a splat of the integer. This is better
13311     // for 32-bit and smaller ints and neutral for 64-bit ints.
13312     if (IsSplat)
13313       return SDValue();
13314 
13315     // Now that we know we have the right type of node, get its operands
13316     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13317       SDValue In = N->getOperand(i).getOperand(0);
13318       if (Is32Bit) {
13319         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13320         // here, we know that all inputs are extending loads so this is safe).
13321         if (In.isUndef())
13322           Ops.push_back(DAG.getUNDEF(SrcVT));
13323         else {
13324           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13325                                       MVT::f32, In.getOperand(0),
13326                                       DAG.getIntPtrConstant(1, dl));
13327           Ops.push_back(Trunc);
13328         }
13329       } else
13330         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13331     }
13332 
13333     unsigned Opcode;
13334     if (FirstConversion == PPCISD::FCTIDZ ||
13335         FirstConversion == PPCISD::FCTIWZ)
13336       Opcode = ISD::FP_TO_SINT;
13337     else
13338       Opcode = ISD::FP_TO_UINT;
13339 
13340     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13341     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13342     return DAG.getNode(Opcode, dl, TargetVT, BV);
13343   }
13344   return SDValue();
13345 }
13346 
13347 /// Reduce the number of loads when building a vector.
13348 ///
13349 /// Building a vector out of multiple loads can be converted to a load
13350 /// of the vector type if the loads are consecutive. If the loads are
13351 /// consecutive but in descending order, a shuffle is added at the end
13352 /// to reorder the vector.
13353 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13354   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13355          "Should be called with a BUILD_VECTOR node");
13356 
13357   SDLoc dl(N);
13358 
13359   // Return early for non byte-sized type, as they can't be consecutive.
13360   if (!N->getValueType(0).getVectorElementType().isByteSized())
13361     return SDValue();
13362 
13363   bool InputsAreConsecutiveLoads = true;
13364   bool InputsAreReverseConsecutive = true;
13365   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13366   SDValue FirstInput = N->getOperand(0);
13367   bool IsRoundOfExtLoad = false;
13368 
13369   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13370       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13371     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13372     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13373   }
13374   // Not a build vector of (possibly fp_rounded) loads.
13375   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13376       N->getNumOperands() == 1)
13377     return SDValue();
13378 
13379   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13380     // If any inputs are fp_round(extload), they all must be.
13381     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13382       return SDValue();
13383 
13384     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13385       N->getOperand(i);
13386     if (NextInput.getOpcode() != ISD::LOAD)
13387       return SDValue();
13388 
13389     SDValue PreviousInput =
13390       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13391     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13392     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13393 
13394     // If any inputs are fp_round(extload), they all must be.
13395     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13396       return SDValue();
13397 
13398     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13399       InputsAreConsecutiveLoads = false;
13400     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13401       InputsAreReverseConsecutive = false;
13402 
13403     // Exit early if the loads are neither consecutive nor reverse consecutive.
13404     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13405       return SDValue();
13406   }
13407 
13408   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13409          "The loads cannot be both consecutive and reverse consecutive.");
13410 
13411   SDValue FirstLoadOp =
13412     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13413   SDValue LastLoadOp =
13414     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13415                        N->getOperand(N->getNumOperands()-1);
13416 
13417   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13418   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13419   if (InputsAreConsecutiveLoads) {
13420     assert(LD1 && "Input needs to be a LoadSDNode.");
13421     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13422                        LD1->getBasePtr(), LD1->getPointerInfo(),
13423                        LD1->getAlignment());
13424   }
13425   if (InputsAreReverseConsecutive) {
13426     assert(LDL && "Input needs to be a LoadSDNode.");
13427     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13428                                LDL->getBasePtr(), LDL->getPointerInfo(),
13429                                LDL->getAlignment());
13430     SmallVector<int, 16> Ops;
13431     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13432       Ops.push_back(i);
13433 
13434     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13435                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13436   }
13437   return SDValue();
13438 }
13439 
13440 // This function adds the required vector_shuffle needed to get
13441 // the elements of the vector extract in the correct position
13442 // as specified by the CorrectElems encoding.
13443 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13444                                       SDValue Input, uint64_t Elems,
13445                                       uint64_t CorrectElems) {
13446   SDLoc dl(N);
13447 
13448   unsigned NumElems = Input.getValueType().getVectorNumElements();
13449   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13450 
13451   // Knowing the element indices being extracted from the original
13452   // vector and the order in which they're being inserted, just put
13453   // them at element indices required for the instruction.
13454   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13455     if (DAG.getDataLayout().isLittleEndian())
13456       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13457     else
13458       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13459     CorrectElems = CorrectElems >> 8;
13460     Elems = Elems >> 8;
13461   }
13462 
13463   SDValue Shuffle =
13464       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13465                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13466 
13467   EVT VT = N->getValueType(0);
13468   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13469 
13470   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13471                                Input.getValueType().getVectorElementType(),
13472                                VT.getVectorNumElements());
13473   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13474                      DAG.getValueType(ExtVT));
13475 }
13476 
13477 // Look for build vector patterns where input operands come from sign
13478 // extended vector_extract elements of specific indices. If the correct indices
13479 // aren't used, add a vector shuffle to fix up the indices and create
13480 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13481 // during instruction selection.
13482 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13483   // This array encodes the indices that the vector sign extend instructions
13484   // extract from when extending from one type to another for both BE and LE.
13485   // The right nibble of each byte corresponds to the LE incides.
13486   // and the left nibble of each byte corresponds to the BE incides.
13487   // For example: 0x3074B8FC  byte->word
13488   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13489   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13490   // For example: 0x000070F8  byte->double word
13491   // For LE: the allowed indices are: 0x0,0x8
13492   // For BE: the allowed indices are: 0x7,0xF
13493   uint64_t TargetElems[] = {
13494       0x3074B8FC, // b->w
13495       0x000070F8, // b->d
13496       0x10325476, // h->w
13497       0x00003074, // h->d
13498       0x00001032, // w->d
13499   };
13500 
13501   uint64_t Elems = 0;
13502   int Index;
13503   SDValue Input;
13504 
13505   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13506     if (!Op)
13507       return false;
13508     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13509         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13510       return false;
13511 
13512     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13513     // of the right width.
13514     SDValue Extract = Op.getOperand(0);
13515     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13516       Extract = Extract.getOperand(0);
13517     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13518       return false;
13519 
13520     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13521     if (!ExtOp)
13522       return false;
13523 
13524     Index = ExtOp->getZExtValue();
13525     if (Input && Input != Extract.getOperand(0))
13526       return false;
13527 
13528     if (!Input)
13529       Input = Extract.getOperand(0);
13530 
13531     Elems = Elems << 8;
13532     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13533     Elems |= Index;
13534 
13535     return true;
13536   };
13537 
13538   // If the build vector operands aren't sign extended vector extracts,
13539   // of the same input vector, then return.
13540   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13541     if (!isSExtOfVecExtract(N->getOperand(i))) {
13542       return SDValue();
13543     }
13544   }
13545 
13546   // If the vector extract indicies are not correct, add the appropriate
13547   // vector_shuffle.
13548   int TgtElemArrayIdx;
13549   int InputSize = Input.getValueType().getScalarSizeInBits();
13550   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13551   if (InputSize + OutputSize == 40)
13552     TgtElemArrayIdx = 0;
13553   else if (InputSize + OutputSize == 72)
13554     TgtElemArrayIdx = 1;
13555   else if (InputSize + OutputSize == 48)
13556     TgtElemArrayIdx = 2;
13557   else if (InputSize + OutputSize == 80)
13558     TgtElemArrayIdx = 3;
13559   else if (InputSize + OutputSize == 96)
13560     TgtElemArrayIdx = 4;
13561   else
13562     return SDValue();
13563 
13564   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13565   CorrectElems = DAG.getDataLayout().isLittleEndian()
13566                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13567                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13568   if (Elems != CorrectElems) {
13569     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13570   }
13571 
13572   // Regular lowering will catch cases where a shuffle is not needed.
13573   return SDValue();
13574 }
13575 
13576 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13577                                                  DAGCombinerInfo &DCI) const {
13578   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13579          "Should be called with a BUILD_VECTOR node");
13580 
13581   SelectionDAG &DAG = DCI.DAG;
13582   SDLoc dl(N);
13583 
13584   if (!Subtarget.hasVSX())
13585     return SDValue();
13586 
13587   // The target independent DAG combiner will leave a build_vector of
13588   // float-to-int conversions intact. We can generate MUCH better code for
13589   // a float-to-int conversion of a vector of floats.
13590   SDValue FirstInput = N->getOperand(0);
13591   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13592     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13593     if (Reduced)
13594       return Reduced;
13595   }
13596 
13597   // If we're building a vector out of consecutive loads, just load that
13598   // vector type.
13599   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13600   if (Reduced)
13601     return Reduced;
13602 
13603   // If we're building a vector out of extended elements from another vector
13604   // we have P9 vector integer extend instructions. The code assumes legal
13605   // input types (i.e. it can't handle things like v4i16) so do not run before
13606   // legalization.
13607   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13608     Reduced = combineBVOfVecSExt(N, DAG);
13609     if (Reduced)
13610       return Reduced;
13611   }
13612 
13613 
13614   if (N->getValueType(0) != MVT::v2f64)
13615     return SDValue();
13616 
13617   // Looking for:
13618   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13619   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13620       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13621     return SDValue();
13622   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13623       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13624     return SDValue();
13625   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13626     return SDValue();
13627 
13628   SDValue Ext1 = FirstInput.getOperand(0);
13629   SDValue Ext2 = N->getOperand(1).getOperand(0);
13630   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13631      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13632     return SDValue();
13633 
13634   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13635   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13636   if (!Ext1Op || !Ext2Op)
13637     return SDValue();
13638   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13639       Ext1.getOperand(0) != Ext2.getOperand(0))
13640     return SDValue();
13641 
13642   int FirstElem = Ext1Op->getZExtValue();
13643   int SecondElem = Ext2Op->getZExtValue();
13644   int SubvecIdx;
13645   if (FirstElem == 0 && SecondElem == 1)
13646     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13647   else if (FirstElem == 2 && SecondElem == 3)
13648     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13649   else
13650     return SDValue();
13651 
13652   SDValue SrcVec = Ext1.getOperand(0);
13653   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13654     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13655   return DAG.getNode(NodeType, dl, MVT::v2f64,
13656                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13657 }
13658 
13659 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13660                                               DAGCombinerInfo &DCI) const {
13661   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13662           N->getOpcode() == ISD::UINT_TO_FP) &&
13663          "Need an int -> FP conversion node here");
13664 
13665   if (useSoftFloat() || !Subtarget.has64BitSupport())
13666     return SDValue();
13667 
13668   SelectionDAG &DAG = DCI.DAG;
13669   SDLoc dl(N);
13670   SDValue Op(N, 0);
13671 
13672   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13673   // from the hardware.
13674   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13675     return SDValue();
13676   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13677       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13678     return SDValue();
13679 
13680   SDValue FirstOperand(Op.getOperand(0));
13681   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13682     (FirstOperand.getValueType() == MVT::i8 ||
13683      FirstOperand.getValueType() == MVT::i16);
13684   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13685     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13686     bool DstDouble = Op.getValueType() == MVT::f64;
13687     unsigned ConvOp = Signed ?
13688       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13689       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13690     SDValue WidthConst =
13691       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13692                             dl, false);
13693     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13694     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13695     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13696                                          DAG.getVTList(MVT::f64, MVT::Other),
13697                                          Ops, MVT::i8, LDN->getMemOperand());
13698 
13699     // For signed conversion, we need to sign-extend the value in the VSR
13700     if (Signed) {
13701       SDValue ExtOps[] = { Ld, WidthConst };
13702       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13703       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13704     } else
13705       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13706   }
13707 
13708 
13709   // For i32 intermediate values, unfortunately, the conversion functions
13710   // leave the upper 32 bits of the value are undefined. Within the set of
13711   // scalar instructions, we have no method for zero- or sign-extending the
13712   // value. Thus, we cannot handle i32 intermediate values here.
13713   if (Op.getOperand(0).getValueType() == MVT::i32)
13714     return SDValue();
13715 
13716   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13717          "UINT_TO_FP is supported only with FPCVT");
13718 
13719   // If we have FCFIDS, then use it when converting to single-precision.
13720   // Otherwise, convert to double-precision and then round.
13721   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13722                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13723                                                             : PPCISD::FCFIDS)
13724                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13725                                                             : PPCISD::FCFID);
13726   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13727                   ? MVT::f32
13728                   : MVT::f64;
13729 
13730   // If we're converting from a float, to an int, and back to a float again,
13731   // then we don't need the store/load pair at all.
13732   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13733        Subtarget.hasFPCVT()) ||
13734       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13735     SDValue Src = Op.getOperand(0).getOperand(0);
13736     if (Src.getValueType() == MVT::f32) {
13737       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13738       DCI.AddToWorklist(Src.getNode());
13739     } else if (Src.getValueType() != MVT::f64) {
13740       // Make sure that we don't pick up a ppc_fp128 source value.
13741       return SDValue();
13742     }
13743 
13744     unsigned FCTOp =
13745       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13746                                                         PPCISD::FCTIDUZ;
13747 
13748     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13749     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13750 
13751     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13752       FP = DAG.getNode(ISD::FP_ROUND, dl,
13753                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13754       DCI.AddToWorklist(FP.getNode());
13755     }
13756 
13757     return FP;
13758   }
13759 
13760   return SDValue();
13761 }
13762 
13763 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13764 // builtins) into loads with swaps.
13765 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13766                                               DAGCombinerInfo &DCI) const {
13767   SelectionDAG &DAG = DCI.DAG;
13768   SDLoc dl(N);
13769   SDValue Chain;
13770   SDValue Base;
13771   MachineMemOperand *MMO;
13772 
13773   switch (N->getOpcode()) {
13774   default:
13775     llvm_unreachable("Unexpected opcode for little endian VSX load");
13776   case ISD::LOAD: {
13777     LoadSDNode *LD = cast<LoadSDNode>(N);
13778     Chain = LD->getChain();
13779     Base = LD->getBasePtr();
13780     MMO = LD->getMemOperand();
13781     // If the MMO suggests this isn't a load of a full vector, leave
13782     // things alone.  For a built-in, we have to make the change for
13783     // correctness, so if there is a size problem that will be a bug.
13784     if (MMO->getSize() < 16)
13785       return SDValue();
13786     break;
13787   }
13788   case ISD::INTRINSIC_W_CHAIN: {
13789     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13790     Chain = Intrin->getChain();
13791     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13792     // us what we want. Get operand 2 instead.
13793     Base = Intrin->getOperand(2);
13794     MMO = Intrin->getMemOperand();
13795     break;
13796   }
13797   }
13798 
13799   MVT VecTy = N->getValueType(0).getSimpleVT();
13800 
13801   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13802   // aligned and the type is a vector with elements up to 4 bytes
13803   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13804       VecTy.getScalarSizeInBits() <= 32) {
13805     return SDValue();
13806   }
13807 
13808   SDValue LoadOps[] = { Chain, Base };
13809   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13810                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13811                                          LoadOps, MVT::v2f64, MMO);
13812 
13813   DCI.AddToWorklist(Load.getNode());
13814   Chain = Load.getValue(1);
13815   SDValue Swap = DAG.getNode(
13816       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13817   DCI.AddToWorklist(Swap.getNode());
13818 
13819   // Add a bitcast if the resulting load type doesn't match v2f64.
13820   if (VecTy != MVT::v2f64) {
13821     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13822     DCI.AddToWorklist(N.getNode());
13823     // Package {bitcast value, swap's chain} to match Load's shape.
13824     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13825                        N, Swap.getValue(1));
13826   }
13827 
13828   return Swap;
13829 }
13830 
13831 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13832 // builtins) into stores with swaps.
13833 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13834                                                DAGCombinerInfo &DCI) const {
13835   SelectionDAG &DAG = DCI.DAG;
13836   SDLoc dl(N);
13837   SDValue Chain;
13838   SDValue Base;
13839   unsigned SrcOpnd;
13840   MachineMemOperand *MMO;
13841 
13842   switch (N->getOpcode()) {
13843   default:
13844     llvm_unreachable("Unexpected opcode for little endian VSX store");
13845   case ISD::STORE: {
13846     StoreSDNode *ST = cast<StoreSDNode>(N);
13847     Chain = ST->getChain();
13848     Base = ST->getBasePtr();
13849     MMO = ST->getMemOperand();
13850     SrcOpnd = 1;
13851     // If the MMO suggests this isn't a store of a full vector, leave
13852     // things alone.  For a built-in, we have to make the change for
13853     // correctness, so if there is a size problem that will be a bug.
13854     if (MMO->getSize() < 16)
13855       return SDValue();
13856     break;
13857   }
13858   case ISD::INTRINSIC_VOID: {
13859     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13860     Chain = Intrin->getChain();
13861     // Intrin->getBasePtr() oddly does not get what we want.
13862     Base = Intrin->getOperand(3);
13863     MMO = Intrin->getMemOperand();
13864     SrcOpnd = 2;
13865     break;
13866   }
13867   }
13868 
13869   SDValue Src = N->getOperand(SrcOpnd);
13870   MVT VecTy = Src.getValueType().getSimpleVT();
13871 
13872   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13873   // aligned and the type is a vector with elements up to 4 bytes
13874   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13875       VecTy.getScalarSizeInBits() <= 32) {
13876     return SDValue();
13877   }
13878 
13879   // All stores are done as v2f64 and possible bit cast.
13880   if (VecTy != MVT::v2f64) {
13881     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13882     DCI.AddToWorklist(Src.getNode());
13883   }
13884 
13885   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13886                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13887   DCI.AddToWorklist(Swap.getNode());
13888   Chain = Swap.getValue(1);
13889   SDValue StoreOps[] = { Chain, Swap, Base };
13890   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13891                                           DAG.getVTList(MVT::Other),
13892                                           StoreOps, VecTy, MMO);
13893   DCI.AddToWorklist(Store.getNode());
13894   return Store;
13895 }
13896 
13897 // Handle DAG combine for STORE (FP_TO_INT F).
13898 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13899                                                DAGCombinerInfo &DCI) const {
13900 
13901   SelectionDAG &DAG = DCI.DAG;
13902   SDLoc dl(N);
13903   unsigned Opcode = N->getOperand(1).getOpcode();
13904 
13905   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13906          && "Not a FP_TO_INT Instruction!");
13907 
13908   SDValue Val = N->getOperand(1).getOperand(0);
13909   EVT Op1VT = N->getOperand(1).getValueType();
13910   EVT ResVT = Val.getValueType();
13911 
13912   // Floating point types smaller than 32 bits are not legal on Power.
13913   if (ResVT.getScalarSizeInBits() < 32)
13914     return SDValue();
13915 
13916   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13917   bool ValidTypeForStoreFltAsInt =
13918         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13919          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13920 
13921   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13922       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13923     return SDValue();
13924 
13925   // Extend f32 values to f64
13926   if (ResVT.getScalarSizeInBits() == 32) {
13927     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13928     DCI.AddToWorklist(Val.getNode());
13929   }
13930 
13931   // Set signed or unsigned conversion opcode.
13932   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13933                           PPCISD::FP_TO_SINT_IN_VSR :
13934                           PPCISD::FP_TO_UINT_IN_VSR;
13935 
13936   Val = DAG.getNode(ConvOpcode,
13937                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13938   DCI.AddToWorklist(Val.getNode());
13939 
13940   // Set number of bytes being converted.
13941   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13942   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13943                     DAG.getIntPtrConstant(ByteSize, dl, false),
13944                     DAG.getValueType(Op1VT) };
13945 
13946   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13947           DAG.getVTList(MVT::Other), Ops,
13948           cast<StoreSDNode>(N)->getMemoryVT(),
13949           cast<StoreSDNode>(N)->getMemOperand());
13950 
13951   DCI.AddToWorklist(Val.getNode());
13952   return Val;
13953 }
13954 
13955 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13956                                                 LSBaseSDNode *LSBase,
13957                                                 DAGCombinerInfo &DCI) const {
13958   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13959         "Not a reverse memop pattern!");
13960 
13961   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13962     auto Mask = SVN->getMask();
13963     int i = 0;
13964     auto I = Mask.rbegin();
13965     auto E = Mask.rend();
13966 
13967     for (; I != E; ++I) {
13968       if (*I != i)
13969         return false;
13970       i++;
13971     }
13972     return true;
13973   };
13974 
13975   SelectionDAG &DAG = DCI.DAG;
13976   EVT VT = SVN->getValueType(0);
13977 
13978   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13979     return SDValue();
13980 
13981   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13982   // See comment in PPCVSXSwapRemoval.cpp.
13983   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13984   if (!Subtarget.hasP9Vector())
13985     return SDValue();
13986 
13987   if(!IsElementReverse(SVN))
13988     return SDValue();
13989 
13990   if (LSBase->getOpcode() == ISD::LOAD) {
13991     SDLoc dl(SVN);
13992     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13993     return DAG.getMemIntrinsicNode(
13994         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13995         LSBase->getMemoryVT(), LSBase->getMemOperand());
13996   }
13997 
13998   if (LSBase->getOpcode() == ISD::STORE) {
13999     SDLoc dl(LSBase);
14000     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14001                           LSBase->getBasePtr()};
14002     return DAG.getMemIntrinsicNode(
14003         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14004         LSBase->getMemoryVT(), LSBase->getMemOperand());
14005   }
14006 
14007   llvm_unreachable("Expected a load or store node here");
14008 }
14009 
14010 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14011                                              DAGCombinerInfo &DCI) const {
14012   SelectionDAG &DAG = DCI.DAG;
14013   SDLoc dl(N);
14014   switch (N->getOpcode()) {
14015   default: break;
14016   case ISD::ADD:
14017     return combineADD(N, DCI);
14018   case ISD::SHL:
14019     return combineSHL(N, DCI);
14020   case ISD::SRA:
14021     return combineSRA(N, DCI);
14022   case ISD::SRL:
14023     return combineSRL(N, DCI);
14024   case ISD::MUL:
14025     return combineMUL(N, DCI);
14026   case PPCISD::SHL:
14027     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14028         return N->getOperand(0);
14029     break;
14030   case PPCISD::SRL:
14031     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14032         return N->getOperand(0);
14033     break;
14034   case PPCISD::SRA:
14035     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14036       if (C->isNullValue() ||   //  0 >>s V -> 0.
14037           C->isAllOnesValue())    // -1 >>s V -> -1.
14038         return N->getOperand(0);
14039     }
14040     break;
14041   case ISD::SIGN_EXTEND:
14042   case ISD::ZERO_EXTEND:
14043   case ISD::ANY_EXTEND:
14044     return DAGCombineExtBoolTrunc(N, DCI);
14045   case ISD::TRUNCATE:
14046     return combineTRUNCATE(N, DCI);
14047   case ISD::SETCC:
14048     if (SDValue CSCC = combineSetCC(N, DCI))
14049       return CSCC;
14050     LLVM_FALLTHROUGH;
14051   case ISD::SELECT_CC:
14052     return DAGCombineTruncBoolExt(N, DCI);
14053   case ISD::SINT_TO_FP:
14054   case ISD::UINT_TO_FP:
14055     return combineFPToIntToFP(N, DCI);
14056   case ISD::VECTOR_SHUFFLE:
14057     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14058       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14059       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14060     }
14061     break;
14062   case ISD::STORE: {
14063 
14064     EVT Op1VT = N->getOperand(1).getValueType();
14065     unsigned Opcode = N->getOperand(1).getOpcode();
14066 
14067     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14068       SDValue Val= combineStoreFPToInt(N, DCI);
14069       if (Val)
14070         return Val;
14071     }
14072 
14073     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14074       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14075       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14076       if (Val)
14077         return Val;
14078     }
14079 
14080     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14081     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14082         N->getOperand(1).getNode()->hasOneUse() &&
14083         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14084          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14085 
14086       // STBRX can only handle simple types and it makes no sense to store less
14087       // two bytes in byte-reversed order.
14088       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14089       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14090         break;
14091 
14092       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14093       // Do an any-extend to 32-bits if this is a half-word input.
14094       if (BSwapOp.getValueType() == MVT::i16)
14095         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14096 
14097       // If the type of BSWAP operand is wider than stored memory width
14098       // it need to be shifted to the right side before STBRX.
14099       if (Op1VT.bitsGT(mVT)) {
14100         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14101         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14102                               DAG.getConstant(Shift, dl, MVT::i32));
14103         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14104         if (Op1VT == MVT::i64)
14105           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14106       }
14107 
14108       SDValue Ops[] = {
14109         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14110       };
14111       return
14112         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14113                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14114                                 cast<StoreSDNode>(N)->getMemOperand());
14115     }
14116 
14117     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14118     // So it can increase the chance of CSE constant construction.
14119     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14120         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14121       // Need to sign-extended to 64-bits to handle negative values.
14122       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14123       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14124                                     MemVT.getSizeInBits());
14125       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14126 
14127       // DAG.getTruncStore() can't be used here because it doesn't accept
14128       // the general (base + offset) addressing mode.
14129       // So we use UpdateNodeOperands and setTruncatingStore instead.
14130       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14131                              N->getOperand(3));
14132       cast<StoreSDNode>(N)->setTruncatingStore(true);
14133       return SDValue(N, 0);
14134     }
14135 
14136     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14137     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14138     if (Op1VT.isSimple()) {
14139       MVT StoreVT = Op1VT.getSimpleVT();
14140       if (Subtarget.needsSwapsForVSXMemOps() &&
14141           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14142            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14143         return expandVSXStoreForLE(N, DCI);
14144     }
14145     break;
14146   }
14147   case ISD::LOAD: {
14148     LoadSDNode *LD = cast<LoadSDNode>(N);
14149     EVT VT = LD->getValueType(0);
14150 
14151     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14152     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14153     if (VT.isSimple()) {
14154       MVT LoadVT = VT.getSimpleVT();
14155       if (Subtarget.needsSwapsForVSXMemOps() &&
14156           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14157            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14158         return expandVSXLoadForLE(N, DCI);
14159     }
14160 
14161     // We sometimes end up with a 64-bit integer load, from which we extract
14162     // two single-precision floating-point numbers. This happens with
14163     // std::complex<float>, and other similar structures, because of the way we
14164     // canonicalize structure copies. However, if we lack direct moves,
14165     // then the final bitcasts from the extracted integer values to the
14166     // floating-point numbers turn into store/load pairs. Even with direct moves,
14167     // just loading the two floating-point numbers is likely better.
14168     auto ReplaceTwoFloatLoad = [&]() {
14169       if (VT != MVT::i64)
14170         return false;
14171 
14172       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14173           LD->isVolatile())
14174         return false;
14175 
14176       //  We're looking for a sequence like this:
14177       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14178       //      t16: i64 = srl t13, Constant:i32<32>
14179       //    t17: i32 = truncate t16
14180       //  t18: f32 = bitcast t17
14181       //    t19: i32 = truncate t13
14182       //  t20: f32 = bitcast t19
14183 
14184       if (!LD->hasNUsesOfValue(2, 0))
14185         return false;
14186 
14187       auto UI = LD->use_begin();
14188       while (UI.getUse().getResNo() != 0) ++UI;
14189       SDNode *Trunc = *UI++;
14190       while (UI.getUse().getResNo() != 0) ++UI;
14191       SDNode *RightShift = *UI;
14192       if (Trunc->getOpcode() != ISD::TRUNCATE)
14193         std::swap(Trunc, RightShift);
14194 
14195       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14196           Trunc->getValueType(0) != MVT::i32 ||
14197           !Trunc->hasOneUse())
14198         return false;
14199       if (RightShift->getOpcode() != ISD::SRL ||
14200           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14201           RightShift->getConstantOperandVal(1) != 32 ||
14202           !RightShift->hasOneUse())
14203         return false;
14204 
14205       SDNode *Trunc2 = *RightShift->use_begin();
14206       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14207           Trunc2->getValueType(0) != MVT::i32 ||
14208           !Trunc2->hasOneUse())
14209         return false;
14210 
14211       SDNode *Bitcast = *Trunc->use_begin();
14212       SDNode *Bitcast2 = *Trunc2->use_begin();
14213 
14214       if (Bitcast->getOpcode() != ISD::BITCAST ||
14215           Bitcast->getValueType(0) != MVT::f32)
14216         return false;
14217       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14218           Bitcast2->getValueType(0) != MVT::f32)
14219         return false;
14220 
14221       if (Subtarget.isLittleEndian())
14222         std::swap(Bitcast, Bitcast2);
14223 
14224       // Bitcast has the second float (in memory-layout order) and Bitcast2
14225       // has the first one.
14226 
14227       SDValue BasePtr = LD->getBasePtr();
14228       if (LD->isIndexed()) {
14229         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14230                "Non-pre-inc AM on PPC?");
14231         BasePtr =
14232           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14233                       LD->getOffset());
14234       }
14235 
14236       auto MMOFlags =
14237           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14238       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14239                                       LD->getPointerInfo(), LD->getAlignment(),
14240                                       MMOFlags, LD->getAAInfo());
14241       SDValue AddPtr =
14242         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14243                     BasePtr, DAG.getIntPtrConstant(4, dl));
14244       SDValue FloatLoad2 = DAG.getLoad(
14245           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14246           LD->getPointerInfo().getWithOffset(4),
14247           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14248 
14249       if (LD->isIndexed()) {
14250         // Note that DAGCombine should re-form any pre-increment load(s) from
14251         // what is produced here if that makes sense.
14252         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14253       }
14254 
14255       DCI.CombineTo(Bitcast2, FloatLoad);
14256       DCI.CombineTo(Bitcast, FloatLoad2);
14257 
14258       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14259                                     SDValue(FloatLoad2.getNode(), 1));
14260       return true;
14261     };
14262 
14263     if (ReplaceTwoFloatLoad())
14264       return SDValue(N, 0);
14265 
14266     EVT MemVT = LD->getMemoryVT();
14267     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14268     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14269     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14270     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14271     if (LD->isUnindexed() && VT.isVector() &&
14272         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14273           // P8 and later hardware should just use LOAD.
14274           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14275                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14276          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14277           LD->getAlignment() >= ScalarABIAlignment)) &&
14278         LD->getAlignment() < ABIAlignment) {
14279       // This is a type-legal unaligned Altivec or QPX load.
14280       SDValue Chain = LD->getChain();
14281       SDValue Ptr = LD->getBasePtr();
14282       bool isLittleEndian = Subtarget.isLittleEndian();
14283 
14284       // This implements the loading of unaligned vectors as described in
14285       // the venerable Apple Velocity Engine overview. Specifically:
14286       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14287       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14288       //
14289       // The general idea is to expand a sequence of one or more unaligned
14290       // loads into an alignment-based permutation-control instruction (lvsl
14291       // or lvsr), a series of regular vector loads (which always truncate
14292       // their input address to an aligned address), and a series of
14293       // permutations.  The results of these permutations are the requested
14294       // loaded values.  The trick is that the last "extra" load is not taken
14295       // from the address you might suspect (sizeof(vector) bytes after the
14296       // last requested load), but rather sizeof(vector) - 1 bytes after the
14297       // last requested vector. The point of this is to avoid a page fault if
14298       // the base address happened to be aligned. This works because if the
14299       // base address is aligned, then adding less than a full vector length
14300       // will cause the last vector in the sequence to be (re)loaded.
14301       // Otherwise, the next vector will be fetched as you might suspect was
14302       // necessary.
14303 
14304       // We might be able to reuse the permutation generation from
14305       // a different base address offset from this one by an aligned amount.
14306       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14307       // optimization later.
14308       Intrinsic::ID Intr, IntrLD, IntrPerm;
14309       MVT PermCntlTy, PermTy, LDTy;
14310       if (Subtarget.hasAltivec()) {
14311         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14312                                  Intrinsic::ppc_altivec_lvsl;
14313         IntrLD = Intrinsic::ppc_altivec_lvx;
14314         IntrPerm = Intrinsic::ppc_altivec_vperm;
14315         PermCntlTy = MVT::v16i8;
14316         PermTy = MVT::v4i32;
14317         LDTy = MVT::v4i32;
14318       } else {
14319         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14320                                        Intrinsic::ppc_qpx_qvlpcls;
14321         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14322                                        Intrinsic::ppc_qpx_qvlfs;
14323         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14324         PermCntlTy = MVT::v4f64;
14325         PermTy = MVT::v4f64;
14326         LDTy = MemVT.getSimpleVT();
14327       }
14328 
14329       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14330 
14331       // Create the new MMO for the new base load. It is like the original MMO,
14332       // but represents an area in memory almost twice the vector size centered
14333       // on the original address. If the address is unaligned, we might start
14334       // reading up to (sizeof(vector)-1) bytes below the address of the
14335       // original unaligned load.
14336       MachineFunction &MF = DAG.getMachineFunction();
14337       MachineMemOperand *BaseMMO =
14338         MF.getMachineMemOperand(LD->getMemOperand(),
14339                                 -(long)MemVT.getStoreSize()+1,
14340                                 2*MemVT.getStoreSize()-1);
14341 
14342       // Create the new base load.
14343       SDValue LDXIntID =
14344           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14345       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14346       SDValue BaseLoad =
14347         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14348                                 DAG.getVTList(PermTy, MVT::Other),
14349                                 BaseLoadOps, LDTy, BaseMMO);
14350 
14351       // Note that the value of IncOffset (which is provided to the next
14352       // load's pointer info offset value, and thus used to calculate the
14353       // alignment), and the value of IncValue (which is actually used to
14354       // increment the pointer value) are different! This is because we
14355       // require the next load to appear to be aligned, even though it
14356       // is actually offset from the base pointer by a lesser amount.
14357       int IncOffset = VT.getSizeInBits() / 8;
14358       int IncValue = IncOffset;
14359 
14360       // Walk (both up and down) the chain looking for another load at the real
14361       // (aligned) offset (the alignment of the other load does not matter in
14362       // this case). If found, then do not use the offset reduction trick, as
14363       // that will prevent the loads from being later combined (as they would
14364       // otherwise be duplicates).
14365       if (!findConsecutiveLoad(LD, DAG))
14366         --IncValue;
14367 
14368       SDValue Increment =
14369           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14370       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14371 
14372       MachineMemOperand *ExtraMMO =
14373         MF.getMachineMemOperand(LD->getMemOperand(),
14374                                 1, 2*MemVT.getStoreSize()-1);
14375       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14376       SDValue ExtraLoad =
14377         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14378                                 DAG.getVTList(PermTy, MVT::Other),
14379                                 ExtraLoadOps, LDTy, ExtraMMO);
14380 
14381       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14382         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14383 
14384       // Because vperm has a big-endian bias, we must reverse the order
14385       // of the input vectors and complement the permute control vector
14386       // when generating little endian code.  We have already handled the
14387       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14388       // and ExtraLoad here.
14389       SDValue Perm;
14390       if (isLittleEndian)
14391         Perm = BuildIntrinsicOp(IntrPerm,
14392                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14393       else
14394         Perm = BuildIntrinsicOp(IntrPerm,
14395                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14396 
14397       if (VT != PermTy)
14398         Perm = Subtarget.hasAltivec() ?
14399                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14400                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14401                                DAG.getTargetConstant(1, dl, MVT::i64));
14402                                // second argument is 1 because this rounding
14403                                // is always exact.
14404 
14405       // The output of the permutation is our loaded result, the TokenFactor is
14406       // our new chain.
14407       DCI.CombineTo(N, Perm, TF);
14408       return SDValue(N, 0);
14409     }
14410     }
14411     break;
14412     case ISD::INTRINSIC_WO_CHAIN: {
14413       bool isLittleEndian = Subtarget.isLittleEndian();
14414       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14415       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14416                                            : Intrinsic::ppc_altivec_lvsl);
14417       if ((IID == Intr ||
14418            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14419            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14420         N->getOperand(1)->getOpcode() == ISD::ADD) {
14421         SDValue Add = N->getOperand(1);
14422 
14423         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14424                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14425 
14426         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14427                                   APInt::getAllOnesValue(Bits /* alignment */)
14428                                       .zext(Add.getScalarValueSizeInBits()))) {
14429           SDNode *BasePtr = Add->getOperand(0).getNode();
14430           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14431                                     UE = BasePtr->use_end();
14432                UI != UE; ++UI) {
14433             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14434                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14435               // We've found another LVSL/LVSR, and this address is an aligned
14436               // multiple of that one. The results will be the same, so use the
14437               // one we've just found instead.
14438 
14439               return SDValue(*UI, 0);
14440             }
14441           }
14442         }
14443 
14444         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14445           SDNode *BasePtr = Add->getOperand(0).getNode();
14446           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14447                UE = BasePtr->use_end(); UI != UE; ++UI) {
14448             if (UI->getOpcode() == ISD::ADD &&
14449                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14450                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14451                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14452                 (1ULL << Bits) == 0) {
14453               SDNode *OtherAdd = *UI;
14454               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14455                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14456                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14457                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14458                   return SDValue(*VI, 0);
14459                 }
14460               }
14461             }
14462           }
14463         }
14464       }
14465 
14466       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14467       // Expose the vabsduw/h/b opportunity for down stream
14468       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14469           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14470            IID == Intrinsic::ppc_altivec_vmaxsh ||
14471            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14472         SDValue V1 = N->getOperand(1);
14473         SDValue V2 = N->getOperand(2);
14474         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14475              V1.getSimpleValueType() == MVT::v8i16 ||
14476              V1.getSimpleValueType() == MVT::v16i8) &&
14477             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14478           // (0-a, a)
14479           if (V1.getOpcode() == ISD::SUB &&
14480               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14481               V1.getOperand(1) == V2) {
14482             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14483           }
14484           // (a, 0-a)
14485           if (V2.getOpcode() == ISD::SUB &&
14486               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14487               V2.getOperand(1) == V1) {
14488             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14489           }
14490           // (x-y, y-x)
14491           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14492               V1.getOperand(0) == V2.getOperand(1) &&
14493               V1.getOperand(1) == V2.getOperand(0)) {
14494             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14495           }
14496         }
14497       }
14498     }
14499 
14500     break;
14501   case ISD::INTRINSIC_W_CHAIN:
14502     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14503     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14504     if (Subtarget.needsSwapsForVSXMemOps()) {
14505       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14506       default:
14507         break;
14508       case Intrinsic::ppc_vsx_lxvw4x:
14509       case Intrinsic::ppc_vsx_lxvd2x:
14510         return expandVSXLoadForLE(N, DCI);
14511       }
14512     }
14513     break;
14514   case ISD::INTRINSIC_VOID:
14515     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14516     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14517     if (Subtarget.needsSwapsForVSXMemOps()) {
14518       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14519       default:
14520         break;
14521       case Intrinsic::ppc_vsx_stxvw4x:
14522       case Intrinsic::ppc_vsx_stxvd2x:
14523         return expandVSXStoreForLE(N, DCI);
14524       }
14525     }
14526     break;
14527   case ISD::BSWAP:
14528     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14529     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14530         N->getOperand(0).hasOneUse() &&
14531         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14532          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14533           N->getValueType(0) == MVT::i64))) {
14534       SDValue Load = N->getOperand(0);
14535       LoadSDNode *LD = cast<LoadSDNode>(Load);
14536       // Create the byte-swapping load.
14537       SDValue Ops[] = {
14538         LD->getChain(),    // Chain
14539         LD->getBasePtr(),  // Ptr
14540         DAG.getValueType(N->getValueType(0)) // VT
14541       };
14542       SDValue BSLoad =
14543         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14544                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14545                                               MVT::i64 : MVT::i32, MVT::Other),
14546                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14547 
14548       // If this is an i16 load, insert the truncate.
14549       SDValue ResVal = BSLoad;
14550       if (N->getValueType(0) == MVT::i16)
14551         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14552 
14553       // First, combine the bswap away.  This makes the value produced by the
14554       // load dead.
14555       DCI.CombineTo(N, ResVal);
14556 
14557       // Next, combine the load away, we give it a bogus result value but a real
14558       // chain result.  The result value is dead because the bswap is dead.
14559       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14560 
14561       // Return N so it doesn't get rechecked!
14562       return SDValue(N, 0);
14563     }
14564     break;
14565   case PPCISD::VCMP:
14566     // If a VCMPo node already exists with exactly the same operands as this
14567     // node, use its result instead of this node (VCMPo computes both a CR6 and
14568     // a normal output).
14569     //
14570     if (!N->getOperand(0).hasOneUse() &&
14571         !N->getOperand(1).hasOneUse() &&
14572         !N->getOperand(2).hasOneUse()) {
14573 
14574       // Scan all of the users of the LHS, looking for VCMPo's that match.
14575       SDNode *VCMPoNode = nullptr;
14576 
14577       SDNode *LHSN = N->getOperand(0).getNode();
14578       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14579            UI != E; ++UI)
14580         if (UI->getOpcode() == PPCISD::VCMPo &&
14581             UI->getOperand(1) == N->getOperand(1) &&
14582             UI->getOperand(2) == N->getOperand(2) &&
14583             UI->getOperand(0) == N->getOperand(0)) {
14584           VCMPoNode = *UI;
14585           break;
14586         }
14587 
14588       // If there is no VCMPo node, or if the flag value has a single use, don't
14589       // transform this.
14590       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14591         break;
14592 
14593       // Look at the (necessarily single) use of the flag value.  If it has a
14594       // chain, this transformation is more complex.  Note that multiple things
14595       // could use the value result, which we should ignore.
14596       SDNode *FlagUser = nullptr;
14597       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14598            FlagUser == nullptr; ++UI) {
14599         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14600         SDNode *User = *UI;
14601         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14602           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14603             FlagUser = User;
14604             break;
14605           }
14606         }
14607       }
14608 
14609       // If the user is a MFOCRF instruction, we know this is safe.
14610       // Otherwise we give up for right now.
14611       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14612         return SDValue(VCMPoNode, 0);
14613     }
14614     break;
14615   case ISD::BRCOND: {
14616     SDValue Cond = N->getOperand(1);
14617     SDValue Target = N->getOperand(2);
14618 
14619     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14620         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14621           Intrinsic::loop_decrement) {
14622 
14623       // We now need to make the intrinsic dead (it cannot be instruction
14624       // selected).
14625       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14626       assert(Cond.getNode()->hasOneUse() &&
14627              "Counter decrement has more than one use");
14628 
14629       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14630                          N->getOperand(0), Target);
14631     }
14632   }
14633   break;
14634   case ISD::BR_CC: {
14635     // If this is a branch on an altivec predicate comparison, lower this so
14636     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14637     // lowering is done pre-legalize, because the legalizer lowers the predicate
14638     // compare down to code that is difficult to reassemble.
14639     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14640     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14641 
14642     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14643     // value. If so, pass-through the AND to get to the intrinsic.
14644     if (LHS.getOpcode() == ISD::AND &&
14645         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14646         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14647           Intrinsic::loop_decrement &&
14648         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14649         !isNullConstant(LHS.getOperand(1)))
14650       LHS = LHS.getOperand(0);
14651 
14652     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14653         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14654           Intrinsic::loop_decrement &&
14655         isa<ConstantSDNode>(RHS)) {
14656       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14657              "Counter decrement comparison is not EQ or NE");
14658 
14659       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14660       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14661                     (CC == ISD::SETNE && !Val);
14662 
14663       // We now need to make the intrinsic dead (it cannot be instruction
14664       // selected).
14665       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14666       assert(LHS.getNode()->hasOneUse() &&
14667              "Counter decrement has more than one use");
14668 
14669       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14670                          N->getOperand(0), N->getOperand(4));
14671     }
14672 
14673     int CompareOpc;
14674     bool isDot;
14675 
14676     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14677         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14678         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14679       assert(isDot && "Can't compare against a vector result!");
14680 
14681       // If this is a comparison against something other than 0/1, then we know
14682       // that the condition is never/always true.
14683       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14684       if (Val != 0 && Val != 1) {
14685         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14686           return N->getOperand(0);
14687         // Always !=, turn it into an unconditional branch.
14688         return DAG.getNode(ISD::BR, dl, MVT::Other,
14689                            N->getOperand(0), N->getOperand(4));
14690       }
14691 
14692       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14693 
14694       // Create the PPCISD altivec 'dot' comparison node.
14695       SDValue Ops[] = {
14696         LHS.getOperand(2),  // LHS of compare
14697         LHS.getOperand(3),  // RHS of compare
14698         DAG.getConstant(CompareOpc, dl, MVT::i32)
14699       };
14700       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14701       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14702 
14703       // Unpack the result based on how the target uses it.
14704       PPC::Predicate CompOpc;
14705       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14706       default:  // Can't happen, don't crash on invalid number though.
14707       case 0:   // Branch on the value of the EQ bit of CR6.
14708         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14709         break;
14710       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14711         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14712         break;
14713       case 2:   // Branch on the value of the LT bit of CR6.
14714         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14715         break;
14716       case 3:   // Branch on the inverted value of the LT bit of CR6.
14717         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14718         break;
14719       }
14720 
14721       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14722                          DAG.getConstant(CompOpc, dl, MVT::i32),
14723                          DAG.getRegister(PPC::CR6, MVT::i32),
14724                          N->getOperand(4), CompNode.getValue(1));
14725     }
14726     break;
14727   }
14728   case ISD::BUILD_VECTOR:
14729     return DAGCombineBuildVector(N, DCI);
14730   case ISD::ABS:
14731     return combineABS(N, DCI);
14732   case ISD::VSELECT:
14733     return combineVSelect(N, DCI);
14734   }
14735 
14736   return SDValue();
14737 }
14738 
14739 SDValue
14740 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14741                                  SelectionDAG &DAG,
14742                                  SmallVectorImpl<SDNode *> &Created) const {
14743   // fold (sdiv X, pow2)
14744   EVT VT = N->getValueType(0);
14745   if (VT == MVT::i64 && !Subtarget.isPPC64())
14746     return SDValue();
14747   if ((VT != MVT::i32 && VT != MVT::i64) ||
14748       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14749     return SDValue();
14750 
14751   SDLoc DL(N);
14752   SDValue N0 = N->getOperand(0);
14753 
14754   bool IsNegPow2 = (-Divisor).isPowerOf2();
14755   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14756   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14757 
14758   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14759   Created.push_back(Op.getNode());
14760 
14761   if (IsNegPow2) {
14762     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14763     Created.push_back(Op.getNode());
14764   }
14765 
14766   return Op;
14767 }
14768 
14769 //===----------------------------------------------------------------------===//
14770 // Inline Assembly Support
14771 //===----------------------------------------------------------------------===//
14772 
14773 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14774                                                       KnownBits &Known,
14775                                                       const APInt &DemandedElts,
14776                                                       const SelectionDAG &DAG,
14777                                                       unsigned Depth) const {
14778   Known.resetAll();
14779   switch (Op.getOpcode()) {
14780   default: break;
14781   case PPCISD::LBRX: {
14782     // lhbrx is known to have the top bits cleared out.
14783     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14784       Known.Zero = 0xFFFF0000;
14785     break;
14786   }
14787   case ISD::INTRINSIC_WO_CHAIN: {
14788     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14789     default: break;
14790     case Intrinsic::ppc_altivec_vcmpbfp_p:
14791     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14792     case Intrinsic::ppc_altivec_vcmpequb_p:
14793     case Intrinsic::ppc_altivec_vcmpequh_p:
14794     case Intrinsic::ppc_altivec_vcmpequw_p:
14795     case Intrinsic::ppc_altivec_vcmpequd_p:
14796     case Intrinsic::ppc_altivec_vcmpgefp_p:
14797     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14798     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14799     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14800     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14801     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14802     case Intrinsic::ppc_altivec_vcmpgtub_p:
14803     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14804     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14805     case Intrinsic::ppc_altivec_vcmpgtud_p:
14806       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14807       break;
14808     }
14809   }
14810   }
14811 }
14812 
14813 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14814   switch (Subtarget.getCPUDirective()) {
14815   default: break;
14816   case PPC::DIR_970:
14817   case PPC::DIR_PWR4:
14818   case PPC::DIR_PWR5:
14819   case PPC::DIR_PWR5X:
14820   case PPC::DIR_PWR6:
14821   case PPC::DIR_PWR6X:
14822   case PPC::DIR_PWR7:
14823   case PPC::DIR_PWR8:
14824   case PPC::DIR_PWR9:
14825   case PPC::DIR_PWR_FUTURE: {
14826     if (!ML)
14827       break;
14828 
14829     if (!DisableInnermostLoopAlign32) {
14830       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14831       // so that we can decrease cache misses and branch-prediction misses.
14832       // Actual alignment of the loop will depend on the hotness check and other
14833       // logic in alignBlocks.
14834       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14835         return Align(32);
14836     }
14837 
14838     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14839 
14840     // For small loops (between 5 and 8 instructions), align to a 32-byte
14841     // boundary so that the entire loop fits in one instruction-cache line.
14842     uint64_t LoopSize = 0;
14843     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14844       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14845         LoopSize += TII->getInstSizeInBytes(*J);
14846         if (LoopSize > 32)
14847           break;
14848       }
14849 
14850     if (LoopSize > 16 && LoopSize <= 32)
14851       return Align(32);
14852 
14853     break;
14854   }
14855   }
14856 
14857   return TargetLowering::getPrefLoopAlignment(ML);
14858 }
14859 
14860 /// getConstraintType - Given a constraint, return the type of
14861 /// constraint it is for this target.
14862 PPCTargetLowering::ConstraintType
14863 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14864   if (Constraint.size() == 1) {
14865     switch (Constraint[0]) {
14866     default: break;
14867     case 'b':
14868     case 'r':
14869     case 'f':
14870     case 'd':
14871     case 'v':
14872     case 'y':
14873       return C_RegisterClass;
14874     case 'Z':
14875       // FIXME: While Z does indicate a memory constraint, it specifically
14876       // indicates an r+r address (used in conjunction with the 'y' modifier
14877       // in the replacement string). Currently, we're forcing the base
14878       // register to be r0 in the asm printer (which is interpreted as zero)
14879       // and forming the complete address in the second register. This is
14880       // suboptimal.
14881       return C_Memory;
14882     }
14883   } else if (Constraint == "wc") { // individual CR bits.
14884     return C_RegisterClass;
14885   } else if (Constraint == "wa" || Constraint == "wd" ||
14886              Constraint == "wf" || Constraint == "ws" ||
14887              Constraint == "wi" || Constraint == "ww") {
14888     return C_RegisterClass; // VSX registers.
14889   }
14890   return TargetLowering::getConstraintType(Constraint);
14891 }
14892 
14893 /// Examine constraint type and operand type and determine a weight value.
14894 /// This object must already have been set up with the operand type
14895 /// and the current alternative constraint selected.
14896 TargetLowering::ConstraintWeight
14897 PPCTargetLowering::getSingleConstraintMatchWeight(
14898     AsmOperandInfo &info, const char *constraint) const {
14899   ConstraintWeight weight = CW_Invalid;
14900   Value *CallOperandVal = info.CallOperandVal;
14901     // If we don't have a value, we can't do a match,
14902     // but allow it at the lowest weight.
14903   if (!CallOperandVal)
14904     return CW_Default;
14905   Type *type = CallOperandVal->getType();
14906 
14907   // Look at the constraint type.
14908   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14909     return CW_Register; // an individual CR bit.
14910   else if ((StringRef(constraint) == "wa" ||
14911             StringRef(constraint) == "wd" ||
14912             StringRef(constraint) == "wf") &&
14913            type->isVectorTy())
14914     return CW_Register;
14915   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14916     return CW_Register; // just hold 64-bit integers data.
14917   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14918     return CW_Register;
14919   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14920     return CW_Register;
14921 
14922   switch (*constraint) {
14923   default:
14924     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14925     break;
14926   case 'b':
14927     if (type->isIntegerTy())
14928       weight = CW_Register;
14929     break;
14930   case 'f':
14931     if (type->isFloatTy())
14932       weight = CW_Register;
14933     break;
14934   case 'd':
14935     if (type->isDoubleTy())
14936       weight = CW_Register;
14937     break;
14938   case 'v':
14939     if (type->isVectorTy())
14940       weight = CW_Register;
14941     break;
14942   case 'y':
14943     weight = CW_Register;
14944     break;
14945   case 'Z':
14946     weight = CW_Memory;
14947     break;
14948   }
14949   return weight;
14950 }
14951 
14952 std::pair<unsigned, const TargetRegisterClass *>
14953 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14954                                                 StringRef Constraint,
14955                                                 MVT VT) const {
14956   if (Constraint.size() == 1) {
14957     // GCC RS6000 Constraint Letters
14958     switch (Constraint[0]) {
14959     case 'b':   // R1-R31
14960       if (VT == MVT::i64 && Subtarget.isPPC64())
14961         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14962       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14963     case 'r':   // R0-R31
14964       if (VT == MVT::i64 && Subtarget.isPPC64())
14965         return std::make_pair(0U, &PPC::G8RCRegClass);
14966       return std::make_pair(0U, &PPC::GPRCRegClass);
14967     // 'd' and 'f' constraints are both defined to be "the floating point
14968     // registers", where one is for 32-bit and the other for 64-bit. We don't
14969     // really care overly much here so just give them all the same reg classes.
14970     case 'd':
14971     case 'f':
14972       if (Subtarget.hasSPE()) {
14973         if (VT == MVT::f32 || VT == MVT::i32)
14974           return std::make_pair(0U, &PPC::GPRCRegClass);
14975         if (VT == MVT::f64 || VT == MVT::i64)
14976           return std::make_pair(0U, &PPC::SPERCRegClass);
14977       } else {
14978         if (VT == MVT::f32 || VT == MVT::i32)
14979           return std::make_pair(0U, &PPC::F4RCRegClass);
14980         if (VT == MVT::f64 || VT == MVT::i64)
14981           return std::make_pair(0U, &PPC::F8RCRegClass);
14982         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14983           return std::make_pair(0U, &PPC::QFRCRegClass);
14984         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14985           return std::make_pair(0U, &PPC::QSRCRegClass);
14986       }
14987       break;
14988     case 'v':
14989       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14990         return std::make_pair(0U, &PPC::QFRCRegClass);
14991       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14992         return std::make_pair(0U, &PPC::QSRCRegClass);
14993       if (Subtarget.hasAltivec())
14994         return std::make_pair(0U, &PPC::VRRCRegClass);
14995       break;
14996     case 'y':   // crrc
14997       return std::make_pair(0U, &PPC::CRRCRegClass);
14998     }
14999   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15000     // An individual CR bit.
15001     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15002   } else if ((Constraint == "wa" || Constraint == "wd" ||
15003              Constraint == "wf" || Constraint == "wi") &&
15004              Subtarget.hasVSX()) {
15005     return std::make_pair(0U, &PPC::VSRCRegClass);
15006   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15007     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15008       return std::make_pair(0U, &PPC::VSSRCRegClass);
15009     else
15010       return std::make_pair(0U, &PPC::VSFRCRegClass);
15011   }
15012 
15013   // If we name a VSX register, we can't defer to the base class because it
15014   // will not recognize the correct register (their names will be VSL{0-31}
15015   // and V{0-31} so they won't match). So we match them here.
15016   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15017     int VSNum = atoi(Constraint.data() + 3);
15018     assert(VSNum >= 0 && VSNum <= 63 &&
15019            "Attempted to access a vsr out of range");
15020     if (VSNum < 32)
15021       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15022     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15023   }
15024   std::pair<unsigned, const TargetRegisterClass *> R =
15025       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15026 
15027   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15028   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15029   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15030   // register.
15031   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15032   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15033   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15034       PPC::GPRCRegClass.contains(R.first))
15035     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15036                             PPC::sub_32, &PPC::G8RCRegClass),
15037                           &PPC::G8RCRegClass);
15038 
15039   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15040   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15041     R.first = PPC::CR0;
15042     R.second = &PPC::CRRCRegClass;
15043   }
15044 
15045   return R;
15046 }
15047 
15048 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15049 /// vector.  If it is invalid, don't add anything to Ops.
15050 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15051                                                      std::string &Constraint,
15052                                                      std::vector<SDValue>&Ops,
15053                                                      SelectionDAG &DAG) const {
15054   SDValue Result;
15055 
15056   // Only support length 1 constraints.
15057   if (Constraint.length() > 1) return;
15058 
15059   char Letter = Constraint[0];
15060   switch (Letter) {
15061   default: break;
15062   case 'I':
15063   case 'J':
15064   case 'K':
15065   case 'L':
15066   case 'M':
15067   case 'N':
15068   case 'O':
15069   case 'P': {
15070     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15071     if (!CST) return; // Must be an immediate to match.
15072     SDLoc dl(Op);
15073     int64_t Value = CST->getSExtValue();
15074     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15075                          // numbers are printed as such.
15076     switch (Letter) {
15077     default: llvm_unreachable("Unknown constraint letter!");
15078     case 'I':  // "I" is a signed 16-bit constant.
15079       if (isInt<16>(Value))
15080         Result = DAG.getTargetConstant(Value, dl, TCVT);
15081       break;
15082     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15083       if (isShiftedUInt<16, 16>(Value))
15084         Result = DAG.getTargetConstant(Value, dl, TCVT);
15085       break;
15086     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15087       if (isShiftedInt<16, 16>(Value))
15088         Result = DAG.getTargetConstant(Value, dl, TCVT);
15089       break;
15090     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15091       if (isUInt<16>(Value))
15092         Result = DAG.getTargetConstant(Value, dl, TCVT);
15093       break;
15094     case 'M':  // "M" is a constant that is greater than 31.
15095       if (Value > 31)
15096         Result = DAG.getTargetConstant(Value, dl, TCVT);
15097       break;
15098     case 'N':  // "N" is a positive constant that is an exact power of two.
15099       if (Value > 0 && isPowerOf2_64(Value))
15100         Result = DAG.getTargetConstant(Value, dl, TCVT);
15101       break;
15102     case 'O':  // "O" is the constant zero.
15103       if (Value == 0)
15104         Result = DAG.getTargetConstant(Value, dl, TCVT);
15105       break;
15106     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15107       if (isInt<16>(-Value))
15108         Result = DAG.getTargetConstant(Value, dl, TCVT);
15109       break;
15110     }
15111     break;
15112   }
15113   }
15114 
15115   if (Result.getNode()) {
15116     Ops.push_back(Result);
15117     return;
15118   }
15119 
15120   // Handle standard constraint letters.
15121   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15122 }
15123 
15124 // isLegalAddressingMode - Return true if the addressing mode represented
15125 // by AM is legal for this target, for a load/store of the specified type.
15126 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15127                                               const AddrMode &AM, Type *Ty,
15128                                               unsigned AS, Instruction *I) const {
15129   // PPC does not allow r+i addressing modes for vectors!
15130   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15131     return false;
15132 
15133   // PPC allows a sign-extended 16-bit immediate field.
15134   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15135     return false;
15136 
15137   // No global is ever allowed as a base.
15138   if (AM.BaseGV)
15139     return false;
15140 
15141   // PPC only support r+r,
15142   switch (AM.Scale) {
15143   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15144     break;
15145   case 1:
15146     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15147       return false;
15148     // Otherwise we have r+r or r+i.
15149     break;
15150   case 2:
15151     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15152       return false;
15153     // Allow 2*r as r+r.
15154     break;
15155   default:
15156     // No other scales are supported.
15157     return false;
15158   }
15159 
15160   return true;
15161 }
15162 
15163 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15164                                            SelectionDAG &DAG) const {
15165   MachineFunction &MF = DAG.getMachineFunction();
15166   MachineFrameInfo &MFI = MF.getFrameInfo();
15167   MFI.setReturnAddressIsTaken(true);
15168 
15169   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15170     return SDValue();
15171 
15172   SDLoc dl(Op);
15173   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15174 
15175   // Make sure the function does not optimize away the store of the RA to
15176   // the stack.
15177   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15178   FuncInfo->setLRStoreRequired();
15179   bool isPPC64 = Subtarget.isPPC64();
15180   auto PtrVT = getPointerTy(MF.getDataLayout());
15181 
15182   if (Depth > 0) {
15183     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15184     SDValue Offset =
15185         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15186                         isPPC64 ? MVT::i64 : MVT::i32);
15187     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15188                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15189                        MachinePointerInfo());
15190   }
15191 
15192   // Just load the return address off the stack.
15193   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15194   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15195                      MachinePointerInfo());
15196 }
15197 
15198 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15199                                           SelectionDAG &DAG) const {
15200   SDLoc dl(Op);
15201   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15202 
15203   MachineFunction &MF = DAG.getMachineFunction();
15204   MachineFrameInfo &MFI = MF.getFrameInfo();
15205   MFI.setFrameAddressIsTaken(true);
15206 
15207   EVT PtrVT = getPointerTy(MF.getDataLayout());
15208   bool isPPC64 = PtrVT == MVT::i64;
15209 
15210   // Naked functions never have a frame pointer, and so we use r1. For all
15211   // other functions, this decision must be delayed until during PEI.
15212   unsigned FrameReg;
15213   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15214     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15215   else
15216     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15217 
15218   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15219                                          PtrVT);
15220   while (Depth--)
15221     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15222                             FrameAddr, MachinePointerInfo());
15223   return FrameAddr;
15224 }
15225 
15226 // FIXME? Maybe this could be a TableGen attribute on some registers and
15227 // this table could be generated automatically from RegInfo.
15228 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15229                                               const MachineFunction &MF) const {
15230   bool isPPC64 = Subtarget.isPPC64();
15231 
15232   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15233   if (!is64Bit && VT != LLT::scalar(32))
15234     report_fatal_error("Invalid register global variable type");
15235 
15236   Register Reg = StringSwitch<Register>(RegName)
15237                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15238                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15239                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15240                      .Default(Register());
15241 
15242   if (Reg)
15243     return Reg;
15244   report_fatal_error("Invalid register name global variable");
15245 }
15246 
15247 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15248   // 32-bit SVR4 ABI access everything as got-indirect.
15249   if (Subtarget.is32BitELFABI())
15250     return true;
15251 
15252   // AIX accesses everything indirectly through the TOC, which is similar to
15253   // the GOT.
15254   if (Subtarget.isAIXABI())
15255     return true;
15256 
15257   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15258   // If it is small or large code model, module locals are accessed
15259   // indirectly by loading their address from .toc/.got.
15260   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15261     return true;
15262 
15263   // JumpTable and BlockAddress are accessed as got-indirect.
15264   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15265     return true;
15266 
15267   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15268     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15269 
15270   return false;
15271 }
15272 
15273 bool
15274 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15275   // The PowerPC target isn't yet aware of offsets.
15276   return false;
15277 }
15278 
15279 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15280                                            const CallInst &I,
15281                                            MachineFunction &MF,
15282                                            unsigned Intrinsic) const {
15283   switch (Intrinsic) {
15284   case Intrinsic::ppc_qpx_qvlfd:
15285   case Intrinsic::ppc_qpx_qvlfs:
15286   case Intrinsic::ppc_qpx_qvlfcd:
15287   case Intrinsic::ppc_qpx_qvlfcs:
15288   case Intrinsic::ppc_qpx_qvlfiwa:
15289   case Intrinsic::ppc_qpx_qvlfiwz:
15290   case Intrinsic::ppc_altivec_lvx:
15291   case Intrinsic::ppc_altivec_lvxl:
15292   case Intrinsic::ppc_altivec_lvebx:
15293   case Intrinsic::ppc_altivec_lvehx:
15294   case Intrinsic::ppc_altivec_lvewx:
15295   case Intrinsic::ppc_vsx_lxvd2x:
15296   case Intrinsic::ppc_vsx_lxvw4x: {
15297     EVT VT;
15298     switch (Intrinsic) {
15299     case Intrinsic::ppc_altivec_lvebx:
15300       VT = MVT::i8;
15301       break;
15302     case Intrinsic::ppc_altivec_lvehx:
15303       VT = MVT::i16;
15304       break;
15305     case Intrinsic::ppc_altivec_lvewx:
15306       VT = MVT::i32;
15307       break;
15308     case Intrinsic::ppc_vsx_lxvd2x:
15309       VT = MVT::v2f64;
15310       break;
15311     case Intrinsic::ppc_qpx_qvlfd:
15312       VT = MVT::v4f64;
15313       break;
15314     case Intrinsic::ppc_qpx_qvlfs:
15315       VT = MVT::v4f32;
15316       break;
15317     case Intrinsic::ppc_qpx_qvlfcd:
15318       VT = MVT::v2f64;
15319       break;
15320     case Intrinsic::ppc_qpx_qvlfcs:
15321       VT = MVT::v2f32;
15322       break;
15323     default:
15324       VT = MVT::v4i32;
15325       break;
15326     }
15327 
15328     Info.opc = ISD::INTRINSIC_W_CHAIN;
15329     Info.memVT = VT;
15330     Info.ptrVal = I.getArgOperand(0);
15331     Info.offset = -VT.getStoreSize()+1;
15332     Info.size = 2*VT.getStoreSize()-1;
15333     Info.align = Align(1);
15334     Info.flags = MachineMemOperand::MOLoad;
15335     return true;
15336   }
15337   case Intrinsic::ppc_qpx_qvlfda:
15338   case Intrinsic::ppc_qpx_qvlfsa:
15339   case Intrinsic::ppc_qpx_qvlfcda:
15340   case Intrinsic::ppc_qpx_qvlfcsa:
15341   case Intrinsic::ppc_qpx_qvlfiwaa:
15342   case Intrinsic::ppc_qpx_qvlfiwza: {
15343     EVT VT;
15344     switch (Intrinsic) {
15345     case Intrinsic::ppc_qpx_qvlfda:
15346       VT = MVT::v4f64;
15347       break;
15348     case Intrinsic::ppc_qpx_qvlfsa:
15349       VT = MVT::v4f32;
15350       break;
15351     case Intrinsic::ppc_qpx_qvlfcda:
15352       VT = MVT::v2f64;
15353       break;
15354     case Intrinsic::ppc_qpx_qvlfcsa:
15355       VT = MVT::v2f32;
15356       break;
15357     default:
15358       VT = MVT::v4i32;
15359       break;
15360     }
15361 
15362     Info.opc = ISD::INTRINSIC_W_CHAIN;
15363     Info.memVT = VT;
15364     Info.ptrVal = I.getArgOperand(0);
15365     Info.offset = 0;
15366     Info.size = VT.getStoreSize();
15367     Info.align = Align(1);
15368     Info.flags = MachineMemOperand::MOLoad;
15369     return true;
15370   }
15371   case Intrinsic::ppc_qpx_qvstfd:
15372   case Intrinsic::ppc_qpx_qvstfs:
15373   case Intrinsic::ppc_qpx_qvstfcd:
15374   case Intrinsic::ppc_qpx_qvstfcs:
15375   case Intrinsic::ppc_qpx_qvstfiw:
15376   case Intrinsic::ppc_altivec_stvx:
15377   case Intrinsic::ppc_altivec_stvxl:
15378   case Intrinsic::ppc_altivec_stvebx:
15379   case Intrinsic::ppc_altivec_stvehx:
15380   case Intrinsic::ppc_altivec_stvewx:
15381   case Intrinsic::ppc_vsx_stxvd2x:
15382   case Intrinsic::ppc_vsx_stxvw4x: {
15383     EVT VT;
15384     switch (Intrinsic) {
15385     case Intrinsic::ppc_altivec_stvebx:
15386       VT = MVT::i8;
15387       break;
15388     case Intrinsic::ppc_altivec_stvehx:
15389       VT = MVT::i16;
15390       break;
15391     case Intrinsic::ppc_altivec_stvewx:
15392       VT = MVT::i32;
15393       break;
15394     case Intrinsic::ppc_vsx_stxvd2x:
15395       VT = MVT::v2f64;
15396       break;
15397     case Intrinsic::ppc_qpx_qvstfd:
15398       VT = MVT::v4f64;
15399       break;
15400     case Intrinsic::ppc_qpx_qvstfs:
15401       VT = MVT::v4f32;
15402       break;
15403     case Intrinsic::ppc_qpx_qvstfcd:
15404       VT = MVT::v2f64;
15405       break;
15406     case Intrinsic::ppc_qpx_qvstfcs:
15407       VT = MVT::v2f32;
15408       break;
15409     default:
15410       VT = MVT::v4i32;
15411       break;
15412     }
15413 
15414     Info.opc = ISD::INTRINSIC_VOID;
15415     Info.memVT = VT;
15416     Info.ptrVal = I.getArgOperand(1);
15417     Info.offset = -VT.getStoreSize()+1;
15418     Info.size = 2*VT.getStoreSize()-1;
15419     Info.align = Align(1);
15420     Info.flags = MachineMemOperand::MOStore;
15421     return true;
15422   }
15423   case Intrinsic::ppc_qpx_qvstfda:
15424   case Intrinsic::ppc_qpx_qvstfsa:
15425   case Intrinsic::ppc_qpx_qvstfcda:
15426   case Intrinsic::ppc_qpx_qvstfcsa:
15427   case Intrinsic::ppc_qpx_qvstfiwa: {
15428     EVT VT;
15429     switch (Intrinsic) {
15430     case Intrinsic::ppc_qpx_qvstfda:
15431       VT = MVT::v4f64;
15432       break;
15433     case Intrinsic::ppc_qpx_qvstfsa:
15434       VT = MVT::v4f32;
15435       break;
15436     case Intrinsic::ppc_qpx_qvstfcda:
15437       VT = MVT::v2f64;
15438       break;
15439     case Intrinsic::ppc_qpx_qvstfcsa:
15440       VT = MVT::v2f32;
15441       break;
15442     default:
15443       VT = MVT::v4i32;
15444       break;
15445     }
15446 
15447     Info.opc = ISD::INTRINSIC_VOID;
15448     Info.memVT = VT;
15449     Info.ptrVal = I.getArgOperand(1);
15450     Info.offset = 0;
15451     Info.size = VT.getStoreSize();
15452     Info.align = Align(1);
15453     Info.flags = MachineMemOperand::MOStore;
15454     return true;
15455   }
15456   default:
15457     break;
15458   }
15459 
15460   return false;
15461 }
15462 
15463 /// It returns EVT::Other if the type should be determined using generic
15464 /// target-independent logic.
15465 EVT PPCTargetLowering::getOptimalMemOpType(
15466     const MemOp &Op, const AttributeList &FuncAttributes) const {
15467   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15468     // When expanding a memset, require at least two QPX instructions to cover
15469     // the cost of loading the value to be stored from the constant pool.
15470     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15471         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15472         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15473       return MVT::v4f64;
15474     }
15475 
15476     // We should use Altivec/VSX loads and stores when available. For unaligned
15477     // addresses, unaligned VSX loads are only fast starting with the P8.
15478     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15479         (Op.isAligned(Align(16)) ||
15480          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15481       return MVT::v4i32;
15482   }
15483 
15484   if (Subtarget.isPPC64()) {
15485     return MVT::i64;
15486   }
15487 
15488   return MVT::i32;
15489 }
15490 
15491 /// Returns true if it is beneficial to convert a load of a constant
15492 /// to just the constant itself.
15493 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15494                                                           Type *Ty) const {
15495   assert(Ty->isIntegerTy());
15496 
15497   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15498   return !(BitSize == 0 || BitSize > 64);
15499 }
15500 
15501 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15502   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15503     return false;
15504   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15505   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15506   return NumBits1 == 64 && NumBits2 == 32;
15507 }
15508 
15509 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15510   if (!VT1.isInteger() || !VT2.isInteger())
15511     return false;
15512   unsigned NumBits1 = VT1.getSizeInBits();
15513   unsigned NumBits2 = VT2.getSizeInBits();
15514   return NumBits1 == 64 && NumBits2 == 32;
15515 }
15516 
15517 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15518   // Generally speaking, zexts are not free, but they are free when they can be
15519   // folded with other operations.
15520   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15521     EVT MemVT = LD->getMemoryVT();
15522     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15523          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15524         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15525          LD->getExtensionType() == ISD::ZEXTLOAD))
15526       return true;
15527   }
15528 
15529   // FIXME: Add other cases...
15530   //  - 32-bit shifts with a zext to i64
15531   //  - zext after ctlz, bswap, etc.
15532   //  - zext after and by a constant mask
15533 
15534   return TargetLowering::isZExtFree(Val, VT2);
15535 }
15536 
15537 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15538   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15539          "invalid fpext types");
15540   // Extending to float128 is not free.
15541   if (DestVT == MVT::f128)
15542     return false;
15543   return true;
15544 }
15545 
15546 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15547   return isInt<16>(Imm) || isUInt<16>(Imm);
15548 }
15549 
15550 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15551   return isInt<16>(Imm) || isUInt<16>(Imm);
15552 }
15553 
15554 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15555                                                        unsigned,
15556                                                        unsigned,
15557                                                        MachineMemOperand::Flags,
15558                                                        bool *Fast) const {
15559   if (DisablePPCUnaligned)
15560     return false;
15561 
15562   // PowerPC supports unaligned memory access for simple non-vector types.
15563   // Although accessing unaligned addresses is not as efficient as accessing
15564   // aligned addresses, it is generally more efficient than manual expansion,
15565   // and generally only traps for software emulation when crossing page
15566   // boundaries.
15567 
15568   if (!VT.isSimple())
15569     return false;
15570 
15571   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15572     return false;
15573 
15574   if (VT.getSimpleVT().isVector()) {
15575     if (Subtarget.hasVSX()) {
15576       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15577           VT != MVT::v4f32 && VT != MVT::v4i32)
15578         return false;
15579     } else {
15580       return false;
15581     }
15582   }
15583 
15584   if (VT == MVT::ppcf128)
15585     return false;
15586 
15587   if (Fast)
15588     *Fast = true;
15589 
15590   return true;
15591 }
15592 
15593 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15594                                                    EVT VT) const {
15595   return isFMAFasterThanFMulAndFAdd(
15596       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15597 }
15598 
15599 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15600                                                    Type *Ty) const {
15601   switch (Ty->getScalarType()->getTypeID()) {
15602   case Type::FloatTyID:
15603   case Type::DoubleTyID:
15604     return true;
15605   case Type::FP128TyID:
15606     return EnableQuadPrecision && Subtarget.hasP9Vector();
15607   default:
15608     return false;
15609   }
15610 }
15611 
15612 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15613 // FIXME: add more patterns which are profitable to hoist.
15614 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15615   if (I->getOpcode() != Instruction::FMul)
15616     return true;
15617 
15618   if (!I->hasOneUse())
15619     return true;
15620 
15621   Instruction *User = I->user_back();
15622   assert(User && "A single use instruction with no uses.");
15623 
15624   if (User->getOpcode() != Instruction::FSub &&
15625       User->getOpcode() != Instruction::FAdd)
15626     return true;
15627 
15628   const TargetOptions &Options = getTargetMachine().Options;
15629   const Function *F = I->getFunction();
15630   const DataLayout &DL = F->getParent()->getDataLayout();
15631   Type *Ty = User->getOperand(0)->getType();
15632 
15633   return !(
15634       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15635       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15636       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15637 }
15638 
15639 const MCPhysReg *
15640 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15641   // LR is a callee-save register, but we must treat it as clobbered by any call
15642   // site. Hence we include LR in the scratch registers, which are in turn added
15643   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15644   // to CTR, which is used by any indirect call.
15645   static const MCPhysReg ScratchRegs[] = {
15646     PPC::X12, PPC::LR8, PPC::CTR8, 0
15647   };
15648 
15649   return ScratchRegs;
15650 }
15651 
15652 Register PPCTargetLowering::getExceptionPointerRegister(
15653     const Constant *PersonalityFn) const {
15654   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15655 }
15656 
15657 Register PPCTargetLowering::getExceptionSelectorRegister(
15658     const Constant *PersonalityFn) const {
15659   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15660 }
15661 
15662 bool
15663 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15664                      EVT VT , unsigned DefinedValues) const {
15665   if (VT == MVT::v2i64)
15666     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15667 
15668   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15669     return true;
15670 
15671   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15672 }
15673 
15674 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15675   if (DisableILPPref || Subtarget.enableMachineScheduler())
15676     return TargetLowering::getSchedulingPreference(N);
15677 
15678   return Sched::ILP;
15679 }
15680 
15681 // Create a fast isel object.
15682 FastISel *
15683 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15684                                   const TargetLibraryInfo *LibInfo) const {
15685   return PPC::createFastISel(FuncInfo, LibInfo);
15686 }
15687 
15688 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15689   if (!Subtarget.isPPC64()) return;
15690 
15691   // Update IsSplitCSR in PPCFunctionInfo
15692   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15693   PFI->setIsSplitCSR(true);
15694 }
15695 
15696 void PPCTargetLowering::insertCopiesSplitCSR(
15697   MachineBasicBlock *Entry,
15698   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15699   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15700   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15701   if (!IStart)
15702     return;
15703 
15704   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15705   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15706   MachineBasicBlock::iterator MBBI = Entry->begin();
15707   for (const MCPhysReg *I = IStart; *I; ++I) {
15708     const TargetRegisterClass *RC = nullptr;
15709     if (PPC::G8RCRegClass.contains(*I))
15710       RC = &PPC::G8RCRegClass;
15711     else if (PPC::F8RCRegClass.contains(*I))
15712       RC = &PPC::F8RCRegClass;
15713     else if (PPC::CRRCRegClass.contains(*I))
15714       RC = &PPC::CRRCRegClass;
15715     else if (PPC::VRRCRegClass.contains(*I))
15716       RC = &PPC::VRRCRegClass;
15717     else
15718       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15719 
15720     Register NewVR = MRI->createVirtualRegister(RC);
15721     // Create copy from CSR to a virtual register.
15722     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15723     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15724     // nounwind. If we want to generalize this later, we may need to emit
15725     // CFI pseudo-instructions.
15726     assert(Entry->getParent()->getFunction().hasFnAttribute(
15727              Attribute::NoUnwind) &&
15728            "Function should be nounwind in insertCopiesSplitCSR!");
15729     Entry->addLiveIn(*I);
15730     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15731       .addReg(*I);
15732 
15733     // Insert the copy-back instructions right before the terminator.
15734     for (auto *Exit : Exits)
15735       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15736               TII->get(TargetOpcode::COPY), *I)
15737         .addReg(NewVR);
15738   }
15739 }
15740 
15741 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15742 bool PPCTargetLowering::useLoadStackGuardNode() const {
15743   if (!Subtarget.isTargetLinux())
15744     return TargetLowering::useLoadStackGuardNode();
15745   return true;
15746 }
15747 
15748 // Override to disable global variable loading on Linux.
15749 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15750   if (!Subtarget.isTargetLinux())
15751     return TargetLowering::insertSSPDeclarations(M);
15752 }
15753 
15754 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15755                                      bool ForCodeSize) const {
15756   if (!VT.isSimple() || !Subtarget.hasVSX())
15757     return false;
15758 
15759   switch(VT.getSimpleVT().SimpleTy) {
15760   default:
15761     // For FP types that are currently not supported by PPC backend, return
15762     // false. Examples: f16, f80.
15763     return false;
15764   case MVT::f32:
15765   case MVT::f64:
15766   case MVT::ppcf128:
15767     return Imm.isPosZero();
15768   }
15769 }
15770 
15771 // For vector shift operation op, fold
15772 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15773 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15774                                   SelectionDAG &DAG) {
15775   SDValue N0 = N->getOperand(0);
15776   SDValue N1 = N->getOperand(1);
15777   EVT VT = N0.getValueType();
15778   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15779   unsigned Opcode = N->getOpcode();
15780   unsigned TargetOpcode;
15781 
15782   switch (Opcode) {
15783   default:
15784     llvm_unreachable("Unexpected shift operation");
15785   case ISD::SHL:
15786     TargetOpcode = PPCISD::SHL;
15787     break;
15788   case ISD::SRL:
15789     TargetOpcode = PPCISD::SRL;
15790     break;
15791   case ISD::SRA:
15792     TargetOpcode = PPCISD::SRA;
15793     break;
15794   }
15795 
15796   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15797       N1->getOpcode() == ISD::AND)
15798     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15799       if (Mask->getZExtValue() == OpSizeInBits - 1)
15800         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15801 
15802   return SDValue();
15803 }
15804 
15805 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15806   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15807     return Value;
15808 
15809   SDValue N0 = N->getOperand(0);
15810   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15811   if (!Subtarget.isISA3_0() ||
15812       N0.getOpcode() != ISD::SIGN_EXTEND ||
15813       N0.getOperand(0).getValueType() != MVT::i32 ||
15814       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15815     return SDValue();
15816 
15817   // We can't save an operation here if the value is already extended, and
15818   // the existing shift is easier to combine.
15819   SDValue ExtsSrc = N0.getOperand(0);
15820   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15821       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15822     return SDValue();
15823 
15824   SDLoc DL(N0);
15825   SDValue ShiftBy = SDValue(CN1, 0);
15826   // We want the shift amount to be i32 on the extswli, but the shift could
15827   // have an i64.
15828   if (ShiftBy.getValueType() == MVT::i64)
15829     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15830 
15831   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15832                          ShiftBy);
15833 }
15834 
15835 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15836   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15837     return Value;
15838 
15839   return SDValue();
15840 }
15841 
15842 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15843   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15844     return Value;
15845 
15846   return SDValue();
15847 }
15848 
15849 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15850 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15851 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15852 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15853 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15854                                  const PPCSubtarget &Subtarget) {
15855   if (!Subtarget.isPPC64())
15856     return SDValue();
15857 
15858   SDValue LHS = N->getOperand(0);
15859   SDValue RHS = N->getOperand(1);
15860 
15861   auto isZextOfCompareWithConstant = [](SDValue Op) {
15862     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15863         Op.getValueType() != MVT::i64)
15864       return false;
15865 
15866     SDValue Cmp = Op.getOperand(0);
15867     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15868         Cmp.getOperand(0).getValueType() != MVT::i64)
15869       return false;
15870 
15871     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15872       int64_t NegConstant = 0 - Constant->getSExtValue();
15873       // Due to the limitations of the addi instruction,
15874       // -C is required to be [-32768, 32767].
15875       return isInt<16>(NegConstant);
15876     }
15877 
15878     return false;
15879   };
15880 
15881   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15882   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15883 
15884   // If there is a pattern, canonicalize a zext operand to the RHS.
15885   if (LHSHasPattern && !RHSHasPattern)
15886     std::swap(LHS, RHS);
15887   else if (!LHSHasPattern && !RHSHasPattern)
15888     return SDValue();
15889 
15890   SDLoc DL(N);
15891   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15892   SDValue Cmp = RHS.getOperand(0);
15893   SDValue Z = Cmp.getOperand(0);
15894   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15895 
15896   assert(Constant && "Constant Should not be a null pointer.");
15897   int64_t NegConstant = 0 - Constant->getSExtValue();
15898 
15899   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15900   default: break;
15901   case ISD::SETNE: {
15902     //                                 when C == 0
15903     //                             --> addze X, (addic Z, -1).carry
15904     //                            /
15905     // add X, (zext(setne Z, C))--
15906     //                            \    when -32768 <= -C <= 32767 && C != 0
15907     //                             --> addze X, (addic (addi Z, -C), -1).carry
15908     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15909                               DAG.getConstant(NegConstant, DL, MVT::i64));
15910     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15911     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15912                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15913     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15914                        SDValue(Addc.getNode(), 1));
15915     }
15916   case ISD::SETEQ: {
15917     //                                 when C == 0
15918     //                             --> addze X, (subfic Z, 0).carry
15919     //                            /
15920     // add X, (zext(sete  Z, C))--
15921     //                            \    when -32768 <= -C <= 32767 && C != 0
15922     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15923     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15924                               DAG.getConstant(NegConstant, DL, MVT::i64));
15925     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15926     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15927                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15928     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15929                        SDValue(Subc.getNode(), 1));
15930     }
15931   }
15932 
15933   return SDValue();
15934 }
15935 
15936 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15937   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15938     return Value;
15939 
15940   return SDValue();
15941 }
15942 
15943 // Detect TRUNCATE operations on bitcasts of float128 values.
15944 // What we are looking for here is the situtation where we extract a subset
15945 // of bits from a 128 bit float.
15946 // This can be of two forms:
15947 // 1) BITCAST of f128 feeding TRUNCATE
15948 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15949 // The reason this is required is because we do not have a legal i128 type
15950 // and so we want to prevent having to store the f128 and then reload part
15951 // of it.
15952 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15953                                            DAGCombinerInfo &DCI) const {
15954   // If we are using CRBits then try that first.
15955   if (Subtarget.useCRBits()) {
15956     // Check if CRBits did anything and return that if it did.
15957     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15958       return CRTruncValue;
15959   }
15960 
15961   SDLoc dl(N);
15962   SDValue Op0 = N->getOperand(0);
15963 
15964   // Looking for a truncate of i128 to i64.
15965   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15966     return SDValue();
15967 
15968   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15969 
15970   // SRL feeding TRUNCATE.
15971   if (Op0.getOpcode() == ISD::SRL) {
15972     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15973     // The right shift has to be by 64 bits.
15974     if (!ConstNode || ConstNode->getZExtValue() != 64)
15975       return SDValue();
15976 
15977     // Switch the element number to extract.
15978     EltToExtract = EltToExtract ? 0 : 1;
15979     // Update Op0 past the SRL.
15980     Op0 = Op0.getOperand(0);
15981   }
15982 
15983   // BITCAST feeding a TRUNCATE possibly via SRL.
15984   if (Op0.getOpcode() == ISD::BITCAST &&
15985       Op0.getValueType() == MVT::i128 &&
15986       Op0.getOperand(0).getValueType() == MVT::f128) {
15987     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15988     return DCI.DAG.getNode(
15989         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15990         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15991   }
15992   return SDValue();
15993 }
15994 
15995 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15996   SelectionDAG &DAG = DCI.DAG;
15997 
15998   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15999   if (!ConstOpOrElement)
16000     return SDValue();
16001 
16002   // An imul is usually smaller than the alternative sequence for legal type.
16003   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16004       isOperationLegal(ISD::MUL, N->getValueType(0)))
16005     return SDValue();
16006 
16007   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16008     switch (this->Subtarget.getCPUDirective()) {
16009     default:
16010       // TODO: enhance the condition for subtarget before pwr8
16011       return false;
16012     case PPC::DIR_PWR8:
16013       //  type        mul     add    shl
16014       // scalar        4       1      1
16015       // vector        7       2      2
16016       return true;
16017     case PPC::DIR_PWR9:
16018     case PPC::DIR_PWR_FUTURE:
16019       //  type        mul     add    shl
16020       // scalar        5       2      2
16021       // vector        7       2      2
16022 
16023       // The cycle RATIO of related operations are showed as a table above.
16024       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16025       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16026       // are 4, it is always profitable; but for 3 instrs patterns
16027       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16028       // So we should only do it for vector type.
16029       return IsAddOne && IsNeg ? VT.isVector() : true;
16030     }
16031   };
16032 
16033   EVT VT = N->getValueType(0);
16034   SDLoc DL(N);
16035 
16036   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16037   bool IsNeg = MulAmt.isNegative();
16038   APInt MulAmtAbs = MulAmt.abs();
16039 
16040   if ((MulAmtAbs - 1).isPowerOf2()) {
16041     // (mul x, 2^N + 1) => (add (shl x, N), x)
16042     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16043 
16044     if (!IsProfitable(IsNeg, true, VT))
16045       return SDValue();
16046 
16047     SDValue Op0 = N->getOperand(0);
16048     SDValue Op1 =
16049         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16050                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16051     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16052 
16053     if (!IsNeg)
16054       return Res;
16055 
16056     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16057   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16058     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16059     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16060 
16061     if (!IsProfitable(IsNeg, false, VT))
16062       return SDValue();
16063 
16064     SDValue Op0 = N->getOperand(0);
16065     SDValue Op1 =
16066         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16067                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16068 
16069     if (!IsNeg)
16070       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16071     else
16072       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16073 
16074   } else {
16075     return SDValue();
16076   }
16077 }
16078 
16079 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16080   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16081   if (!Subtarget.is64BitELFABI())
16082     return false;
16083 
16084   // If not a tail call then no need to proceed.
16085   if (!CI->isTailCall())
16086     return false;
16087 
16088   // If sibling calls have been disabled and tail-calls aren't guaranteed
16089   // there is no reason to duplicate.
16090   auto &TM = getTargetMachine();
16091   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16092     return false;
16093 
16094   // Can't tail call a function called indirectly, or if it has variadic args.
16095   const Function *Callee = CI->getCalledFunction();
16096   if (!Callee || Callee->isVarArg())
16097     return false;
16098 
16099   // Make sure the callee and caller calling conventions are eligible for tco.
16100   const Function *Caller = CI->getParent()->getParent();
16101   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16102                                            CI->getCallingConv()))
16103       return false;
16104 
16105   // If the function is local then we have a good chance at tail-calling it
16106   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16107 }
16108 
16109 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16110   if (!Subtarget.hasVSX())
16111     return false;
16112   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16113     return true;
16114   return VT == MVT::f32 || VT == MVT::f64 ||
16115     VT == MVT::v4f32 || VT == MVT::v2f64;
16116 }
16117 
16118 bool PPCTargetLowering::
16119 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16120   const Value *Mask = AndI.getOperand(1);
16121   // If the mask is suitable for andi. or andis. we should sink the and.
16122   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16123     // Can't handle constants wider than 64-bits.
16124     if (CI->getBitWidth() > 64)
16125       return false;
16126     int64_t ConstVal = CI->getZExtValue();
16127     return isUInt<16>(ConstVal) ||
16128       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16129   }
16130 
16131   // For non-constant masks, we can always use the record-form and.
16132   return true;
16133 }
16134 
16135 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16136 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16137 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16138 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16139 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16140 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16141   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16142   assert(Subtarget.hasP9Altivec() &&
16143          "Only combine this when P9 altivec supported!");
16144   EVT VT = N->getValueType(0);
16145   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16146     return SDValue();
16147 
16148   SelectionDAG &DAG = DCI.DAG;
16149   SDLoc dl(N);
16150   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16151     // Even for signed integers, if it's known to be positive (as signed
16152     // integer) due to zero-extended inputs.
16153     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16154     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16155     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16156          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16157         (SubOpcd1 == ISD::ZERO_EXTEND ||
16158          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16159       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16160                          N->getOperand(0)->getOperand(0),
16161                          N->getOperand(0)->getOperand(1),
16162                          DAG.getTargetConstant(0, dl, MVT::i32));
16163     }
16164 
16165     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16166     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16167         N->getOperand(0).hasOneUse()) {
16168       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16169                          N->getOperand(0)->getOperand(0),
16170                          N->getOperand(0)->getOperand(1),
16171                          DAG.getTargetConstant(1, dl, MVT::i32));
16172     }
16173   }
16174 
16175   return SDValue();
16176 }
16177 
16178 // For type v4i32/v8ii16/v16i8, transform
16179 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16180 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16181 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16182 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16183 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16184                                           DAGCombinerInfo &DCI) const {
16185   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16186   assert(Subtarget.hasP9Altivec() &&
16187          "Only combine this when P9 altivec supported!");
16188 
16189   SelectionDAG &DAG = DCI.DAG;
16190   SDLoc dl(N);
16191   SDValue Cond = N->getOperand(0);
16192   SDValue TrueOpnd = N->getOperand(1);
16193   SDValue FalseOpnd = N->getOperand(2);
16194   EVT VT = N->getOperand(1).getValueType();
16195 
16196   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16197       FalseOpnd.getOpcode() != ISD::SUB)
16198     return SDValue();
16199 
16200   // ABSD only available for type v4i32/v8i16/v16i8
16201   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16202     return SDValue();
16203 
16204   // At least to save one more dependent computation
16205   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16206     return SDValue();
16207 
16208   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16209 
16210   // Can only handle unsigned comparison here
16211   switch (CC) {
16212   default:
16213     return SDValue();
16214   case ISD::SETUGT:
16215   case ISD::SETUGE:
16216     break;
16217   case ISD::SETULT:
16218   case ISD::SETULE:
16219     std::swap(TrueOpnd, FalseOpnd);
16220     break;
16221   }
16222 
16223   SDValue CmpOpnd1 = Cond.getOperand(0);
16224   SDValue CmpOpnd2 = Cond.getOperand(1);
16225 
16226   // SETCC CmpOpnd1 CmpOpnd2 cond
16227   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16228   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16229   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16230       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16231       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16232       FalseOpnd.getOperand(1) == CmpOpnd1) {
16233     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16234                        CmpOpnd1, CmpOpnd2,
16235                        DAG.getTargetConstant(0, dl, MVT::i32));
16236   }
16237 
16238   return SDValue();
16239 }
16240