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 &&
1337         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1338       MaxAlign = 32;
1339     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1340              MaxAlign < 16)
1341       MaxAlign = 16;
1342   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1343     unsigned EltAlign = 0;
1344     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1345     if (EltAlign > MaxAlign)
1346       MaxAlign = EltAlign;
1347   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1348     for (auto *EltTy : STy->elements()) {
1349       unsigned EltAlign = 0;
1350       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1351       if (EltAlign > MaxAlign)
1352         MaxAlign = EltAlign;
1353       if (MaxAlign == MaxMaxAlign)
1354         break;
1355     }
1356   }
1357 }
1358 
1359 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1360 /// function arguments in the caller parameter area.
1361 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1362                                                   const DataLayout &DL) const {
1363   // 16byte and wider vectors are passed on 16byte boundary.
1364   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1365   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1366   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1367     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1368   return Align;
1369 }
1370 
1371 bool PPCTargetLowering::useSoftFloat() const {
1372   return Subtarget.useSoftFloat();
1373 }
1374 
1375 bool PPCTargetLowering::hasSPE() const {
1376   return Subtarget.hasSPE();
1377 }
1378 
1379 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1380   return VT.isScalarInteger();
1381 }
1382 
1383 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1384   switch ((PPCISD::NodeType)Opcode) {
1385   case PPCISD::FIRST_NUMBER:    break;
1386   case PPCISD::FSEL:            return "PPCISD::FSEL";
1387   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1388   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1389   case PPCISD::FCFID:           return "PPCISD::FCFID";
1390   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1391   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1392   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1393   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1394   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1395   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1396   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1397   case PPCISD::FP_TO_UINT_IN_VSR:
1398                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1399   case PPCISD::FP_TO_SINT_IN_VSR:
1400                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1401   case PPCISD::FRE:             return "PPCISD::FRE";
1402   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1403   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1404   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1405   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1406   case PPCISD::VPERM:           return "PPCISD::VPERM";
1407   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1408   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1409   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1410   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1411   case PPCISD::CMPB:            return "PPCISD::CMPB";
1412   case PPCISD::Hi:              return "PPCISD::Hi";
1413   case PPCISD::Lo:              return "PPCISD::Lo";
1414   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1415   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1416   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1417   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1418   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1419   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1420   case PPCISD::SRL:             return "PPCISD::SRL";
1421   case PPCISD::SRA:             return "PPCISD::SRA";
1422   case PPCISD::SHL:             return "PPCISD::SHL";
1423   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1424   case PPCISD::CALL:            return "PPCISD::CALL";
1425   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1426   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1427   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1428   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1429   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1430   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1431   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1432   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1433   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1434   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1435   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1436   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1437   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1438   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1439   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1440   case PPCISD::ANDI_rec_1_EQ_BIT:
1441     return "PPCISD::ANDI_rec_1_EQ_BIT";
1442   case PPCISD::ANDI_rec_1_GT_BIT:
1443     return "PPCISD::ANDI_rec_1_GT_BIT";
1444   case PPCISD::VCMP:            return "PPCISD::VCMP";
1445   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1446   case PPCISD::LBRX:            return "PPCISD::LBRX";
1447   case PPCISD::STBRX:           return "PPCISD::STBRX";
1448   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1449   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1450   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1451   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1452   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1453   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1454   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1455   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1456   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1457   case PPCISD::ST_VSR_SCAL_INT:
1458                                 return "PPCISD::ST_VSR_SCAL_INT";
1459   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1460   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1461   case PPCISD::BDZ:             return "PPCISD::BDZ";
1462   case PPCISD::MFFS:            return "PPCISD::MFFS";
1463   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1464   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1465   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1466   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1467   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1468   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1469   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1470   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1471   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1472   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1473   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1474   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1475   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1476   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1477   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1478   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1479   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1480   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1481   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1482   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1483   case PPCISD::SC:              return "PPCISD::SC";
1484   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1485   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1486   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1487   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1488   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1489   case PPCISD::VABSD:           return "PPCISD::VABSD";
1490   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1491   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1492   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1493   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1494   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1495   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1496   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1497   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1498   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1499   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1500   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1501   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1502   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1503   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1504   }
1505   return nullptr;
1506 }
1507 
1508 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1509                                           EVT VT) const {
1510   if (!VT.isVector())
1511     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1512 
1513   if (Subtarget.hasQPX())
1514     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1515 
1516   return VT.changeVectorElementTypeToInteger();
1517 }
1518 
1519 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1520   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1521   return true;
1522 }
1523 
1524 //===----------------------------------------------------------------------===//
1525 // Node matching predicates, for use by the tblgen matching code.
1526 //===----------------------------------------------------------------------===//
1527 
1528 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1529 static bool isFloatingPointZero(SDValue Op) {
1530   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1531     return CFP->getValueAPF().isZero();
1532   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1533     // Maybe this has already been legalized into the constant pool?
1534     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1535       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1536         return CFP->getValueAPF().isZero();
1537   }
1538   return false;
1539 }
1540 
1541 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1542 /// true if Op is undef or if it matches the specified value.
1543 static bool isConstantOrUndef(int Op, int Val) {
1544   return Op < 0 || Op == Val;
1545 }
1546 
1547 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1548 /// VPKUHUM instruction.
1549 /// The ShuffleKind distinguishes between big-endian operations with
1550 /// two different inputs (0), either-endian operations with two identical
1551 /// inputs (1), and little-endian operations with two different inputs (2).
1552 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1553 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1554                                SelectionDAG &DAG) {
1555   bool IsLE = DAG.getDataLayout().isLittleEndian();
1556   if (ShuffleKind == 0) {
1557     if (IsLE)
1558       return false;
1559     for (unsigned i = 0; i != 16; ++i)
1560       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1561         return false;
1562   } else if (ShuffleKind == 2) {
1563     if (!IsLE)
1564       return false;
1565     for (unsigned i = 0; i != 16; ++i)
1566       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1567         return false;
1568   } else if (ShuffleKind == 1) {
1569     unsigned j = IsLE ? 0 : 1;
1570     for (unsigned i = 0; i != 8; ++i)
1571       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1572           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1573         return false;
1574   }
1575   return true;
1576 }
1577 
1578 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1579 /// VPKUWUM instruction.
1580 /// The ShuffleKind distinguishes between big-endian operations with
1581 /// two different inputs (0), either-endian operations with two identical
1582 /// inputs (1), and little-endian operations with two different inputs (2).
1583 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1584 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1585                                SelectionDAG &DAG) {
1586   bool IsLE = DAG.getDataLayout().isLittleEndian();
1587   if (ShuffleKind == 0) {
1588     if (IsLE)
1589       return false;
1590     for (unsigned i = 0; i != 16; i += 2)
1591       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1592           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1593         return false;
1594   } else if (ShuffleKind == 2) {
1595     if (!IsLE)
1596       return false;
1597     for (unsigned i = 0; i != 16; i += 2)
1598       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1599           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1600         return false;
1601   } else if (ShuffleKind == 1) {
1602     unsigned j = IsLE ? 0 : 2;
1603     for (unsigned i = 0; i != 8; i += 2)
1604       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1605           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1606           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1607           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1608         return false;
1609   }
1610   return true;
1611 }
1612 
1613 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1614 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1615 /// current subtarget.
1616 ///
1617 /// The ShuffleKind distinguishes between big-endian operations with
1618 /// two different inputs (0), either-endian operations with two identical
1619 /// inputs (1), and little-endian operations with two different inputs (2).
1620 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1621 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1622                                SelectionDAG &DAG) {
1623   const PPCSubtarget& Subtarget =
1624       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1625   if (!Subtarget.hasP8Vector())
1626     return false;
1627 
1628   bool IsLE = DAG.getDataLayout().isLittleEndian();
1629   if (ShuffleKind == 0) {
1630     if (IsLE)
1631       return false;
1632     for (unsigned i = 0; i != 16; i += 4)
1633       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1634           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1635           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1636           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1637         return false;
1638   } else if (ShuffleKind == 2) {
1639     if (!IsLE)
1640       return false;
1641     for (unsigned i = 0; i != 16; i += 4)
1642       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1643           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1644           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1645           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1646         return false;
1647   } else if (ShuffleKind == 1) {
1648     unsigned j = IsLE ? 0 : 4;
1649     for (unsigned i = 0; i != 8; i += 4)
1650       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1651           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1652           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1653           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1654           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1655           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1656           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1657           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1658         return false;
1659   }
1660   return true;
1661 }
1662 
1663 /// isVMerge - Common function, used to match vmrg* shuffles.
1664 ///
1665 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1666                      unsigned LHSStart, unsigned RHSStart) {
1667   if (N->getValueType(0) != MVT::v16i8)
1668     return false;
1669   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1670          "Unsupported merge size!");
1671 
1672   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1673     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1674       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1675                              LHSStart+j+i*UnitSize) ||
1676           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1677                              RHSStart+j+i*UnitSize))
1678         return false;
1679     }
1680   return true;
1681 }
1682 
1683 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1684 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1685 /// The ShuffleKind distinguishes between big-endian merges with two
1686 /// different inputs (0), either-endian merges with two identical inputs (1),
1687 /// and little-endian merges with two different inputs (2).  For the latter,
1688 /// the input operands are swapped (see PPCInstrAltivec.td).
1689 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1690                              unsigned ShuffleKind, SelectionDAG &DAG) {
1691   if (DAG.getDataLayout().isLittleEndian()) {
1692     if (ShuffleKind == 1) // unary
1693       return isVMerge(N, UnitSize, 0, 0);
1694     else if (ShuffleKind == 2) // swapped
1695       return isVMerge(N, UnitSize, 0, 16);
1696     else
1697       return false;
1698   } else {
1699     if (ShuffleKind == 1) // unary
1700       return isVMerge(N, UnitSize, 8, 8);
1701     else if (ShuffleKind == 0) // normal
1702       return isVMerge(N, UnitSize, 8, 24);
1703     else
1704       return false;
1705   }
1706 }
1707 
1708 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1709 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1710 /// The ShuffleKind distinguishes between big-endian merges with two
1711 /// different inputs (0), either-endian merges with two identical inputs (1),
1712 /// and little-endian merges with two different inputs (2).  For the latter,
1713 /// the input operands are swapped (see PPCInstrAltivec.td).
1714 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1715                              unsigned ShuffleKind, SelectionDAG &DAG) {
1716   if (DAG.getDataLayout().isLittleEndian()) {
1717     if (ShuffleKind == 1) // unary
1718       return isVMerge(N, UnitSize, 8, 8);
1719     else if (ShuffleKind == 2) // swapped
1720       return isVMerge(N, UnitSize, 8, 24);
1721     else
1722       return false;
1723   } else {
1724     if (ShuffleKind == 1) // unary
1725       return isVMerge(N, UnitSize, 0, 0);
1726     else if (ShuffleKind == 0) // normal
1727       return isVMerge(N, UnitSize, 0, 16);
1728     else
1729       return false;
1730   }
1731 }
1732 
1733 /**
1734  * Common function used to match vmrgew and vmrgow shuffles
1735  *
1736  * The indexOffset determines whether to look for even or odd words in
1737  * the shuffle mask. This is based on the of the endianness of the target
1738  * machine.
1739  *   - Little Endian:
1740  *     - Use offset of 0 to check for odd elements
1741  *     - Use offset of 4 to check for even elements
1742  *   - Big Endian:
1743  *     - Use offset of 0 to check for even elements
1744  *     - Use offset of 4 to check for odd elements
1745  * A detailed description of the vector element ordering for little endian and
1746  * big endian can be found at
1747  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1748  * Targeting your applications - what little endian and big endian IBM XL C/C++
1749  * compiler differences mean to you
1750  *
1751  * The mask to the shuffle vector instruction specifies the indices of the
1752  * elements from the two input vectors to place in the result. The elements are
1753  * numbered in array-access order, starting with the first vector. These vectors
1754  * are always of type v16i8, thus each vector will contain 16 elements of size
1755  * 8. More info on the shuffle vector can be found in the
1756  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1757  * Language Reference.
1758  *
1759  * The RHSStartValue indicates whether the same input vectors are used (unary)
1760  * or two different input vectors are used, based on the following:
1761  *   - If the instruction uses the same vector for both inputs, the range of the
1762  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1763  *     be 0.
1764  *   - If the instruction has two different vectors then the range of the
1765  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1766  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1767  *     to 31 specify elements in the second vector).
1768  *
1769  * \param[in] N The shuffle vector SD Node to analyze
1770  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1771  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1772  * vector to the shuffle_vector instruction
1773  * \return true iff this shuffle vector represents an even or odd word merge
1774  */
1775 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1776                      unsigned RHSStartValue) {
1777   if (N->getValueType(0) != MVT::v16i8)
1778     return false;
1779 
1780   for (unsigned i = 0; i < 2; ++i)
1781     for (unsigned j = 0; j < 4; ++j)
1782       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1783                              i*RHSStartValue+j+IndexOffset) ||
1784           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1785                              i*RHSStartValue+j+IndexOffset+8))
1786         return false;
1787   return true;
1788 }
1789 
1790 /**
1791  * Determine if the specified shuffle mask is suitable for the vmrgew or
1792  * vmrgow instructions.
1793  *
1794  * \param[in] N The shuffle vector SD Node to analyze
1795  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1796  * \param[in] ShuffleKind Identify the type of merge:
1797  *   - 0 = big-endian merge with two different inputs;
1798  *   - 1 = either-endian merge with two identical inputs;
1799  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1800  *     little-endian merges).
1801  * \param[in] DAG The current SelectionDAG
1802  * \return true iff this shuffle mask
1803  */
1804 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1805                               unsigned ShuffleKind, SelectionDAG &DAG) {
1806   if (DAG.getDataLayout().isLittleEndian()) {
1807     unsigned indexOffset = CheckEven ? 4 : 0;
1808     if (ShuffleKind == 1) // Unary
1809       return isVMerge(N, indexOffset, 0);
1810     else if (ShuffleKind == 2) // swapped
1811       return isVMerge(N, indexOffset, 16);
1812     else
1813       return false;
1814   }
1815   else {
1816     unsigned indexOffset = CheckEven ? 0 : 4;
1817     if (ShuffleKind == 1) // Unary
1818       return isVMerge(N, indexOffset, 0);
1819     else if (ShuffleKind == 0) // Normal
1820       return isVMerge(N, indexOffset, 16);
1821     else
1822       return false;
1823   }
1824   return false;
1825 }
1826 
1827 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1828 /// amount, otherwise return -1.
1829 /// The ShuffleKind distinguishes between big-endian operations with two
1830 /// different inputs (0), either-endian operations with two identical inputs
1831 /// (1), and little-endian operations with two different inputs (2).  For the
1832 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1833 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1834                              SelectionDAG &DAG) {
1835   if (N->getValueType(0) != MVT::v16i8)
1836     return -1;
1837 
1838   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1839 
1840   // Find the first non-undef value in the shuffle mask.
1841   unsigned i;
1842   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1843     /*search*/;
1844 
1845   if (i == 16) return -1;  // all undef.
1846 
1847   // Otherwise, check to see if the rest of the elements are consecutively
1848   // numbered from this value.
1849   unsigned ShiftAmt = SVOp->getMaskElt(i);
1850   if (ShiftAmt < i) return -1;
1851 
1852   ShiftAmt -= i;
1853   bool isLE = DAG.getDataLayout().isLittleEndian();
1854 
1855   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1856     // Check the rest of the elements to see if they are consecutive.
1857     for (++i; i != 16; ++i)
1858       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1859         return -1;
1860   } else if (ShuffleKind == 1) {
1861     // Check the rest of the elements to see if they are consecutive.
1862     for (++i; i != 16; ++i)
1863       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1864         return -1;
1865   } else
1866     return -1;
1867 
1868   if (isLE)
1869     ShiftAmt = 16 - ShiftAmt;
1870 
1871   return ShiftAmt;
1872 }
1873 
1874 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1875 /// specifies a splat of a single element that is suitable for input to
1876 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1877 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1878   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1879          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1880 
1881   // The consecutive indices need to specify an element, not part of two
1882   // different elements.  So abandon ship early if this isn't the case.
1883   if (N->getMaskElt(0) % EltSize != 0)
1884     return false;
1885 
1886   // This is a splat operation if each element of the permute is the same, and
1887   // if the value doesn't reference the second vector.
1888   unsigned ElementBase = N->getMaskElt(0);
1889 
1890   // FIXME: Handle UNDEF elements too!
1891   if (ElementBase >= 16)
1892     return false;
1893 
1894   // Check that the indices are consecutive, in the case of a multi-byte element
1895   // splatted with a v16i8 mask.
1896   for (unsigned i = 1; i != EltSize; ++i)
1897     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1898       return false;
1899 
1900   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1901     if (N->getMaskElt(i) < 0) continue;
1902     for (unsigned j = 0; j != EltSize; ++j)
1903       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1904         return false;
1905   }
1906   return true;
1907 }
1908 
1909 /// Check that the mask is shuffling N byte elements. Within each N byte
1910 /// element of the mask, the indices could be either in increasing or
1911 /// decreasing order as long as they are consecutive.
1912 /// \param[in] N the shuffle vector SD Node to analyze
1913 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1914 /// Word/DoubleWord/QuadWord).
1915 /// \param[in] StepLen the delta indices number among the N byte element, if
1916 /// the mask is in increasing/decreasing order then it is 1/-1.
1917 /// \return true iff the mask is shuffling N byte elements.
1918 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1919                                    int StepLen) {
1920   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1921          "Unexpected element width.");
1922   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1923 
1924   unsigned NumOfElem = 16 / Width;
1925   unsigned MaskVal[16]; //  Width is never greater than 16
1926   for (unsigned i = 0; i < NumOfElem; ++i) {
1927     MaskVal[0] = N->getMaskElt(i * Width);
1928     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1929       return false;
1930     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1931       return false;
1932     }
1933 
1934     for (unsigned int j = 1; j < Width; ++j) {
1935       MaskVal[j] = N->getMaskElt(i * Width + j);
1936       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1937         return false;
1938       }
1939     }
1940   }
1941 
1942   return true;
1943 }
1944 
1945 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1946                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1947   if (!isNByteElemShuffleMask(N, 4, 1))
1948     return false;
1949 
1950   // Now we look at mask elements 0,4,8,12
1951   unsigned M0 = N->getMaskElt(0) / 4;
1952   unsigned M1 = N->getMaskElt(4) / 4;
1953   unsigned M2 = N->getMaskElt(8) / 4;
1954   unsigned M3 = N->getMaskElt(12) / 4;
1955   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1956   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1957 
1958   // Below, let H and L be arbitrary elements of the shuffle mask
1959   // where H is in the range [4,7] and L is in the range [0,3].
1960   // H, 1, 2, 3 or L, 5, 6, 7
1961   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1962       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1963     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1964     InsertAtByte = IsLE ? 12 : 0;
1965     Swap = M0 < 4;
1966     return true;
1967   }
1968   // 0, H, 2, 3 or 4, L, 6, 7
1969   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1970       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1971     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1972     InsertAtByte = IsLE ? 8 : 4;
1973     Swap = M1 < 4;
1974     return true;
1975   }
1976   // 0, 1, H, 3 or 4, 5, L, 7
1977   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1978       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1979     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1980     InsertAtByte = IsLE ? 4 : 8;
1981     Swap = M2 < 4;
1982     return true;
1983   }
1984   // 0, 1, 2, H or 4, 5, 6, L
1985   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1986       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1987     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1988     InsertAtByte = IsLE ? 0 : 12;
1989     Swap = M3 < 4;
1990     return true;
1991   }
1992 
1993   // If both vector operands for the shuffle are the same vector, the mask will
1994   // contain only elements from the first one and the second one will be undef.
1995   if (N->getOperand(1).isUndef()) {
1996     ShiftElts = 0;
1997     Swap = true;
1998     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1999     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2000       InsertAtByte = IsLE ? 12 : 0;
2001       return true;
2002     }
2003     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2004       InsertAtByte = IsLE ? 8 : 4;
2005       return true;
2006     }
2007     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2008       InsertAtByte = IsLE ? 4 : 8;
2009       return true;
2010     }
2011     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2012       InsertAtByte = IsLE ? 0 : 12;
2013       return true;
2014     }
2015   }
2016 
2017   return false;
2018 }
2019 
2020 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2021                                bool &Swap, bool IsLE) {
2022   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2023   // Ensure each byte index of the word is consecutive.
2024   if (!isNByteElemShuffleMask(N, 4, 1))
2025     return false;
2026 
2027   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2028   unsigned M0 = N->getMaskElt(0) / 4;
2029   unsigned M1 = N->getMaskElt(4) / 4;
2030   unsigned M2 = N->getMaskElt(8) / 4;
2031   unsigned M3 = N->getMaskElt(12) / 4;
2032 
2033   // If both vector operands for the shuffle are the same vector, the mask will
2034   // contain only elements from the first one and the second one will be undef.
2035   if (N->getOperand(1).isUndef()) {
2036     assert(M0 < 4 && "Indexing into an undef vector?");
2037     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2038       return false;
2039 
2040     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2041     Swap = false;
2042     return true;
2043   }
2044 
2045   // Ensure each word index of the ShuffleVector Mask is consecutive.
2046   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2047     return false;
2048 
2049   if (IsLE) {
2050     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2051       // Input vectors don't need to be swapped if the leading element
2052       // of the result is one of the 3 left elements of the second vector
2053       // (or if there is no shift to be done at all).
2054       Swap = false;
2055       ShiftElts = (8 - M0) % 8;
2056     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2057       // Input vectors need to be swapped if the leading element
2058       // of the result is one of the 3 left elements of the first vector
2059       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2060       Swap = true;
2061       ShiftElts = (4 - M0) % 4;
2062     }
2063 
2064     return true;
2065   } else {                                          // BE
2066     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2067       // Input vectors don't need to be swapped if the leading element
2068       // of the result is one of the 4 elements of the first vector.
2069       Swap = false;
2070       ShiftElts = M0;
2071     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2072       // Input vectors need to be swapped if the leading element
2073       // of the result is one of the 4 elements of the right vector.
2074       Swap = true;
2075       ShiftElts = M0 - 4;
2076     }
2077 
2078     return true;
2079   }
2080 }
2081 
2082 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2083   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2084 
2085   if (!isNByteElemShuffleMask(N, Width, -1))
2086     return false;
2087 
2088   for (int i = 0; i < 16; i += Width)
2089     if (N->getMaskElt(i) != i + Width - 1)
2090       return false;
2091 
2092   return true;
2093 }
2094 
2095 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2096   return isXXBRShuffleMaskHelper(N, 2);
2097 }
2098 
2099 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2100   return isXXBRShuffleMaskHelper(N, 4);
2101 }
2102 
2103 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2104   return isXXBRShuffleMaskHelper(N, 8);
2105 }
2106 
2107 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2108   return isXXBRShuffleMaskHelper(N, 16);
2109 }
2110 
2111 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2112 /// if the inputs to the instruction should be swapped and set \p DM to the
2113 /// value for the immediate.
2114 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2115 /// AND element 0 of the result comes from the first input (LE) or second input
2116 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2117 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2118 /// mask.
2119 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2120                                bool &Swap, bool IsLE) {
2121   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2122 
2123   // Ensure each byte index of the double word is consecutive.
2124   if (!isNByteElemShuffleMask(N, 8, 1))
2125     return false;
2126 
2127   unsigned M0 = N->getMaskElt(0) / 8;
2128   unsigned M1 = N->getMaskElt(8) / 8;
2129   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2130 
2131   // If both vector operands for the shuffle are the same vector, the mask will
2132   // contain only elements from the first one and the second one will be undef.
2133   if (N->getOperand(1).isUndef()) {
2134     if ((M0 | M1) < 2) {
2135       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2136       Swap = false;
2137       return true;
2138     } else
2139       return false;
2140   }
2141 
2142   if (IsLE) {
2143     if (M0 > 1 && M1 < 2) {
2144       Swap = false;
2145     } else if (M0 < 2 && M1 > 1) {
2146       M0 = (M0 + 2) % 4;
2147       M1 = (M1 + 2) % 4;
2148       Swap = true;
2149     } else
2150       return false;
2151 
2152     // Note: if control flow comes here that means Swap is already set above
2153     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2154     return true;
2155   } else { // BE
2156     if (M0 < 2 && M1 > 1) {
2157       Swap = false;
2158     } else if (M0 > 1 && M1 < 2) {
2159       M0 = (M0 + 2) % 4;
2160       M1 = (M1 + 2) % 4;
2161       Swap = true;
2162     } else
2163       return false;
2164 
2165     // Note: if control flow comes here that means Swap is already set above
2166     DM = (M0 << 1) + (M1 & 1);
2167     return true;
2168   }
2169 }
2170 
2171 
2172 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2173 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2174 /// elements are counted from the left of the vector register).
2175 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2176                                          SelectionDAG &DAG) {
2177   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2178   assert(isSplatShuffleMask(SVOp, EltSize));
2179   if (DAG.getDataLayout().isLittleEndian())
2180     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2181   else
2182     return SVOp->getMaskElt(0) / EltSize;
2183 }
2184 
2185 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2186 /// by using a vspltis[bhw] instruction of the specified element size, return
2187 /// the constant being splatted.  The ByteSize field indicates the number of
2188 /// bytes of each element [124] -> [bhw].
2189 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2190   SDValue OpVal(nullptr, 0);
2191 
2192   // If ByteSize of the splat is bigger than the element size of the
2193   // build_vector, then we have a case where we are checking for a splat where
2194   // multiple elements of the buildvector are folded together into a single
2195   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2196   unsigned EltSize = 16/N->getNumOperands();
2197   if (EltSize < ByteSize) {
2198     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2199     SDValue UniquedVals[4];
2200     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2201 
2202     // See if all of the elements in the buildvector agree across.
2203     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2204       if (N->getOperand(i).isUndef()) continue;
2205       // If the element isn't a constant, bail fully out.
2206       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2207 
2208       if (!UniquedVals[i&(Multiple-1)].getNode())
2209         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2210       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2211         return SDValue();  // no match.
2212     }
2213 
2214     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2215     // either constant or undef values that are identical for each chunk.  See
2216     // if these chunks can form into a larger vspltis*.
2217 
2218     // Check to see if all of the leading entries are either 0 or -1.  If
2219     // neither, then this won't fit into the immediate field.
2220     bool LeadingZero = true;
2221     bool LeadingOnes = true;
2222     for (unsigned i = 0; i != Multiple-1; ++i) {
2223       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2224 
2225       LeadingZero &= isNullConstant(UniquedVals[i]);
2226       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2227     }
2228     // Finally, check the least significant entry.
2229     if (LeadingZero) {
2230       if (!UniquedVals[Multiple-1].getNode())
2231         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2232       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2233       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2234         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2235     }
2236     if (LeadingOnes) {
2237       if (!UniquedVals[Multiple-1].getNode())
2238         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2239       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2240       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2241         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2242     }
2243 
2244     return SDValue();
2245   }
2246 
2247   // Check to see if this buildvec has a single non-undef value in its elements.
2248   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2249     if (N->getOperand(i).isUndef()) continue;
2250     if (!OpVal.getNode())
2251       OpVal = N->getOperand(i);
2252     else if (OpVal != N->getOperand(i))
2253       return SDValue();
2254   }
2255 
2256   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2257 
2258   unsigned ValSizeInBytes = EltSize;
2259   uint64_t Value = 0;
2260   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2261     Value = CN->getZExtValue();
2262   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2263     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2264     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2265   }
2266 
2267   // If the splat value is larger than the element value, then we can never do
2268   // this splat.  The only case that we could fit the replicated bits into our
2269   // immediate field for would be zero, and we prefer to use vxor for it.
2270   if (ValSizeInBytes < ByteSize) return SDValue();
2271 
2272   // If the element value is larger than the splat value, check if it consists
2273   // of a repeated bit pattern of size ByteSize.
2274   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2275     return SDValue();
2276 
2277   // Properly sign extend the value.
2278   int MaskVal = SignExtend32(Value, ByteSize * 8);
2279 
2280   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2281   if (MaskVal == 0) return SDValue();
2282 
2283   // Finally, if this value fits in a 5 bit sext field, return it
2284   if (SignExtend32<5>(MaskVal) == MaskVal)
2285     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2286   return SDValue();
2287 }
2288 
2289 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2290 /// amount, otherwise return -1.
2291 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2292   EVT VT = N->getValueType(0);
2293   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2294     return -1;
2295 
2296   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2297 
2298   // Find the first non-undef value in the shuffle mask.
2299   unsigned i;
2300   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2301     /*search*/;
2302 
2303   if (i == 4) return -1;  // all undef.
2304 
2305   // Otherwise, check to see if the rest of the elements are consecutively
2306   // numbered from this value.
2307   unsigned ShiftAmt = SVOp->getMaskElt(i);
2308   if (ShiftAmt < i) return -1;
2309   ShiftAmt -= i;
2310 
2311   // Check the rest of the elements to see if they are consecutive.
2312   for (++i; i != 4; ++i)
2313     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2314       return -1;
2315 
2316   return ShiftAmt;
2317 }
2318 
2319 //===----------------------------------------------------------------------===//
2320 //  Addressing Mode Selection
2321 //===----------------------------------------------------------------------===//
2322 
2323 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2324 /// or 64-bit immediate, and if the value can be accurately represented as a
2325 /// sign extension from a 16-bit value.  If so, this returns true and the
2326 /// immediate.
2327 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2328   if (!isa<ConstantSDNode>(N))
2329     return false;
2330 
2331   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2332   if (N->getValueType(0) == MVT::i32)
2333     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2334   else
2335     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2336 }
2337 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2338   return isIntS16Immediate(Op.getNode(), Imm);
2339 }
2340 
2341 
2342 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2343 /// be represented as an indexed [r+r] operation.
2344 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2345                                                SDValue &Index,
2346                                                SelectionDAG &DAG) const {
2347   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2348       UI != E; ++UI) {
2349     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2350       if (Memop->getMemoryVT() == MVT::f64) {
2351           Base = N.getOperand(0);
2352           Index = N.getOperand(1);
2353           return true;
2354       }
2355     }
2356   }
2357   return false;
2358 }
2359 
2360 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2361 /// can be represented as an indexed [r+r] operation.  Returns false if it
2362 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2363 /// non-zero and N can be represented by a base register plus a signed 16-bit
2364 /// displacement, make a more precise judgement by checking (displacement % \p
2365 /// EncodingAlignment).
2366 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2367                                             SDValue &Index, SelectionDAG &DAG,
2368                                             unsigned EncodingAlignment) const {
2369   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2370   // a [pc+imm].
2371   if (SelectAddressPCRel(N, Base))
2372     return false;
2373 
2374   int16_t imm = 0;
2375   if (N.getOpcode() == ISD::ADD) {
2376     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2377     // SPE load/store can only handle 8-bit offsets.
2378     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2379         return true;
2380     if (isIntS16Immediate(N.getOperand(1), imm) &&
2381         (!EncodingAlignment || !(imm % EncodingAlignment)))
2382       return false; // r+i
2383     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2384       return false;    // r+i
2385 
2386     Base = N.getOperand(0);
2387     Index = N.getOperand(1);
2388     return true;
2389   } else if (N.getOpcode() == ISD::OR) {
2390     if (isIntS16Immediate(N.getOperand(1), imm) &&
2391         (!EncodingAlignment || !(imm % EncodingAlignment)))
2392       return false; // r+i can fold it if we can.
2393 
2394     // If this is an or of disjoint bitfields, we can codegen this as an add
2395     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2396     // disjoint.
2397     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2398 
2399     if (LHSKnown.Zero.getBoolValue()) {
2400       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2401       // If all of the bits are known zero on the LHS or RHS, the add won't
2402       // carry.
2403       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2404         Base = N.getOperand(0);
2405         Index = N.getOperand(1);
2406         return true;
2407       }
2408     }
2409   }
2410 
2411   return false;
2412 }
2413 
2414 // If we happen to be doing an i64 load or store into a stack slot that has
2415 // less than a 4-byte alignment, then the frame-index elimination may need to
2416 // use an indexed load or store instruction (because the offset may not be a
2417 // multiple of 4). The extra register needed to hold the offset comes from the
2418 // register scavenger, and it is possible that the scavenger will need to use
2419 // an emergency spill slot. As a result, we need to make sure that a spill slot
2420 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2421 // stack slot.
2422 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2423   // FIXME: This does not handle the LWA case.
2424   if (VT != MVT::i64)
2425     return;
2426 
2427   // NOTE: We'll exclude negative FIs here, which come from argument
2428   // lowering, because there are no known test cases triggering this problem
2429   // using packed structures (or similar). We can remove this exclusion if
2430   // we find such a test case. The reason why this is so test-case driven is
2431   // because this entire 'fixup' is only to prevent crashes (from the
2432   // register scavenger) on not-really-valid inputs. For example, if we have:
2433   //   %a = alloca i1
2434   //   %b = bitcast i1* %a to i64*
2435   //   store i64* a, i64 b
2436   // then the store should really be marked as 'align 1', but is not. If it
2437   // were marked as 'align 1' then the indexed form would have been
2438   // instruction-selected initially, and the problem this 'fixup' is preventing
2439   // won't happen regardless.
2440   if (FrameIdx < 0)
2441     return;
2442 
2443   MachineFunction &MF = DAG.getMachineFunction();
2444   MachineFrameInfo &MFI = MF.getFrameInfo();
2445 
2446   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2447     return;
2448 
2449   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2450   FuncInfo->setHasNonRISpills();
2451 }
2452 
2453 /// Returns true if the address N can be represented by a base register plus
2454 /// a signed 16-bit displacement [r+imm], and if it is not better
2455 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2456 /// displacements that are multiples of that value.
2457 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2458                                             SDValue &Base,
2459                                             SelectionDAG &DAG,
2460                                             unsigned EncodingAlignment) const {
2461   // FIXME dl should come from parent load or store, not from address
2462   SDLoc dl(N);
2463 
2464   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2465   // a [pc+imm].
2466   if (SelectAddressPCRel(N, Base))
2467     return false;
2468 
2469   // If this can be more profitably realized as r+r, fail.
2470   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2471     return false;
2472 
2473   if (N.getOpcode() == ISD::ADD) {
2474     int16_t imm = 0;
2475     if (isIntS16Immediate(N.getOperand(1), imm) &&
2476         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2477       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2478       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2479         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2480         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2481       } else {
2482         Base = N.getOperand(0);
2483       }
2484       return true; // [r+i]
2485     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2486       // Match LOAD (ADD (X, Lo(G))).
2487       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2488              && "Cannot handle constant offsets yet!");
2489       Disp = N.getOperand(1).getOperand(0);  // The global address.
2490       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2491              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2492              Disp.getOpcode() == ISD::TargetConstantPool ||
2493              Disp.getOpcode() == ISD::TargetJumpTable);
2494       Base = N.getOperand(0);
2495       return true;  // [&g+r]
2496     }
2497   } else if (N.getOpcode() == ISD::OR) {
2498     int16_t imm = 0;
2499     if (isIntS16Immediate(N.getOperand(1), imm) &&
2500         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2501       // If this is an or of disjoint bitfields, we can codegen this as an add
2502       // (for better address arithmetic) if the LHS and RHS of the OR are
2503       // provably disjoint.
2504       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2505 
2506       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2507         // If all of the bits are known zero on the LHS or RHS, the add won't
2508         // carry.
2509         if (FrameIndexSDNode *FI =
2510               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2511           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2512           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2513         } else {
2514           Base = N.getOperand(0);
2515         }
2516         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2517         return true;
2518       }
2519     }
2520   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2521     // Loading from a constant address.
2522 
2523     // If this address fits entirely in a 16-bit sext immediate field, codegen
2524     // this as "d, 0"
2525     int16_t Imm;
2526     if (isIntS16Immediate(CN, Imm) &&
2527         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2528       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2529       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2530                              CN->getValueType(0));
2531       return true;
2532     }
2533 
2534     // Handle 32-bit sext immediates with LIS + addr mode.
2535     if ((CN->getValueType(0) == MVT::i32 ||
2536          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2537         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2538       int Addr = (int)CN->getZExtValue();
2539 
2540       // Otherwise, break this down into an LIS + disp.
2541       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2542 
2543       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2544                                    MVT::i32);
2545       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2546       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2547       return true;
2548     }
2549   }
2550 
2551   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2552   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2553     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2554     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2555   } else
2556     Base = N;
2557   return true;      // [r+0]
2558 }
2559 
2560 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2561 /// represented as an indexed [r+r] operation.
2562 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2563                                                 SDValue &Index,
2564                                                 SelectionDAG &DAG) const {
2565   // Check to see if we can easily represent this as an [r+r] address.  This
2566   // will fail if it thinks that the address is more profitably represented as
2567   // reg+imm, e.g. where imm = 0.
2568   if (SelectAddressRegReg(N, Base, Index, DAG))
2569     return true;
2570 
2571   // If the address is the result of an add, we will utilize the fact that the
2572   // address calculation includes an implicit add.  However, we can reduce
2573   // register pressure if we do not materialize a constant just for use as the
2574   // index register.  We only get rid of the add if it is not an add of a
2575   // value and a 16-bit signed constant and both have a single use.
2576   int16_t imm = 0;
2577   if (N.getOpcode() == ISD::ADD &&
2578       (!isIntS16Immediate(N.getOperand(1), imm) ||
2579        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2580     Base = N.getOperand(0);
2581     Index = N.getOperand(1);
2582     return true;
2583   }
2584 
2585   // Otherwise, do it the hard way, using R0 as the base register.
2586   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2587                          N.getValueType());
2588   Index = N;
2589   return true;
2590 }
2591 
2592 /// Returns true if this address is a PC Relative address.
2593 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2594 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2595 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2596   // This is a materialize PC Relative node. Always select this as PC Relative.
2597   Base = N;
2598   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2599     return true;
2600   if (ConstantPoolSDNode *CPN = dyn_cast<ConstantPoolSDNode>(N))
2601     if (CPN->getTargetFlags() & PPCII::MO_PCREL_FLAG)
2602       return true;
2603   if (GlobalAddressSDNode *GAN = dyn_cast<GlobalAddressSDNode>(N))
2604     if (GAN->getTargetFlags() & PPCII::MO_PCREL_FLAG)
2605       return true;
2606   return false;
2607 }
2608 
2609 /// Returns true if we should use a direct load into vector instruction
2610 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2611 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2612 
2613   // If there are any other uses other than scalar to vector, then we should
2614   // keep it as a scalar load -> direct move pattern to prevent multiple
2615   // loads.
2616   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2617   if (!LD)
2618     return false;
2619 
2620   EVT MemVT = LD->getMemoryVT();
2621   if (!MemVT.isSimple())
2622     return false;
2623   switch(MemVT.getSimpleVT().SimpleTy) {
2624   case MVT::i64:
2625     break;
2626   case MVT::i32:
2627     if (!ST.hasP8Vector())
2628       return false;
2629     break;
2630   case MVT::i16:
2631   case MVT::i8:
2632     if (!ST.hasP9Vector())
2633       return false;
2634     break;
2635   default:
2636     return false;
2637   }
2638 
2639   SDValue LoadedVal(N, 0);
2640   if (!LoadedVal.hasOneUse())
2641     return false;
2642 
2643   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2644        UI != UE; ++UI)
2645     if (UI.getUse().get().getResNo() == 0 &&
2646         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2647       return false;
2648 
2649   return true;
2650 }
2651 
2652 /// getPreIndexedAddressParts - returns true by value, base pointer and
2653 /// offset pointer and addressing mode by reference if the node's address
2654 /// can be legally represented as pre-indexed load / store address.
2655 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2656                                                   SDValue &Offset,
2657                                                   ISD::MemIndexedMode &AM,
2658                                                   SelectionDAG &DAG) const {
2659   if (DisablePPCPreinc) return false;
2660 
2661   bool isLoad = true;
2662   SDValue Ptr;
2663   EVT VT;
2664   unsigned Alignment;
2665   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2666     Ptr = LD->getBasePtr();
2667     VT = LD->getMemoryVT();
2668     Alignment = LD->getAlignment();
2669   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2670     Ptr = ST->getBasePtr();
2671     VT  = ST->getMemoryVT();
2672     Alignment = ST->getAlignment();
2673     isLoad = false;
2674   } else
2675     return false;
2676 
2677   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2678   // instructions because we can fold these into a more efficient instruction
2679   // instead, (such as LXSD).
2680   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2681     return false;
2682   }
2683 
2684   // PowerPC doesn't have preinc load/store instructions for vectors (except
2685   // for QPX, which does have preinc r+r forms).
2686   if (VT.isVector()) {
2687     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2688       return false;
2689     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2690       AM = ISD::PRE_INC;
2691       return true;
2692     }
2693   }
2694 
2695   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2696     // Common code will reject creating a pre-inc form if the base pointer
2697     // is a frame index, or if N is a store and the base pointer is either
2698     // the same as or a predecessor of the value being stored.  Check for
2699     // those situations here, and try with swapped Base/Offset instead.
2700     bool Swap = false;
2701 
2702     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2703       Swap = true;
2704     else if (!isLoad) {
2705       SDValue Val = cast<StoreSDNode>(N)->getValue();
2706       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2707         Swap = true;
2708     }
2709 
2710     if (Swap)
2711       std::swap(Base, Offset);
2712 
2713     AM = ISD::PRE_INC;
2714     return true;
2715   }
2716 
2717   // LDU/STU can only handle immediates that are a multiple of 4.
2718   if (VT != MVT::i64) {
2719     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2720       return false;
2721   } else {
2722     // LDU/STU need an address with at least 4-byte alignment.
2723     if (Alignment < 4)
2724       return false;
2725 
2726     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2727       return false;
2728   }
2729 
2730   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2731     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2732     // sext i32 to i64 when addr mode is r+i.
2733     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2734         LD->getExtensionType() == ISD::SEXTLOAD &&
2735         isa<ConstantSDNode>(Offset))
2736       return false;
2737   }
2738 
2739   AM = ISD::PRE_INC;
2740   return true;
2741 }
2742 
2743 //===----------------------------------------------------------------------===//
2744 //  LowerOperation implementation
2745 //===----------------------------------------------------------------------===//
2746 
2747 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2748 /// and LoOpFlags to the target MO flags.
2749 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2750                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2751                                const GlobalValue *GV = nullptr) {
2752   HiOpFlags = PPCII::MO_HA;
2753   LoOpFlags = PPCII::MO_LO;
2754 
2755   // Don't use the pic base if not in PIC relocation model.
2756   if (IsPIC) {
2757     HiOpFlags |= PPCII::MO_PIC_FLAG;
2758     LoOpFlags |= PPCII::MO_PIC_FLAG;
2759   }
2760 }
2761 
2762 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2763                              SelectionDAG &DAG) {
2764   SDLoc DL(HiPart);
2765   EVT PtrVT = HiPart.getValueType();
2766   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2767 
2768   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2769   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2770 
2771   // With PIC, the first instruction is actually "GR+hi(&G)".
2772   if (isPIC)
2773     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2774                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2775 
2776   // Generate non-pic code that has direct accesses to the constant pool.
2777   // The address of the global is just (hi(&g)+lo(&g)).
2778   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2779 }
2780 
2781 static void setUsesTOCBasePtr(MachineFunction &MF) {
2782   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2783   FuncInfo->setUsesTOCBasePtr();
2784 }
2785 
2786 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2787   setUsesTOCBasePtr(DAG.getMachineFunction());
2788 }
2789 
2790 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2791                                        SDValue GA) const {
2792   const bool Is64Bit = Subtarget.isPPC64();
2793   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2794   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2795                         : Subtarget.isAIXABI()
2796                               ? DAG.getRegister(PPC::R2, VT)
2797                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2798   SDValue Ops[] = { GA, Reg };
2799   return DAG.getMemIntrinsicNode(
2800       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2801       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2802       MachineMemOperand::MOLoad);
2803 }
2804 
2805 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2806                                              SelectionDAG &DAG) const {
2807   EVT PtrVT = Op.getValueType();
2808   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2809   const Constant *C = CP->getConstVal();
2810 
2811   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2812   // The actual address of the GlobalValue is stored in the TOC.
2813   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2814     if (Subtarget.hasPCRelativeMemops()) {
2815       SDLoc DL(CP);
2816       EVT Ty = getPointerTy(DAG.getDataLayout());
2817       SDValue ConstPool = DAG.getTargetConstantPool(C, Ty,
2818                                                     CP->getAlignment(),
2819                                                     CP->getOffset(),
2820                                                     PPCII::MO_PCREL_FLAG);
2821       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2822     }
2823     setUsesTOCBasePtr(DAG);
2824     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2825     return getTOCEntry(DAG, SDLoc(CP), GA);
2826   }
2827 
2828   unsigned MOHiFlag, MOLoFlag;
2829   bool IsPIC = isPositionIndependent();
2830   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2831 
2832   if (IsPIC && Subtarget.isSVR4ABI()) {
2833     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2834                                            PPCII::MO_PIC_FLAG);
2835     return getTOCEntry(DAG, SDLoc(CP), GA);
2836   }
2837 
2838   SDValue CPIHi =
2839     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2840   SDValue CPILo =
2841     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2842   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2843 }
2844 
2845 // For 64-bit PowerPC, prefer the more compact relative encodings.
2846 // This trades 32 bits per jump table entry for one or two instructions
2847 // on the jump site.
2848 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2849   if (isJumpTableRelative())
2850     return MachineJumpTableInfo::EK_LabelDifference32;
2851 
2852   return TargetLowering::getJumpTableEncoding();
2853 }
2854 
2855 bool PPCTargetLowering::isJumpTableRelative() const {
2856   if (UseAbsoluteJumpTables)
2857     return false;
2858   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2859     return true;
2860   return TargetLowering::isJumpTableRelative();
2861 }
2862 
2863 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2864                                                     SelectionDAG &DAG) const {
2865   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2866     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2867 
2868   switch (getTargetMachine().getCodeModel()) {
2869   case CodeModel::Small:
2870   case CodeModel::Medium:
2871     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2872   default:
2873     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2874                        getPointerTy(DAG.getDataLayout()));
2875   }
2876 }
2877 
2878 const MCExpr *
2879 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2880                                                 unsigned JTI,
2881                                                 MCContext &Ctx) const {
2882   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2883     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2884 
2885   switch (getTargetMachine().getCodeModel()) {
2886   case CodeModel::Small:
2887   case CodeModel::Medium:
2888     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2889   default:
2890     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2891   }
2892 }
2893 
2894 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2895   EVT PtrVT = Op.getValueType();
2896   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2897 
2898   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2899   // The actual address of the GlobalValue is stored in the TOC.
2900   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2901     setUsesTOCBasePtr(DAG);
2902     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2903     return getTOCEntry(DAG, SDLoc(JT), GA);
2904   }
2905 
2906   unsigned MOHiFlag, MOLoFlag;
2907   bool IsPIC = isPositionIndependent();
2908   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2909 
2910   if (IsPIC && Subtarget.isSVR4ABI()) {
2911     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2912                                         PPCII::MO_PIC_FLAG);
2913     return getTOCEntry(DAG, SDLoc(GA), GA);
2914   }
2915 
2916   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2917   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2918   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2919 }
2920 
2921 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2922                                              SelectionDAG &DAG) const {
2923   EVT PtrVT = Op.getValueType();
2924   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2925   const BlockAddress *BA = BASDN->getBlockAddress();
2926 
2927   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2928   // The actual BlockAddress is stored in the TOC.
2929   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2930     setUsesTOCBasePtr(DAG);
2931     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2932     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2933   }
2934 
2935   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2936   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2937     return getTOCEntry(
2938         DAG, SDLoc(BASDN),
2939         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2940 
2941   unsigned MOHiFlag, MOLoFlag;
2942   bool IsPIC = isPositionIndependent();
2943   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2944   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2945   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2946   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2947 }
2948 
2949 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2950                                               SelectionDAG &DAG) const {
2951   // FIXME: TLS addresses currently use medium model code sequences,
2952   // which is the most useful form.  Eventually support for small and
2953   // large models could be added if users need it, at the cost of
2954   // additional complexity.
2955   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2956   if (DAG.getTarget().useEmulatedTLS())
2957     return LowerToTLSEmulatedModel(GA, DAG);
2958 
2959   SDLoc dl(GA);
2960   const GlobalValue *GV = GA->getGlobal();
2961   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2962   bool is64bit = Subtarget.isPPC64();
2963   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2964   PICLevel::Level picLevel = M->getPICLevel();
2965 
2966   const TargetMachine &TM = getTargetMachine();
2967   TLSModel::Model Model = TM.getTLSModel(GV);
2968 
2969   if (Model == TLSModel::LocalExec) {
2970     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2971                                                PPCII::MO_TPREL_HA);
2972     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2973                                                PPCII::MO_TPREL_LO);
2974     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2975                              : DAG.getRegister(PPC::R2, MVT::i32);
2976 
2977     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2978     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2979   }
2980 
2981   if (Model == TLSModel::InitialExec) {
2982     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2983     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2984                                                 PPCII::MO_TLS);
2985     SDValue GOTPtr;
2986     if (is64bit) {
2987       setUsesTOCBasePtr(DAG);
2988       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2989       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2990                            PtrVT, GOTReg, TGA);
2991     } else {
2992       if (!TM.isPositionIndependent())
2993         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2994       else if (picLevel == PICLevel::SmallPIC)
2995         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2996       else
2997         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2998     }
2999     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
3000                                    PtrVT, TGA, GOTPtr);
3001     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3002   }
3003 
3004   if (Model == TLSModel::GeneralDynamic) {
3005     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3006     SDValue GOTPtr;
3007     if (is64bit) {
3008       setUsesTOCBasePtr(DAG);
3009       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3010       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3011                                    GOTReg, TGA);
3012     } else {
3013       if (picLevel == PICLevel::SmallPIC)
3014         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3015       else
3016         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3017     }
3018     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3019                        GOTPtr, TGA, TGA);
3020   }
3021 
3022   if (Model == TLSModel::LocalDynamic) {
3023     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3024     SDValue GOTPtr;
3025     if (is64bit) {
3026       setUsesTOCBasePtr(DAG);
3027       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3028       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3029                            GOTReg, TGA);
3030     } else {
3031       if (picLevel == PICLevel::SmallPIC)
3032         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3033       else
3034         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3035     }
3036     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3037                                   PtrVT, GOTPtr, TGA, TGA);
3038     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3039                                       PtrVT, TLSAddr, TGA);
3040     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3041   }
3042 
3043   llvm_unreachable("Unknown TLS model!");
3044 }
3045 
3046 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3047                                               SelectionDAG &DAG) const {
3048   EVT PtrVT = Op.getValueType();
3049   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3050   SDLoc DL(GSDN);
3051   const GlobalValue *GV = GSDN->getGlobal();
3052 
3053   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3054   // The actual address of the GlobalValue is stored in the TOC.
3055   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3056     if (Subtarget.isUsingPCRelativeCalls()) {
3057       EVT Ty = getPointerTy(DAG.getDataLayout());
3058       if (isAccessedAsGotIndirect(Op)) {
3059         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3060                                                 PPCII::MO_PCREL_FLAG |
3061                                                     PPCII::MO_GOT_FLAG);
3062         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3063         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3064                                    MachinePointerInfo());
3065         return Load;
3066       } else {
3067         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3068                                                 PPCII::MO_PCREL_FLAG);
3069         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3070       }
3071     }
3072     setUsesTOCBasePtr(DAG);
3073     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3074     return getTOCEntry(DAG, DL, GA);
3075   }
3076 
3077   unsigned MOHiFlag, MOLoFlag;
3078   bool IsPIC = isPositionIndependent();
3079   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3080 
3081   if (IsPIC && Subtarget.isSVR4ABI()) {
3082     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3083                                             GSDN->getOffset(),
3084                                             PPCII::MO_PIC_FLAG);
3085     return getTOCEntry(DAG, DL, GA);
3086   }
3087 
3088   SDValue GAHi =
3089     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3090   SDValue GALo =
3091     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3092 
3093   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3094 }
3095 
3096 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3097   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3098   SDLoc dl(Op);
3099 
3100   if (Op.getValueType() == MVT::v2i64) {
3101     // When the operands themselves are v2i64 values, we need to do something
3102     // special because VSX has no underlying comparison operations for these.
3103     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3104       // Equality can be handled by casting to the legal type for Altivec
3105       // comparisons, everything else needs to be expanded.
3106       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3107         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3108                  DAG.getSetCC(dl, MVT::v4i32,
3109                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3110                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3111                    CC));
3112       }
3113 
3114       return SDValue();
3115     }
3116 
3117     // We handle most of these in the usual way.
3118     return Op;
3119   }
3120 
3121   // If we're comparing for equality to zero, expose the fact that this is
3122   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3123   // fold the new nodes.
3124   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3125     return V;
3126 
3127   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3128     // Leave comparisons against 0 and -1 alone for now, since they're usually
3129     // optimized.  FIXME: revisit this when we can custom lower all setcc
3130     // optimizations.
3131     if (C->isAllOnesValue() || C->isNullValue())
3132       return SDValue();
3133   }
3134 
3135   // If we have an integer seteq/setne, turn it into a compare against zero
3136   // by xor'ing the rhs with the lhs, which is faster than setting a
3137   // condition register, reading it back out, and masking the correct bit.  The
3138   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3139   // the result to other bit-twiddling opportunities.
3140   EVT LHSVT = Op.getOperand(0).getValueType();
3141   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3142     EVT VT = Op.getValueType();
3143     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3144                                 Op.getOperand(1));
3145     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3146   }
3147   return SDValue();
3148 }
3149 
3150 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3151   SDNode *Node = Op.getNode();
3152   EVT VT = Node->getValueType(0);
3153   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3154   SDValue InChain = Node->getOperand(0);
3155   SDValue VAListPtr = Node->getOperand(1);
3156   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3157   SDLoc dl(Node);
3158 
3159   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3160 
3161   // gpr_index
3162   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3163                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3164   InChain = GprIndex.getValue(1);
3165 
3166   if (VT == MVT::i64) {
3167     // Check if GprIndex is even
3168     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3169                                  DAG.getConstant(1, dl, MVT::i32));
3170     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3171                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3172     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3173                                           DAG.getConstant(1, dl, MVT::i32));
3174     // Align GprIndex to be even if it isn't
3175     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3176                            GprIndex);
3177   }
3178 
3179   // fpr index is 1 byte after gpr
3180   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3181                                DAG.getConstant(1, dl, MVT::i32));
3182 
3183   // fpr
3184   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3185                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3186   InChain = FprIndex.getValue(1);
3187 
3188   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3189                                        DAG.getConstant(8, dl, MVT::i32));
3190 
3191   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3192                                         DAG.getConstant(4, dl, MVT::i32));
3193 
3194   // areas
3195   SDValue OverflowArea =
3196       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3197   InChain = OverflowArea.getValue(1);
3198 
3199   SDValue RegSaveArea =
3200       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3201   InChain = RegSaveArea.getValue(1);
3202 
3203   // select overflow_area if index > 8
3204   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3205                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3206 
3207   // adjustment constant gpr_index * 4/8
3208   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3209                                     VT.isInteger() ? GprIndex : FprIndex,
3210                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3211                                                     MVT::i32));
3212 
3213   // OurReg = RegSaveArea + RegConstant
3214   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3215                                RegConstant);
3216 
3217   // Floating types are 32 bytes into RegSaveArea
3218   if (VT.isFloatingPoint())
3219     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3220                          DAG.getConstant(32, dl, MVT::i32));
3221 
3222   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3223   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3224                                    VT.isInteger() ? GprIndex : FprIndex,
3225                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3226                                                    MVT::i32));
3227 
3228   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3229                               VT.isInteger() ? VAListPtr : FprPtr,
3230                               MachinePointerInfo(SV), MVT::i8);
3231 
3232   // determine if we should load from reg_save_area or overflow_area
3233   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3234 
3235   // increase overflow_area by 4/8 if gpr/fpr > 8
3236   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3237                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3238                                           dl, MVT::i32));
3239 
3240   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3241                              OverflowAreaPlusN);
3242 
3243   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3244                               MachinePointerInfo(), MVT::i32);
3245 
3246   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3247 }
3248 
3249 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3250   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3251 
3252   // We have to copy the entire va_list struct:
3253   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3254   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3255                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3256                        false, true, false, MachinePointerInfo(),
3257                        MachinePointerInfo());
3258 }
3259 
3260 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3261                                                   SelectionDAG &DAG) const {
3262   if (Subtarget.isAIXABI())
3263     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3264 
3265   return Op.getOperand(0);
3266 }
3267 
3268 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3269                                                 SelectionDAG &DAG) const {
3270   if (Subtarget.isAIXABI())
3271     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3272 
3273   SDValue Chain = Op.getOperand(0);
3274   SDValue Trmp = Op.getOperand(1); // trampoline
3275   SDValue FPtr = Op.getOperand(2); // nested function
3276   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3277   SDLoc dl(Op);
3278 
3279   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3280   bool isPPC64 = (PtrVT == MVT::i64);
3281   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3282 
3283   TargetLowering::ArgListTy Args;
3284   TargetLowering::ArgListEntry Entry;
3285 
3286   Entry.Ty = IntPtrTy;
3287   Entry.Node = Trmp; Args.push_back(Entry);
3288 
3289   // TrampSize == (isPPC64 ? 48 : 40);
3290   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3291                                isPPC64 ? MVT::i64 : MVT::i32);
3292   Args.push_back(Entry);
3293 
3294   Entry.Node = FPtr; Args.push_back(Entry);
3295   Entry.Node = Nest; Args.push_back(Entry);
3296 
3297   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3298   TargetLowering::CallLoweringInfo CLI(DAG);
3299   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3300       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3301       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3302 
3303   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3304   return CallResult.second;
3305 }
3306 
3307 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3308   MachineFunction &MF = DAG.getMachineFunction();
3309   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3310   EVT PtrVT = getPointerTy(MF.getDataLayout());
3311 
3312   SDLoc dl(Op);
3313 
3314   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3315     // vastart just stores the address of the VarArgsFrameIndex slot into the
3316     // memory location argument.
3317     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3318     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3319     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3320                         MachinePointerInfo(SV));
3321   }
3322 
3323   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3324   // We suppose the given va_list is already allocated.
3325   //
3326   // typedef struct {
3327   //  char gpr;     /* index into the array of 8 GPRs
3328   //                 * stored in the register save area
3329   //                 * gpr=0 corresponds to r3,
3330   //                 * gpr=1 to r4, etc.
3331   //                 */
3332   //  char fpr;     /* index into the array of 8 FPRs
3333   //                 * stored in the register save area
3334   //                 * fpr=0 corresponds to f1,
3335   //                 * fpr=1 to f2, etc.
3336   //                 */
3337   //  char *overflow_arg_area;
3338   //                /* location on stack that holds
3339   //                 * the next overflow argument
3340   //                 */
3341   //  char *reg_save_area;
3342   //               /* where r3:r10 and f1:f8 (if saved)
3343   //                * are stored
3344   //                */
3345   // } va_list[1];
3346 
3347   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3348   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3349   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3350                                             PtrVT);
3351   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3352                                  PtrVT);
3353 
3354   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3355   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3356 
3357   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3358   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3359 
3360   uint64_t FPROffset = 1;
3361   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3362 
3363   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3364 
3365   // Store first byte : number of int regs
3366   SDValue firstStore =
3367       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3368                         MachinePointerInfo(SV), MVT::i8);
3369   uint64_t nextOffset = FPROffset;
3370   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3371                                   ConstFPROffset);
3372 
3373   // Store second byte : number of float regs
3374   SDValue secondStore =
3375       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3376                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3377   nextOffset += StackOffset;
3378   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3379 
3380   // Store second word : arguments given on stack
3381   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3382                                     MachinePointerInfo(SV, nextOffset));
3383   nextOffset += FrameOffset;
3384   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3385 
3386   // Store third word : arguments given in registers
3387   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3388                       MachinePointerInfo(SV, nextOffset));
3389 }
3390 
3391 /// FPR - The set of FP registers that should be allocated for arguments
3392 /// on Darwin and AIX.
3393 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3394                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3395                                 PPC::F11, PPC::F12, PPC::F13};
3396 
3397 /// QFPR - The set of QPX registers that should be allocated for arguments.
3398 static const MCPhysReg QFPR[] = {
3399     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3400     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3401 
3402 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3403 /// the stack.
3404 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3405                                        unsigned PtrByteSize) {
3406   unsigned ArgSize = ArgVT.getStoreSize();
3407   if (Flags.isByVal())
3408     ArgSize = Flags.getByValSize();
3409 
3410   // Round up to multiples of the pointer size, except for array members,
3411   // which are always packed.
3412   if (!Flags.isInConsecutiveRegs())
3413     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3414 
3415   return ArgSize;
3416 }
3417 
3418 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3419 /// on the stack.
3420 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3421                                          ISD::ArgFlagsTy Flags,
3422                                          unsigned PtrByteSize) {
3423   Align Alignment(PtrByteSize);
3424 
3425   // Altivec parameters are padded to a 16 byte boundary.
3426   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3427       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3428       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3429       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3430     Alignment = Align(16);
3431   // QPX vector types stored in double-precision are padded to a 32 byte
3432   // boundary.
3433   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3434     Alignment = Align(32);
3435 
3436   // ByVal parameters are aligned as requested.
3437   if (Flags.isByVal()) {
3438     auto BVAlign = Flags.getNonZeroByValAlign();
3439     if (BVAlign > PtrByteSize) {
3440       if (BVAlign.value() % PtrByteSize != 0)
3441         llvm_unreachable(
3442             "ByVal alignment is not a multiple of the pointer size");
3443 
3444       Alignment = BVAlign;
3445     }
3446   }
3447 
3448   // Array members are always packed to their original alignment.
3449   if (Flags.isInConsecutiveRegs()) {
3450     // If the array member was split into multiple registers, the first
3451     // needs to be aligned to the size of the full type.  (Except for
3452     // ppcf128, which is only aligned as its f64 components.)
3453     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3454       Alignment = Align(OrigVT.getStoreSize());
3455     else
3456       Alignment = Align(ArgVT.getStoreSize());
3457   }
3458 
3459   return Alignment;
3460 }
3461 
3462 /// CalculateStackSlotUsed - Return whether this argument will use its
3463 /// stack slot (instead of being passed in registers).  ArgOffset,
3464 /// AvailableFPRs, and AvailableVRs must hold the current argument
3465 /// position, and will be updated to account for this argument.
3466 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3467                                    ISD::ArgFlagsTy Flags,
3468                                    unsigned PtrByteSize,
3469                                    unsigned LinkageSize,
3470                                    unsigned ParamAreaSize,
3471                                    unsigned &ArgOffset,
3472                                    unsigned &AvailableFPRs,
3473                                    unsigned &AvailableVRs, bool HasQPX) {
3474   bool UseMemory = false;
3475 
3476   // Respect alignment of argument on the stack.
3477   Align Alignment =
3478       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3479   ArgOffset = alignTo(ArgOffset, Alignment);
3480   // If there's no space left in the argument save area, we must
3481   // use memory (this check also catches zero-sized arguments).
3482   if (ArgOffset >= LinkageSize + ParamAreaSize)
3483     UseMemory = true;
3484 
3485   // Allocate argument on the stack.
3486   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3487   if (Flags.isInConsecutiveRegsLast())
3488     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3489   // If we overran the argument save area, we must use memory
3490   // (this check catches arguments passed partially in memory)
3491   if (ArgOffset > LinkageSize + ParamAreaSize)
3492     UseMemory = true;
3493 
3494   // However, if the argument is actually passed in an FPR or a VR,
3495   // we don't use memory after all.
3496   if (!Flags.isByVal()) {
3497     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3498         // QPX registers overlap with the scalar FP registers.
3499         (HasQPX && (ArgVT == MVT::v4f32 ||
3500                     ArgVT == MVT::v4f64 ||
3501                     ArgVT == MVT::v4i1)))
3502       if (AvailableFPRs > 0) {
3503         --AvailableFPRs;
3504         return false;
3505       }
3506     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3507         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3508         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3509         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3510       if (AvailableVRs > 0) {
3511         --AvailableVRs;
3512         return false;
3513       }
3514   }
3515 
3516   return UseMemory;
3517 }
3518 
3519 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3520 /// ensure minimum alignment required for target.
3521 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3522                                      unsigned NumBytes) {
3523   return alignTo(NumBytes, Lowering->getStackAlign());
3524 }
3525 
3526 SDValue PPCTargetLowering::LowerFormalArguments(
3527     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3528     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3529     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3530   if (Subtarget.isAIXABI())
3531     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3532                                     InVals);
3533   if (Subtarget.is64BitELFABI())
3534     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3535                                        InVals);
3536   if (Subtarget.is32BitELFABI())
3537     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3538                                        InVals);
3539 
3540   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3541                                      InVals);
3542 }
3543 
3544 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3545     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3546     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3547     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3548 
3549   // 32-bit SVR4 ABI Stack Frame Layout:
3550   //              +-----------------------------------+
3551   //        +-->  |            Back chain             |
3552   //        |     +-----------------------------------+
3553   //        |     | Floating-point register save area |
3554   //        |     +-----------------------------------+
3555   //        |     |    General register save area     |
3556   //        |     +-----------------------------------+
3557   //        |     |          CR save word             |
3558   //        |     +-----------------------------------+
3559   //        |     |         VRSAVE save word          |
3560   //        |     +-----------------------------------+
3561   //        |     |         Alignment padding         |
3562   //        |     +-----------------------------------+
3563   //        |     |     Vector register save area     |
3564   //        |     +-----------------------------------+
3565   //        |     |       Local variable space        |
3566   //        |     +-----------------------------------+
3567   //        |     |        Parameter list area        |
3568   //        |     +-----------------------------------+
3569   //        |     |           LR save word            |
3570   //        |     +-----------------------------------+
3571   // SP-->  +---  |            Back chain             |
3572   //              +-----------------------------------+
3573   //
3574   // Specifications:
3575   //   System V Application Binary Interface PowerPC Processor Supplement
3576   //   AltiVec Technology Programming Interface Manual
3577 
3578   MachineFunction &MF = DAG.getMachineFunction();
3579   MachineFrameInfo &MFI = MF.getFrameInfo();
3580   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3581 
3582   EVT PtrVT = getPointerTy(MF.getDataLayout());
3583   // Potential tail calls could cause overwriting of argument stack slots.
3584   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3585                        (CallConv == CallingConv::Fast));
3586   unsigned PtrByteSize = 4;
3587 
3588   // Assign locations to all of the incoming arguments.
3589   SmallVector<CCValAssign, 16> ArgLocs;
3590   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3591                  *DAG.getContext());
3592 
3593   // Reserve space for the linkage area on the stack.
3594   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3595   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3596   if (useSoftFloat())
3597     CCInfo.PreAnalyzeFormalArguments(Ins);
3598 
3599   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3600   CCInfo.clearWasPPCF128();
3601 
3602   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3603     CCValAssign &VA = ArgLocs[i];
3604 
3605     // Arguments stored in registers.
3606     if (VA.isRegLoc()) {
3607       const TargetRegisterClass *RC;
3608       EVT ValVT = VA.getValVT();
3609 
3610       switch (ValVT.getSimpleVT().SimpleTy) {
3611         default:
3612           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3613         case MVT::i1:
3614         case MVT::i32:
3615           RC = &PPC::GPRCRegClass;
3616           break;
3617         case MVT::f32:
3618           if (Subtarget.hasP8Vector())
3619             RC = &PPC::VSSRCRegClass;
3620           else if (Subtarget.hasSPE())
3621             RC = &PPC::GPRCRegClass;
3622           else
3623             RC = &PPC::F4RCRegClass;
3624           break;
3625         case MVT::f64:
3626           if (Subtarget.hasVSX())
3627             RC = &PPC::VSFRCRegClass;
3628           else if (Subtarget.hasSPE())
3629             // SPE passes doubles in GPR pairs.
3630             RC = &PPC::GPRCRegClass;
3631           else
3632             RC = &PPC::F8RCRegClass;
3633           break;
3634         case MVT::v16i8:
3635         case MVT::v8i16:
3636         case MVT::v4i32:
3637           RC = &PPC::VRRCRegClass;
3638           break;
3639         case MVT::v4f32:
3640           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3641           break;
3642         case MVT::v2f64:
3643         case MVT::v2i64:
3644           RC = &PPC::VRRCRegClass;
3645           break;
3646         case MVT::v4f64:
3647           RC = &PPC::QFRCRegClass;
3648           break;
3649         case MVT::v4i1:
3650           RC = &PPC::QBRCRegClass;
3651           break;
3652       }
3653 
3654       SDValue ArgValue;
3655       // Transform the arguments stored in physical registers into
3656       // virtual ones.
3657       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3658         assert(i + 1 < e && "No second half of double precision argument");
3659         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3660         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3661         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3662         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3663         if (!Subtarget.isLittleEndian())
3664           std::swap (ArgValueLo, ArgValueHi);
3665         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3666                                ArgValueHi);
3667       } else {
3668         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3669         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3670                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3671         if (ValVT == MVT::i1)
3672           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3673       }
3674 
3675       InVals.push_back(ArgValue);
3676     } else {
3677       // Argument stored in memory.
3678       assert(VA.isMemLoc());
3679 
3680       // Get the extended size of the argument type in stack
3681       unsigned ArgSize = VA.getLocVT().getStoreSize();
3682       // Get the actual size of the argument type
3683       unsigned ObjSize = VA.getValVT().getStoreSize();
3684       unsigned ArgOffset = VA.getLocMemOffset();
3685       // Stack objects in PPC32 are right justified.
3686       ArgOffset += ArgSize - ObjSize;
3687       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3688 
3689       // Create load nodes to retrieve arguments from the stack.
3690       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3691       InVals.push_back(
3692           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3693     }
3694   }
3695 
3696   // Assign locations to all of the incoming aggregate by value arguments.
3697   // Aggregates passed by value are stored in the local variable space of the
3698   // caller's stack frame, right above the parameter list area.
3699   SmallVector<CCValAssign, 16> ByValArgLocs;
3700   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3701                       ByValArgLocs, *DAG.getContext());
3702 
3703   // Reserve stack space for the allocations in CCInfo.
3704   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3705 
3706   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3707 
3708   // Area that is at least reserved in the caller of this function.
3709   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3710   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3711 
3712   // Set the size that is at least reserved in caller of this function.  Tail
3713   // call optimized function's reserved stack space needs to be aligned so that
3714   // taking the difference between two stack areas will result in an aligned
3715   // stack.
3716   MinReservedArea =
3717       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3718   FuncInfo->setMinReservedArea(MinReservedArea);
3719 
3720   SmallVector<SDValue, 8> MemOps;
3721 
3722   // If the function takes variable number of arguments, make a frame index for
3723   // the start of the first vararg value... for expansion of llvm.va_start.
3724   if (isVarArg) {
3725     static const MCPhysReg GPArgRegs[] = {
3726       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3727       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3728     };
3729     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3730 
3731     static const MCPhysReg FPArgRegs[] = {
3732       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3733       PPC::F8
3734     };
3735     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3736 
3737     if (useSoftFloat() || hasSPE())
3738        NumFPArgRegs = 0;
3739 
3740     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3741     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3742 
3743     // Make room for NumGPArgRegs and NumFPArgRegs.
3744     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3745                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3746 
3747     FuncInfo->setVarArgsStackOffset(
3748       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3749                             CCInfo.getNextStackOffset(), true));
3750 
3751     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3752     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3753 
3754     // The fixed integer arguments of a variadic function are stored to the
3755     // VarArgsFrameIndex on the stack so that they may be loaded by
3756     // dereferencing the result of va_next.
3757     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3758       // Get an existing live-in vreg, or add a new one.
3759       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3760       if (!VReg)
3761         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3762 
3763       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3764       SDValue Store =
3765           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3766       MemOps.push_back(Store);
3767       // Increment the address by four for the next argument to store
3768       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3769       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3770     }
3771 
3772     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3773     // is set.
3774     // The double arguments are stored to the VarArgsFrameIndex
3775     // on the stack.
3776     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3777       // Get an existing live-in vreg, or add a new one.
3778       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3779       if (!VReg)
3780         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3781 
3782       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3783       SDValue Store =
3784           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3785       MemOps.push_back(Store);
3786       // Increment the address by eight for the next argument to store
3787       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3788                                          PtrVT);
3789       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3790     }
3791   }
3792 
3793   if (!MemOps.empty())
3794     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3795 
3796   return Chain;
3797 }
3798 
3799 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3800 // value to MVT::i64 and then truncate to the correct register size.
3801 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3802                                              EVT ObjectVT, SelectionDAG &DAG,
3803                                              SDValue ArgVal,
3804                                              const SDLoc &dl) const {
3805   if (Flags.isSExt())
3806     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3807                          DAG.getValueType(ObjectVT));
3808   else if (Flags.isZExt())
3809     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3810                          DAG.getValueType(ObjectVT));
3811 
3812   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3813 }
3814 
3815 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3816     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3817     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3818     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3819   // TODO: add description of PPC stack frame format, or at least some docs.
3820   //
3821   bool isELFv2ABI = Subtarget.isELFv2ABI();
3822   bool isLittleEndian = Subtarget.isLittleEndian();
3823   MachineFunction &MF = DAG.getMachineFunction();
3824   MachineFrameInfo &MFI = MF.getFrameInfo();
3825   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3826 
3827   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3828          "fastcc not supported on varargs functions");
3829 
3830   EVT PtrVT = getPointerTy(MF.getDataLayout());
3831   // Potential tail calls could cause overwriting of argument stack slots.
3832   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3833                        (CallConv == CallingConv::Fast));
3834   unsigned PtrByteSize = 8;
3835   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3836 
3837   static const MCPhysReg GPR[] = {
3838     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3839     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3840   };
3841   static const MCPhysReg VR[] = {
3842     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3843     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3844   };
3845 
3846   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3847   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3848   const unsigned Num_VR_Regs  = array_lengthof(VR);
3849   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3850 
3851   // Do a first pass over the arguments to determine whether the ABI
3852   // guarantees that our caller has allocated the parameter save area
3853   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3854   // in the ELFv2 ABI, it is true if this is a vararg function or if
3855   // any parameter is located in a stack slot.
3856 
3857   bool HasParameterArea = !isELFv2ABI || isVarArg;
3858   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3859   unsigned NumBytes = LinkageSize;
3860   unsigned AvailableFPRs = Num_FPR_Regs;
3861   unsigned AvailableVRs = Num_VR_Regs;
3862   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3863     if (Ins[i].Flags.isNest())
3864       continue;
3865 
3866     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3867                                PtrByteSize, LinkageSize, ParamAreaSize,
3868                                NumBytes, AvailableFPRs, AvailableVRs,
3869                                Subtarget.hasQPX()))
3870       HasParameterArea = true;
3871   }
3872 
3873   // Add DAG nodes to load the arguments or copy them out of registers.  On
3874   // entry to a function on PPC, the arguments start after the linkage area,
3875   // although the first ones are often in registers.
3876 
3877   unsigned ArgOffset = LinkageSize;
3878   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3879   unsigned &QFPR_idx = FPR_idx;
3880   SmallVector<SDValue, 8> MemOps;
3881   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3882   unsigned CurArgIdx = 0;
3883   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3884     SDValue ArgVal;
3885     bool needsLoad = false;
3886     EVT ObjectVT = Ins[ArgNo].VT;
3887     EVT OrigVT = Ins[ArgNo].ArgVT;
3888     unsigned ObjSize = ObjectVT.getStoreSize();
3889     unsigned ArgSize = ObjSize;
3890     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3891     if (Ins[ArgNo].isOrigArg()) {
3892       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3893       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3894     }
3895     // We re-align the argument offset for each argument, except when using the
3896     // fast calling convention, when we need to make sure we do that only when
3897     // we'll actually use a stack slot.
3898     unsigned CurArgOffset;
3899     Align Alignment;
3900     auto ComputeArgOffset = [&]() {
3901       /* Respect alignment of argument on the stack.  */
3902       Alignment =
3903           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3904       ArgOffset = alignTo(ArgOffset, Alignment);
3905       CurArgOffset = ArgOffset;
3906     };
3907 
3908     if (CallConv != CallingConv::Fast) {
3909       ComputeArgOffset();
3910 
3911       /* Compute GPR index associated with argument offset.  */
3912       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3913       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3914     }
3915 
3916     // FIXME the codegen can be much improved in some cases.
3917     // We do not have to keep everything in memory.
3918     if (Flags.isByVal()) {
3919       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3920 
3921       if (CallConv == CallingConv::Fast)
3922         ComputeArgOffset();
3923 
3924       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3925       ObjSize = Flags.getByValSize();
3926       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3927       // Empty aggregate parameters do not take up registers.  Examples:
3928       //   struct { } a;
3929       //   union  { } b;
3930       //   int c[0];
3931       // etc.  However, we have to provide a place-holder in InVals, so
3932       // pretend we have an 8-byte item at the current address for that
3933       // purpose.
3934       if (!ObjSize) {
3935         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3936         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3937         InVals.push_back(FIN);
3938         continue;
3939       }
3940 
3941       // Create a stack object covering all stack doublewords occupied
3942       // by the argument.  If the argument is (fully or partially) on
3943       // the stack, or if the argument is fully in registers but the
3944       // caller has allocated the parameter save anyway, we can refer
3945       // directly to the caller's stack frame.  Otherwise, create a
3946       // local copy in our own frame.
3947       int FI;
3948       if (HasParameterArea ||
3949           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3950         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3951       else
3952         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3953       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3954 
3955       // Handle aggregates smaller than 8 bytes.
3956       if (ObjSize < PtrByteSize) {
3957         // The value of the object is its address, which differs from the
3958         // address of the enclosing doubleword on big-endian systems.
3959         SDValue Arg = FIN;
3960         if (!isLittleEndian) {
3961           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3962           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3963         }
3964         InVals.push_back(Arg);
3965 
3966         if (GPR_idx != Num_GPR_Regs) {
3967           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3968           FuncInfo->addLiveInAttr(VReg, Flags);
3969           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3970           SDValue Store;
3971 
3972           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3973             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3974                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3975             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3976                                       MachinePointerInfo(&*FuncArg), ObjType);
3977           } else {
3978             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3979             // store the whole register as-is to the parameter save area
3980             // slot.
3981             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3982                                  MachinePointerInfo(&*FuncArg));
3983           }
3984 
3985           MemOps.push_back(Store);
3986         }
3987         // Whether we copied from a register or not, advance the offset
3988         // into the parameter save area by a full doubleword.
3989         ArgOffset += PtrByteSize;
3990         continue;
3991       }
3992 
3993       // The value of the object is its address, which is the address of
3994       // its first stack doubleword.
3995       InVals.push_back(FIN);
3996 
3997       // Store whatever pieces of the object are in registers to memory.
3998       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3999         if (GPR_idx == Num_GPR_Regs)
4000           break;
4001 
4002         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4003         FuncInfo->addLiveInAttr(VReg, Flags);
4004         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4005         SDValue Addr = FIN;
4006         if (j) {
4007           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4008           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4009         }
4010         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4011                                      MachinePointerInfo(&*FuncArg, j));
4012         MemOps.push_back(Store);
4013         ++GPR_idx;
4014       }
4015       ArgOffset += ArgSize;
4016       continue;
4017     }
4018 
4019     switch (ObjectVT.getSimpleVT().SimpleTy) {
4020     default: llvm_unreachable("Unhandled argument type!");
4021     case MVT::i1:
4022     case MVT::i32:
4023     case MVT::i64:
4024       if (Flags.isNest()) {
4025         // The 'nest' parameter, if any, is passed in R11.
4026         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4027         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4028 
4029         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4030           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4031 
4032         break;
4033       }
4034 
4035       // These can be scalar arguments or elements of an integer array type
4036       // passed directly.  Clang may use those instead of "byval" aggregate
4037       // types to avoid forcing arguments to memory unnecessarily.
4038       if (GPR_idx != Num_GPR_Regs) {
4039         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4040         FuncInfo->addLiveInAttr(VReg, Flags);
4041         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4042 
4043         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4044           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4045           // value to MVT::i64 and then truncate to the correct register size.
4046           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4047       } else {
4048         if (CallConv == CallingConv::Fast)
4049           ComputeArgOffset();
4050 
4051         needsLoad = true;
4052         ArgSize = PtrByteSize;
4053       }
4054       if (CallConv != CallingConv::Fast || needsLoad)
4055         ArgOffset += 8;
4056       break;
4057 
4058     case MVT::f32:
4059     case MVT::f64:
4060       // These can be scalar arguments or elements of a float array type
4061       // passed directly.  The latter are used to implement ELFv2 homogenous
4062       // float aggregates.
4063       if (FPR_idx != Num_FPR_Regs) {
4064         unsigned VReg;
4065 
4066         if (ObjectVT == MVT::f32)
4067           VReg = MF.addLiveIn(FPR[FPR_idx],
4068                               Subtarget.hasP8Vector()
4069                                   ? &PPC::VSSRCRegClass
4070                                   : &PPC::F4RCRegClass);
4071         else
4072           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4073                                                 ? &PPC::VSFRCRegClass
4074                                                 : &PPC::F8RCRegClass);
4075 
4076         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4077         ++FPR_idx;
4078       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4079         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4080         // once we support fp <-> gpr moves.
4081 
4082         // This can only ever happen in the presence of f32 array types,
4083         // since otherwise we never run out of FPRs before running out
4084         // of GPRs.
4085         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4086         FuncInfo->addLiveInAttr(VReg, Flags);
4087         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4088 
4089         if (ObjectVT == MVT::f32) {
4090           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4091             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4092                                  DAG.getConstant(32, dl, MVT::i32));
4093           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4094         }
4095 
4096         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4097       } else {
4098         if (CallConv == CallingConv::Fast)
4099           ComputeArgOffset();
4100 
4101         needsLoad = true;
4102       }
4103 
4104       // When passing an array of floats, the array occupies consecutive
4105       // space in the argument area; only round up to the next doubleword
4106       // at the end of the array.  Otherwise, each float takes 8 bytes.
4107       if (CallConv != CallingConv::Fast || needsLoad) {
4108         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4109         ArgOffset += ArgSize;
4110         if (Flags.isInConsecutiveRegsLast())
4111           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4112       }
4113       break;
4114     case MVT::v4f32:
4115     case MVT::v4i32:
4116     case MVT::v8i16:
4117     case MVT::v16i8:
4118     case MVT::v2f64:
4119     case MVT::v2i64:
4120     case MVT::v1i128:
4121     case MVT::f128:
4122       if (!Subtarget.hasQPX()) {
4123         // These can be scalar arguments or elements of a vector array type
4124         // passed directly.  The latter are used to implement ELFv2 homogenous
4125         // vector aggregates.
4126         if (VR_idx != Num_VR_Regs) {
4127           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4128           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4129           ++VR_idx;
4130         } else {
4131           if (CallConv == CallingConv::Fast)
4132             ComputeArgOffset();
4133           needsLoad = true;
4134         }
4135         if (CallConv != CallingConv::Fast || needsLoad)
4136           ArgOffset += 16;
4137         break;
4138       } // not QPX
4139 
4140       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4141              "Invalid QPX parameter type");
4142       LLVM_FALLTHROUGH;
4143 
4144     case MVT::v4f64:
4145     case MVT::v4i1:
4146       // QPX vectors are treated like their scalar floating-point subregisters
4147       // (except that they're larger).
4148       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4149       if (QFPR_idx != Num_QFPR_Regs) {
4150         const TargetRegisterClass *RC;
4151         switch (ObjectVT.getSimpleVT().SimpleTy) {
4152         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4153         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4154         default:         RC = &PPC::QBRCRegClass; break;
4155         }
4156 
4157         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4158         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4159         ++QFPR_idx;
4160       } else {
4161         if (CallConv == CallingConv::Fast)
4162           ComputeArgOffset();
4163         needsLoad = true;
4164       }
4165       if (CallConv != CallingConv::Fast || needsLoad)
4166         ArgOffset += Sz;
4167       break;
4168     }
4169 
4170     // We need to load the argument to a virtual register if we determined
4171     // above that we ran out of physical registers of the appropriate type.
4172     if (needsLoad) {
4173       if (ObjSize < ArgSize && !isLittleEndian)
4174         CurArgOffset += ArgSize - ObjSize;
4175       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4176       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4177       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4178     }
4179 
4180     InVals.push_back(ArgVal);
4181   }
4182 
4183   // Area that is at least reserved in the caller of this function.
4184   unsigned MinReservedArea;
4185   if (HasParameterArea)
4186     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4187   else
4188     MinReservedArea = LinkageSize;
4189 
4190   // Set the size that is at least reserved in caller of this function.  Tail
4191   // call optimized functions' reserved stack space needs to be aligned so that
4192   // taking the difference between two stack areas will result in an aligned
4193   // stack.
4194   MinReservedArea =
4195       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4196   FuncInfo->setMinReservedArea(MinReservedArea);
4197 
4198   // If the function takes variable number of arguments, make a frame index for
4199   // the start of the first vararg value... for expansion of llvm.va_start.
4200   if (isVarArg) {
4201     int Depth = ArgOffset;
4202 
4203     FuncInfo->setVarArgsFrameIndex(
4204       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4205     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4206 
4207     // If this function is vararg, store any remaining integer argument regs
4208     // to their spots on the stack so that they may be loaded by dereferencing
4209     // the result of va_next.
4210     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4211          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4212       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4213       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4214       SDValue Store =
4215           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4216       MemOps.push_back(Store);
4217       // Increment the address by four for the next argument to store
4218       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4219       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4220     }
4221   }
4222 
4223   if (!MemOps.empty())
4224     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4225 
4226   return Chain;
4227 }
4228 
4229 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4230     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4231     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4232     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4233   // TODO: add description of PPC stack frame format, or at least some docs.
4234   //
4235   MachineFunction &MF = DAG.getMachineFunction();
4236   MachineFrameInfo &MFI = MF.getFrameInfo();
4237   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4238 
4239   EVT PtrVT = getPointerTy(MF.getDataLayout());
4240   bool isPPC64 = PtrVT == MVT::i64;
4241   // Potential tail calls could cause overwriting of argument stack slots.
4242   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4243                        (CallConv == CallingConv::Fast));
4244   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4245   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4246   unsigned ArgOffset = LinkageSize;
4247   // Area that is at least reserved in caller of this function.
4248   unsigned MinReservedArea = ArgOffset;
4249 
4250   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4251     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4252     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4253   };
4254   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4255     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4256     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4257   };
4258   static const MCPhysReg VR[] = {
4259     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4260     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4261   };
4262 
4263   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4264   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4265   const unsigned Num_VR_Regs  = array_lengthof( VR);
4266 
4267   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4268 
4269   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4270 
4271   // In 32-bit non-varargs functions, the stack space for vectors is after the
4272   // stack space for non-vectors.  We do not use this space unless we have
4273   // too many vectors to fit in registers, something that only occurs in
4274   // constructed examples:), but we have to walk the arglist to figure
4275   // that out...for the pathological case, compute VecArgOffset as the
4276   // start of the vector parameter area.  Computing VecArgOffset is the
4277   // entire point of the following loop.
4278   unsigned VecArgOffset = ArgOffset;
4279   if (!isVarArg && !isPPC64) {
4280     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4281          ++ArgNo) {
4282       EVT ObjectVT = Ins[ArgNo].VT;
4283       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4284 
4285       if (Flags.isByVal()) {
4286         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4287         unsigned ObjSize = Flags.getByValSize();
4288         unsigned ArgSize =
4289                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4290         VecArgOffset += ArgSize;
4291         continue;
4292       }
4293 
4294       switch(ObjectVT.getSimpleVT().SimpleTy) {
4295       default: llvm_unreachable("Unhandled argument type!");
4296       case MVT::i1:
4297       case MVT::i32:
4298       case MVT::f32:
4299         VecArgOffset += 4;
4300         break;
4301       case MVT::i64:  // PPC64
4302       case MVT::f64:
4303         // FIXME: We are guaranteed to be !isPPC64 at this point.
4304         // Does MVT::i64 apply?
4305         VecArgOffset += 8;
4306         break;
4307       case MVT::v4f32:
4308       case MVT::v4i32:
4309       case MVT::v8i16:
4310       case MVT::v16i8:
4311         // Nothing to do, we're only looking at Nonvector args here.
4312         break;
4313       }
4314     }
4315   }
4316   // We've found where the vector parameter area in memory is.  Skip the
4317   // first 12 parameters; these don't use that memory.
4318   VecArgOffset = ((VecArgOffset+15)/16)*16;
4319   VecArgOffset += 12*16;
4320 
4321   // Add DAG nodes to load the arguments or copy them out of registers.  On
4322   // entry to a function on PPC, the arguments start after the linkage area,
4323   // although the first ones are often in registers.
4324 
4325   SmallVector<SDValue, 8> MemOps;
4326   unsigned nAltivecParamsAtEnd = 0;
4327   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4328   unsigned CurArgIdx = 0;
4329   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4330     SDValue ArgVal;
4331     bool needsLoad = false;
4332     EVT ObjectVT = Ins[ArgNo].VT;
4333     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4334     unsigned ArgSize = ObjSize;
4335     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4336     if (Ins[ArgNo].isOrigArg()) {
4337       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4338       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4339     }
4340     unsigned CurArgOffset = ArgOffset;
4341 
4342     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4343     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4344         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4345       if (isVarArg || isPPC64) {
4346         MinReservedArea = ((MinReservedArea+15)/16)*16;
4347         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4348                                                   Flags,
4349                                                   PtrByteSize);
4350       } else  nAltivecParamsAtEnd++;
4351     } else
4352       // Calculate min reserved area.
4353       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4354                                                 Flags,
4355                                                 PtrByteSize);
4356 
4357     // FIXME the codegen can be much improved in some cases.
4358     // We do not have to keep everything in memory.
4359     if (Flags.isByVal()) {
4360       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4361 
4362       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4363       ObjSize = Flags.getByValSize();
4364       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4365       // Objects of size 1 and 2 are right justified, everything else is
4366       // left justified.  This means the memory address is adjusted forwards.
4367       if (ObjSize==1 || ObjSize==2) {
4368         CurArgOffset = CurArgOffset + (4 - ObjSize);
4369       }
4370       // The value of the object is its address.
4371       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4372       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4373       InVals.push_back(FIN);
4374       if (ObjSize==1 || ObjSize==2) {
4375         if (GPR_idx != Num_GPR_Regs) {
4376           unsigned VReg;
4377           if (isPPC64)
4378             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4379           else
4380             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4381           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4382           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4383           SDValue Store =
4384               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4385                                 MachinePointerInfo(&*FuncArg), ObjType);
4386           MemOps.push_back(Store);
4387           ++GPR_idx;
4388         }
4389 
4390         ArgOffset += PtrByteSize;
4391 
4392         continue;
4393       }
4394       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4395         // Store whatever pieces of the object are in registers
4396         // to memory.  ArgOffset will be the address of the beginning
4397         // of the object.
4398         if (GPR_idx != Num_GPR_Regs) {
4399           unsigned VReg;
4400           if (isPPC64)
4401             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4402           else
4403             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4404           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4405           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4406           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4407           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4408                                        MachinePointerInfo(&*FuncArg, j));
4409           MemOps.push_back(Store);
4410           ++GPR_idx;
4411           ArgOffset += PtrByteSize;
4412         } else {
4413           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4414           break;
4415         }
4416       }
4417       continue;
4418     }
4419 
4420     switch (ObjectVT.getSimpleVT().SimpleTy) {
4421     default: llvm_unreachable("Unhandled argument type!");
4422     case MVT::i1:
4423     case MVT::i32:
4424       if (!isPPC64) {
4425         if (GPR_idx != Num_GPR_Regs) {
4426           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4427           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4428 
4429           if (ObjectVT == MVT::i1)
4430             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
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 += PtrByteSize;
4439         break;
4440       }
4441       LLVM_FALLTHROUGH;
4442     case MVT::i64:  // PPC64
4443       if (GPR_idx != Num_GPR_Regs) {
4444         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4445         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4446 
4447         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4448           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4449           // value to MVT::i64 and then truncate to the correct register size.
4450           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4451 
4452         ++GPR_idx;
4453       } else {
4454         needsLoad = true;
4455         ArgSize = PtrByteSize;
4456       }
4457       // All int arguments reserve stack space in the Darwin ABI.
4458       ArgOffset += 8;
4459       break;
4460 
4461     case MVT::f32:
4462     case MVT::f64:
4463       // Every 4 bytes of argument space consumes one of the GPRs available for
4464       // argument passing.
4465       if (GPR_idx != Num_GPR_Regs) {
4466         ++GPR_idx;
4467         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4468           ++GPR_idx;
4469       }
4470       if (FPR_idx != Num_FPR_Regs) {
4471         unsigned VReg;
4472 
4473         if (ObjectVT == MVT::f32)
4474           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4475         else
4476           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4477 
4478         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4479         ++FPR_idx;
4480       } else {
4481         needsLoad = true;
4482       }
4483 
4484       // All FP arguments reserve stack space in the Darwin ABI.
4485       ArgOffset += isPPC64 ? 8 : ObjSize;
4486       break;
4487     case MVT::v4f32:
4488     case MVT::v4i32:
4489     case MVT::v8i16:
4490     case MVT::v16i8:
4491       // Note that vector arguments in registers don't reserve stack space,
4492       // except in varargs functions.
4493       if (VR_idx != Num_VR_Regs) {
4494         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4495         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4496         if (isVarArg) {
4497           while ((ArgOffset % 16) != 0) {
4498             ArgOffset += PtrByteSize;
4499             if (GPR_idx != Num_GPR_Regs)
4500               GPR_idx++;
4501           }
4502           ArgOffset += 16;
4503           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4504         }
4505         ++VR_idx;
4506       } else {
4507         if (!isVarArg && !isPPC64) {
4508           // Vectors go after all the nonvectors.
4509           CurArgOffset = VecArgOffset;
4510           VecArgOffset += 16;
4511         } else {
4512           // Vectors are aligned.
4513           ArgOffset = ((ArgOffset+15)/16)*16;
4514           CurArgOffset = ArgOffset;
4515           ArgOffset += 16;
4516         }
4517         needsLoad = true;
4518       }
4519       break;
4520     }
4521 
4522     // We need to load the argument to a virtual register if we determined above
4523     // that we ran out of physical registers of the appropriate type.
4524     if (needsLoad) {
4525       int FI = MFI.CreateFixedObject(ObjSize,
4526                                      CurArgOffset + (ArgSize - ObjSize),
4527                                      isImmutable);
4528       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4529       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4530     }
4531 
4532     InVals.push_back(ArgVal);
4533   }
4534 
4535   // Allow for Altivec parameters at the end, if needed.
4536   if (nAltivecParamsAtEnd) {
4537     MinReservedArea = ((MinReservedArea+15)/16)*16;
4538     MinReservedArea += 16*nAltivecParamsAtEnd;
4539   }
4540 
4541   // Area that is at least reserved in the caller of this function.
4542   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4543 
4544   // Set the size that is at least reserved in caller of this function.  Tail
4545   // call optimized functions' reserved stack space needs to be aligned so that
4546   // taking the difference between two stack areas will result in an aligned
4547   // stack.
4548   MinReservedArea =
4549       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4550   FuncInfo->setMinReservedArea(MinReservedArea);
4551 
4552   // If the function takes variable number of arguments, make a frame index for
4553   // the start of the first vararg value... for expansion of llvm.va_start.
4554   if (isVarArg) {
4555     int Depth = ArgOffset;
4556 
4557     FuncInfo->setVarArgsFrameIndex(
4558       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4559                             Depth, true));
4560     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4561 
4562     // If this function is vararg, store any remaining integer argument regs
4563     // to their spots on the stack so that they may be loaded by dereferencing
4564     // the result of va_next.
4565     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4566       unsigned VReg;
4567 
4568       if (isPPC64)
4569         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4570       else
4571         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4572 
4573       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4574       SDValue Store =
4575           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4576       MemOps.push_back(Store);
4577       // Increment the address by four for the next argument to store
4578       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4579       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4580     }
4581   }
4582 
4583   if (!MemOps.empty())
4584     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4585 
4586   return Chain;
4587 }
4588 
4589 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4590 /// adjusted to accommodate the arguments for the tailcall.
4591 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4592                                    unsigned ParamSize) {
4593 
4594   if (!isTailCall) return 0;
4595 
4596   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4597   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4598   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4599   // Remember only if the new adjustment is bigger.
4600   if (SPDiff < FI->getTailCallSPDelta())
4601     FI->setTailCallSPDelta(SPDiff);
4602 
4603   return SPDiff;
4604 }
4605 
4606 static bool isFunctionGlobalAddress(SDValue Callee);
4607 
4608 static bool
4609 callsShareTOCBase(const Function *Caller, SDValue Callee,
4610                     const TargetMachine &TM) {
4611    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4612    // don't have enough information to determine if the caller and calle share
4613    // the same  TOC base, so we have to pessimistically assume they don't for
4614    // correctness.
4615    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4616    if (!G)
4617      return false;
4618 
4619    const GlobalValue *GV = G->getGlobal();
4620   // The medium and large code models are expected to provide a sufficiently
4621   // large TOC to provide all data addressing needs of a module with a
4622   // single TOC. Since each module will be addressed with a single TOC then we
4623   // only need to check that caller and callee don't cross dso boundaries.
4624   if (CodeModel::Medium == TM.getCodeModel() ||
4625       CodeModel::Large == TM.getCodeModel())
4626     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4627 
4628   // Otherwise we need to ensure callee and caller are in the same section,
4629   // since the linker may allocate multiple TOCs, and we don't know which
4630   // sections will belong to the same TOC base.
4631 
4632   if (!GV->isStrongDefinitionForLinker())
4633     return false;
4634 
4635   // Any explicitly-specified sections and section prefixes must also match.
4636   // Also, if we're using -ffunction-sections, then each function is always in
4637   // a different section (the same is true for COMDAT functions).
4638   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4639       GV->getSection() != Caller->getSection())
4640     return false;
4641   if (const auto *F = dyn_cast<Function>(GV)) {
4642     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4643       return false;
4644   }
4645 
4646   // If the callee might be interposed, then we can't assume the ultimate call
4647   // target will be in the same section. Even in cases where we can assume that
4648   // interposition won't happen, in any case where the linker might insert a
4649   // stub to allow for interposition, we must generate code as though
4650   // interposition might occur. To understand why this matters, consider a
4651   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4652   // in the same section, but a is in a different module (i.e. has a different
4653   // TOC base pointer). If the linker allows for interposition between b and c,
4654   // then it will generate a stub for the call edge between b and c which will
4655   // save the TOC pointer into the designated stack slot allocated by b. If we
4656   // return true here, and therefore allow a tail call between b and c, that
4657   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4658   // pointer into the stack slot allocated by a (where the a -> b stub saved
4659   // a's TOC base pointer). If we're not considering a tail call, but rather,
4660   // whether a nop is needed after the call instruction in b, because the linker
4661   // will insert a stub, it might complain about a missing nop if we omit it
4662   // (although many don't complain in this case).
4663   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4664     return false;
4665 
4666   return true;
4667 }
4668 
4669 static bool
4670 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4671                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4672   assert(Subtarget.is64BitELFABI());
4673 
4674   const unsigned PtrByteSize = 8;
4675   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4676 
4677   static const MCPhysReg GPR[] = {
4678     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4679     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4680   };
4681   static const MCPhysReg VR[] = {
4682     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4683     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4684   };
4685 
4686   const unsigned NumGPRs = array_lengthof(GPR);
4687   const unsigned NumFPRs = 13;
4688   const unsigned NumVRs = array_lengthof(VR);
4689   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4690 
4691   unsigned NumBytes = LinkageSize;
4692   unsigned AvailableFPRs = NumFPRs;
4693   unsigned AvailableVRs = NumVRs;
4694 
4695   for (const ISD::OutputArg& Param : Outs) {
4696     if (Param.Flags.isNest()) continue;
4697 
4698     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4699                                PtrByteSize, LinkageSize, ParamAreaSize,
4700                                NumBytes, AvailableFPRs, AvailableVRs,
4701                                Subtarget.hasQPX()))
4702       return true;
4703   }
4704   return false;
4705 }
4706 
4707 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4708   if (CB.arg_size() != CallerFn->arg_size())
4709     return false;
4710 
4711   auto CalleeArgIter = CB.arg_begin();
4712   auto CalleeArgEnd = CB.arg_end();
4713   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4714 
4715   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4716     const Value* CalleeArg = *CalleeArgIter;
4717     const Value* CallerArg = &(*CallerArgIter);
4718     if (CalleeArg == CallerArg)
4719       continue;
4720 
4721     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4722     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4723     //      }
4724     // 1st argument of callee is undef and has the same type as caller.
4725     if (CalleeArg->getType() == CallerArg->getType() &&
4726         isa<UndefValue>(CalleeArg))
4727       continue;
4728 
4729     return false;
4730   }
4731 
4732   return true;
4733 }
4734 
4735 // Returns true if TCO is possible between the callers and callees
4736 // calling conventions.
4737 static bool
4738 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4739                                     CallingConv::ID CalleeCC) {
4740   // Tail calls are possible with fastcc and ccc.
4741   auto isTailCallableCC  = [] (CallingConv::ID CC){
4742       return  CC == CallingConv::C || CC == CallingConv::Fast;
4743   };
4744   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4745     return false;
4746 
4747   // We can safely tail call both fastcc and ccc callees from a c calling
4748   // convention caller. If the caller is fastcc, we may have less stack space
4749   // than a non-fastcc caller with the same signature so disable tail-calls in
4750   // that case.
4751   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4752 }
4753 
4754 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4755     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4756     const SmallVectorImpl<ISD::OutputArg> &Outs,
4757     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4758   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4759 
4760   // FIXME: Tail calls are currently disabled when using PC Relative addressing.
4761   // The issue is that PC Relative is only partially implemented and so there
4762   // is currently a mix of functions that require the TOC and functions that do
4763   // not require it. If we have A calls B calls C and both A and B require the
4764   // TOC and C does not and is marked as clobbering R2 then it is not safe for
4765   // B to tail call C. Since we do not have the information of whether or not
4766   // a funciton needs to use the TOC here in this function we need to be
4767   // conservatively safe and disable all tail calls for now.
4768   if (Subtarget.isUsingPCRelativeCalls()) return false;
4769 
4770   if (DisableSCO && !TailCallOpt) return false;
4771 
4772   // Variadic argument functions are not supported.
4773   if (isVarArg) return false;
4774 
4775   auto &Caller = DAG.getMachineFunction().getFunction();
4776   // Check that the calling conventions are compatible for tco.
4777   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4778     return false;
4779 
4780   // Caller contains any byval parameter is not supported.
4781   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4782     return false;
4783 
4784   // Callee contains any byval parameter is not supported, too.
4785   // Note: This is a quick work around, because in some cases, e.g.
4786   // caller's stack size > callee's stack size, we are still able to apply
4787   // sibling call optimization. For example, gcc is able to do SCO for caller1
4788   // in the following example, but not for caller2.
4789   //   struct test {
4790   //     long int a;
4791   //     char ary[56];
4792   //   } gTest;
4793   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4794   //     b->a = v.a;
4795   //     return 0;
4796   //   }
4797   //   void caller1(struct test a, struct test c, struct test *b) {
4798   //     callee(gTest, b); }
4799   //   void caller2(struct test *b) { callee(gTest, b); }
4800   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4801     return false;
4802 
4803   // If callee and caller use different calling conventions, we cannot pass
4804   // parameters on stack since offsets for the parameter area may be different.
4805   if (Caller.getCallingConv() != CalleeCC &&
4806       needStackSlotPassParameters(Subtarget, Outs))
4807     return false;
4808 
4809   // No TCO/SCO on indirect call because Caller have to restore its TOC
4810   if (!isFunctionGlobalAddress(Callee) &&
4811       !isa<ExternalSymbolSDNode>(Callee))
4812     return false;
4813 
4814   // If the caller and callee potentially have different TOC bases then we
4815   // cannot tail call since we need to restore the TOC pointer after the call.
4816   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4817   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4818     return false;
4819 
4820   // TCO allows altering callee ABI, so we don't have to check further.
4821   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4822     return true;
4823 
4824   if (DisableSCO) return false;
4825 
4826   // If callee use the same argument list that caller is using, then we can
4827   // apply SCO on this case. If it is not, then we need to check if callee needs
4828   // stack for passing arguments.
4829   assert(CB && "Expected to have a CallBase!");
4830   if (!hasSameArgumentList(&Caller, *CB) &&
4831       needStackSlotPassParameters(Subtarget, Outs)) {
4832     return false;
4833   }
4834 
4835   return true;
4836 }
4837 
4838 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4839 /// for tail call optimization. Targets which want to do tail call
4840 /// optimization should implement this function.
4841 bool
4842 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4843                                                      CallingConv::ID CalleeCC,
4844                                                      bool isVarArg,
4845                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4846                                                      SelectionDAG& DAG) const {
4847   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4848     return false;
4849 
4850   // Variable argument functions are not supported.
4851   if (isVarArg)
4852     return false;
4853 
4854   MachineFunction &MF = DAG.getMachineFunction();
4855   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4856   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4857     // Functions containing by val parameters are not supported.
4858     for (unsigned i = 0; i != Ins.size(); i++) {
4859        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4860        if (Flags.isByVal()) return false;
4861     }
4862 
4863     // Non-PIC/GOT tail calls are supported.
4864     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4865       return true;
4866 
4867     // At the moment we can only do local tail calls (in same module, hidden
4868     // or protected) if we are generating PIC.
4869     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4870       return G->getGlobal()->hasHiddenVisibility()
4871           || G->getGlobal()->hasProtectedVisibility();
4872   }
4873 
4874   return false;
4875 }
4876 
4877 /// isCallCompatibleAddress - Return the immediate to use if the specified
4878 /// 32-bit value is representable in the immediate field of a BxA instruction.
4879 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4880   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4881   if (!C) return nullptr;
4882 
4883   int Addr = C->getZExtValue();
4884   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4885       SignExtend32<26>(Addr) != Addr)
4886     return nullptr;  // Top 6 bits have to be sext of immediate.
4887 
4888   return DAG
4889       .getConstant(
4890           (int)C->getZExtValue() >> 2, SDLoc(Op),
4891           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4892       .getNode();
4893 }
4894 
4895 namespace {
4896 
4897 struct TailCallArgumentInfo {
4898   SDValue Arg;
4899   SDValue FrameIdxOp;
4900   int FrameIdx = 0;
4901 
4902   TailCallArgumentInfo() = default;
4903 };
4904 
4905 } // end anonymous namespace
4906 
4907 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4908 static void StoreTailCallArgumentsToStackSlot(
4909     SelectionDAG &DAG, SDValue Chain,
4910     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4911     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4912   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4913     SDValue Arg = TailCallArgs[i].Arg;
4914     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4915     int FI = TailCallArgs[i].FrameIdx;
4916     // Store relative to framepointer.
4917     MemOpChains.push_back(DAG.getStore(
4918         Chain, dl, Arg, FIN,
4919         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4920   }
4921 }
4922 
4923 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4924 /// the appropriate stack slot for the tail call optimized function call.
4925 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4926                                              SDValue OldRetAddr, SDValue OldFP,
4927                                              int SPDiff, const SDLoc &dl) {
4928   if (SPDiff) {
4929     // Calculate the new stack slot for the return address.
4930     MachineFunction &MF = DAG.getMachineFunction();
4931     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4932     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4933     bool isPPC64 = Subtarget.isPPC64();
4934     int SlotSize = isPPC64 ? 8 : 4;
4935     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4936     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4937                                                          NewRetAddrLoc, true);
4938     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4939     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4940     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4941                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4942   }
4943   return Chain;
4944 }
4945 
4946 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4947 /// the position of the argument.
4948 static void
4949 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4950                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4951                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4952   int Offset = ArgOffset + SPDiff;
4953   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4954   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4955   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4956   SDValue FIN = DAG.getFrameIndex(FI, VT);
4957   TailCallArgumentInfo Info;
4958   Info.Arg = Arg;
4959   Info.FrameIdxOp = FIN;
4960   Info.FrameIdx = FI;
4961   TailCallArguments.push_back(Info);
4962 }
4963 
4964 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4965 /// stack slot. Returns the chain as result and the loaded frame pointers in
4966 /// LROpOut/FPOpout. Used when tail calling.
4967 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4968     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4969     SDValue &FPOpOut, const SDLoc &dl) const {
4970   if (SPDiff) {
4971     // Load the LR and FP stack slot for later adjusting.
4972     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4973     LROpOut = getReturnAddrFrameIndex(DAG);
4974     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4975     Chain = SDValue(LROpOut.getNode(), 1);
4976   }
4977   return Chain;
4978 }
4979 
4980 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4981 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4982 /// specified by the specific parameter attribute. The copy will be passed as
4983 /// a byval function parameter.
4984 /// Sometimes what we are copying is the end of a larger object, the part that
4985 /// does not fit in registers.
4986 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4987                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4988                                          SelectionDAG &DAG, const SDLoc &dl) {
4989   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4990   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4991                        Flags.getNonZeroByValAlign(), false, false, false,
4992                        MachinePointerInfo(), MachinePointerInfo());
4993 }
4994 
4995 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4996 /// tail calls.
4997 static void LowerMemOpCallTo(
4998     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4999     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5000     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5001     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5002   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5003   if (!isTailCall) {
5004     if (isVector) {
5005       SDValue StackPtr;
5006       if (isPPC64)
5007         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5008       else
5009         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5010       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5011                            DAG.getConstant(ArgOffset, dl, PtrVT));
5012     }
5013     MemOpChains.push_back(
5014         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5015     // Calculate and remember argument location.
5016   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5017                                   TailCallArguments);
5018 }
5019 
5020 static void
5021 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5022                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5023                 SDValue FPOp,
5024                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5025   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5026   // might overwrite each other in case of tail call optimization.
5027   SmallVector<SDValue, 8> MemOpChains2;
5028   // Do not flag preceding copytoreg stuff together with the following stuff.
5029   InFlag = SDValue();
5030   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5031                                     MemOpChains2, dl);
5032   if (!MemOpChains2.empty())
5033     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5034 
5035   // Store the return address to the appropriate stack slot.
5036   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5037 
5038   // Emit callseq_end just before tailcall node.
5039   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5040                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5041   InFlag = Chain.getValue(1);
5042 }
5043 
5044 // Is this global address that of a function that can be called by name? (as
5045 // opposed to something that must hold a descriptor for an indirect call).
5046 static bool isFunctionGlobalAddress(SDValue Callee) {
5047   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5048     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5049         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5050       return false;
5051 
5052     return G->getGlobal()->getValueType()->isFunctionTy();
5053   }
5054 
5055   return false;
5056 }
5057 
5058 SDValue PPCTargetLowering::LowerCallResult(
5059     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5060     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5061     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5062   SmallVector<CCValAssign, 16> RVLocs;
5063   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5064                     *DAG.getContext());
5065 
5066   CCRetInfo.AnalyzeCallResult(
5067       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5068                ? RetCC_PPC_Cold
5069                : RetCC_PPC);
5070 
5071   // Copy all of the result registers out of their specified physreg.
5072   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5073     CCValAssign &VA = RVLocs[i];
5074     assert(VA.isRegLoc() && "Can only return in registers!");
5075 
5076     SDValue Val;
5077 
5078     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5079       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5080                                       InFlag);
5081       Chain = Lo.getValue(1);
5082       InFlag = Lo.getValue(2);
5083       VA = RVLocs[++i]; // skip ahead to next loc
5084       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5085                                       InFlag);
5086       Chain = Hi.getValue(1);
5087       InFlag = Hi.getValue(2);
5088       if (!Subtarget.isLittleEndian())
5089         std::swap (Lo, Hi);
5090       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5091     } else {
5092       Val = DAG.getCopyFromReg(Chain, dl,
5093                                VA.getLocReg(), VA.getLocVT(), InFlag);
5094       Chain = Val.getValue(1);
5095       InFlag = Val.getValue(2);
5096     }
5097 
5098     switch (VA.getLocInfo()) {
5099     default: llvm_unreachable("Unknown loc info!");
5100     case CCValAssign::Full: break;
5101     case CCValAssign::AExt:
5102       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5103       break;
5104     case CCValAssign::ZExt:
5105       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5106                         DAG.getValueType(VA.getValVT()));
5107       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5108       break;
5109     case CCValAssign::SExt:
5110       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5111                         DAG.getValueType(VA.getValVT()));
5112       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5113       break;
5114     }
5115 
5116     InVals.push_back(Val);
5117   }
5118 
5119   return Chain;
5120 }
5121 
5122 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5123                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5124   // PatchPoint calls are not indirect.
5125   if (isPatchPoint)
5126     return false;
5127 
5128   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5129     return false;
5130 
5131   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5132   // becuase the immediate function pointer points to a descriptor instead of
5133   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5134   // pointer immediate points to the global entry point, while the BLA would
5135   // need to jump to the local entry point (see rL211174).
5136   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5137       isBLACompatibleAddress(Callee, DAG))
5138     return false;
5139 
5140   return true;
5141 }
5142 
5143 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5144                               const Function &Caller,
5145                               const SDValue &Callee,
5146                               const PPCSubtarget &Subtarget,
5147                               const TargetMachine &TM) {
5148   if (CFlags.IsTailCall)
5149     return PPCISD::TC_RETURN;
5150 
5151   // This is a call through a function pointer.
5152   if (CFlags.IsIndirect) {
5153     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5154     // indirect calls. The save of the caller's TOC pointer to the stack will be
5155     // inserted into the DAG as part of call lowering. The restore of the TOC
5156     // pointer is modeled by using a pseudo instruction for the call opcode that
5157     // represents the 2 instruction sequence of an indirect branch and link,
5158     // immediately followed by a load of the TOC pointer from the the stack save
5159     // slot into gpr2.
5160     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5161       return PPCISD::BCTRL_LOAD_TOC;
5162 
5163     // An indirect call that does not need a TOC restore.
5164     return PPCISD::BCTRL;
5165   }
5166 
5167   // FIXME: At this moment indirect calls are treated ahead of the
5168   // PC Relative condition because binaries can still contain a possible
5169   // mix of functions that use a TOC and functions that do not use a TOC.
5170   // Once the PC Relative feature is complete this condition should be moved
5171   // up ahead of the indirect calls and should return a PPCISD::BCTRL for
5172   // that case.
5173   if (Subtarget.isUsingPCRelativeCalls()) {
5174     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5175     return PPCISD::CALL_NOTOC;
5176   }
5177 
5178   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5179   // immediately following the call instruction if the caller and callee may
5180   // have different TOC bases. At link time if the linker determines the calls
5181   // may not share a TOC base, the call is redirected to a trampoline inserted
5182   // by the linker. The trampoline will (among other things) save the callers
5183   // TOC pointer at an ABI designated offset in the linkage area and the linker
5184   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5185   // into gpr2.
5186   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5187       return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5188                                                     : PPCISD::CALL_NOP;
5189 
5190   return PPCISD::CALL;
5191 }
5192 
5193 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5194                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5195   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5196     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5197       return SDValue(Dest, 0);
5198 
5199   // Returns true if the callee is local, and false otherwise.
5200   auto isLocalCallee = [&]() {
5201     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5202     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5203     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5204 
5205     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5206            !dyn_cast_or_null<GlobalIFunc>(GV);
5207   };
5208 
5209   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5210   // a static relocation model causes some versions of GNU LD (2.17.50, at
5211   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5212   // built with secure-PLT.
5213   bool UsePlt =
5214       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5215       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5216 
5217   // On AIX, direct function calls reference the symbol for the function's
5218   // entry point, which is named by prepending a "." before the function's
5219   // C-linkage name.
5220   const auto getAIXFuncEntryPointSymbolSDNode =
5221       [&](StringRef FuncName, bool IsDeclaration,
5222           const XCOFF::StorageClass &SC) {
5223         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5224 
5225         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5226             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5227 
5228         if (IsDeclaration && !S->hasRepresentedCsectSet()) {
5229           // On AIX, an undefined symbol needs to be associated with a
5230           // MCSectionXCOFF to get the correct storage mapping class.
5231           // In this case, XCOFF::XMC_PR.
5232           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5233               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5234               SectionKind::getMetadata());
5235           S->setRepresentedCsect(Sec);
5236         }
5237 
5238         MVT PtrVT =
5239             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5240         return DAG.getMCSymbol(S, PtrVT);
5241       };
5242 
5243   if (isFunctionGlobalAddress(Callee)) {
5244     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5245     const GlobalValue *GV = G->getGlobal();
5246 
5247     if (!Subtarget.isAIXABI())
5248       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5249                                         UsePlt ? PPCII::MO_PLT : 0);
5250 
5251     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5252     const GlobalObject *GO = cast<GlobalObject>(GV);
5253     const XCOFF::StorageClass SC =
5254         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5255     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5256                                             SC);
5257   }
5258 
5259   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5260     const char *SymName = S->getSymbol();
5261     if (!Subtarget.isAIXABI())
5262       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5263                                          UsePlt ? PPCII::MO_PLT : 0);
5264 
5265     // If there exists a user-declared function whose name is the same as the
5266     // ExternalSymbol's, then we pick up the user-declared version.
5267     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5268     if (const Function *F =
5269             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5270       const XCOFF::StorageClass SC =
5271           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5272       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5273                                               SC);
5274     }
5275 
5276     return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5277   }
5278 
5279   // No transformation needed.
5280   assert(Callee.getNode() && "What no callee?");
5281   return Callee;
5282 }
5283 
5284 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5285   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5286          "Expected a CALLSEQ_STARTSDNode.");
5287 
5288   // The last operand is the chain, except when the node has glue. If the node
5289   // has glue, then the last operand is the glue, and the chain is the second
5290   // last operand.
5291   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5292   if (LastValue.getValueType() != MVT::Glue)
5293     return LastValue;
5294 
5295   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5296 }
5297 
5298 // Creates the node that moves a functions address into the count register
5299 // to prepare for an indirect call instruction.
5300 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5301                                 SDValue &Glue, SDValue &Chain,
5302                                 const SDLoc &dl) {
5303   SDValue MTCTROps[] = {Chain, Callee, Glue};
5304   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5305   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5306                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5307   // The glue is the second value produced.
5308   Glue = Chain.getValue(1);
5309 }
5310 
5311 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5312                                           SDValue &Glue, SDValue &Chain,
5313                                           SDValue CallSeqStart,
5314                                           const CallBase *CB, const SDLoc &dl,
5315                                           bool hasNest,
5316                                           const PPCSubtarget &Subtarget) {
5317   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5318   // entry point, but to the function descriptor (the function entry point
5319   // address is part of the function descriptor though).
5320   // The function descriptor is a three doubleword structure with the
5321   // following fields: function entry point, TOC base address and
5322   // environment pointer.
5323   // Thus for a call through a function pointer, the following actions need
5324   // to be performed:
5325   //   1. Save the TOC of the caller in the TOC save area of its stack
5326   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5327   //   2. Load the address of the function entry point from the function
5328   //      descriptor.
5329   //   3. Load the TOC of the callee from the function descriptor into r2.
5330   //   4. Load the environment pointer from the function descriptor into
5331   //      r11.
5332   //   5. Branch to the function entry point address.
5333   //   6. On return of the callee, the TOC of the caller needs to be
5334   //      restored (this is done in FinishCall()).
5335   //
5336   // The loads are scheduled at the beginning of the call sequence, and the
5337   // register copies are flagged together to ensure that no other
5338   // operations can be scheduled in between. E.g. without flagging the
5339   // copies together, a TOC access in the caller could be scheduled between
5340   // the assignment of the callee TOC and the branch to the callee, which leads
5341   // to incorrect code.
5342 
5343   // Start by loading the function address from the descriptor.
5344   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5345   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5346                       ? (MachineMemOperand::MODereferenceable |
5347                          MachineMemOperand::MOInvariant)
5348                       : MachineMemOperand::MONone;
5349 
5350   MachinePointerInfo MPI(CB ? CB->getCalledValue() : nullptr);
5351 
5352   // Registers used in building the DAG.
5353   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5354   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5355 
5356   // Offsets of descriptor members.
5357   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5358   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5359 
5360   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5361   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5362 
5363   // One load for the functions entry point address.
5364   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5365                                     Alignment, MMOFlags);
5366 
5367   // One for loading the TOC anchor for the module that contains the called
5368   // function.
5369   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5370   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5371   SDValue TOCPtr =
5372       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5373                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5374 
5375   // One for loading the environment pointer.
5376   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5377   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5378   SDValue LoadEnvPtr =
5379       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5380                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5381 
5382 
5383   // Then copy the newly loaded TOC anchor to the TOC pointer.
5384   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5385   Chain = TOCVal.getValue(0);
5386   Glue = TOCVal.getValue(1);
5387 
5388   // If the function call has an explicit 'nest' parameter, it takes the
5389   // place of the environment pointer.
5390   assert((!hasNest || !Subtarget.isAIXABI()) &&
5391          "Nest parameter is not supported on AIX.");
5392   if (!hasNest) {
5393     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5394     Chain = EnvVal.getValue(0);
5395     Glue = EnvVal.getValue(1);
5396   }
5397 
5398   // The rest of the indirect call sequence is the same as the non-descriptor
5399   // DAG.
5400   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5401 }
5402 
5403 static void
5404 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5405                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5406                   SelectionDAG &DAG,
5407                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5408                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5409                   const PPCSubtarget &Subtarget) {
5410   const bool IsPPC64 = Subtarget.isPPC64();
5411   // MVT for a general purpose register.
5412   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5413 
5414   // First operand is always the chain.
5415   Ops.push_back(Chain);
5416 
5417   // If it's a direct call pass the callee as the second operand.
5418   if (!CFlags.IsIndirect)
5419     Ops.push_back(Callee);
5420   else {
5421     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5422 
5423     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5424     // on the stack (this would have been done in `LowerCall_64SVR4` or
5425     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5426     // represents both the indirect branch and a load that restores the TOC
5427     // pointer from the linkage area. The operand for the TOC restore is an add
5428     // of the TOC save offset to the stack pointer. This must be the second
5429     // operand: after the chain input but before any other variadic arguments.
5430     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5431       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5432 
5433       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5434       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5435       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5436       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5437       Ops.push_back(AddTOC);
5438     }
5439 
5440     // Add the register used for the environment pointer.
5441     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5442       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5443                                     RegVT));
5444 
5445 
5446     // Add CTR register as callee so a bctr can be emitted later.
5447     if (CFlags.IsTailCall)
5448       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5449   }
5450 
5451   // If this is a tail call add stack pointer delta.
5452   if (CFlags.IsTailCall)
5453     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5454 
5455   // Add argument registers to the end of the list so that they are known live
5456   // into the call.
5457   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5458     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5459                                   RegsToPass[i].second.getValueType()));
5460 
5461   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5462   // no way to mark dependencies as implicit here.
5463   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5464   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5465        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5466     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5467 
5468   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5469   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5470     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5471 
5472   // Add a register mask operand representing the call-preserved registers.
5473   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5474   const uint32_t *Mask =
5475       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5476   assert(Mask && "Missing call preserved mask for calling convention");
5477   Ops.push_back(DAG.getRegisterMask(Mask));
5478 
5479   // If the glue is valid, it is the last operand.
5480   if (Glue.getNode())
5481     Ops.push_back(Glue);
5482 }
5483 
5484 SDValue PPCTargetLowering::FinishCall(
5485     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5486     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5487     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5488     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5489     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5490 
5491   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5492       Subtarget.isAIXABI())
5493     setUsesTOCBasePtr(DAG);
5494 
5495   unsigned CallOpc =
5496       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5497                     Subtarget, DAG.getTarget());
5498 
5499   if (!CFlags.IsIndirect)
5500     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5501   else if (Subtarget.usesFunctionDescriptors())
5502     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5503                                   dl, CFlags.HasNest, Subtarget);
5504   else
5505     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5506 
5507   // Build the operand list for the call instruction.
5508   SmallVector<SDValue, 8> Ops;
5509   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5510                     SPDiff, Subtarget);
5511 
5512   // Emit tail call.
5513   if (CFlags.IsTailCall) {
5514     assert(((Callee.getOpcode() == ISD::Register &&
5515              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5516             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5517             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5518             isa<ConstantSDNode>(Callee)) &&
5519            "Expecting a global address, external symbol, absolute value or "
5520            "register");
5521     assert(CallOpc == PPCISD::TC_RETURN &&
5522            "Unexpected call opcode for a tail call.");
5523     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5524     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5525   }
5526 
5527   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5528   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5529   Glue = Chain.getValue(1);
5530 
5531   // When performing tail call optimization the callee pops its arguments off
5532   // the stack. Account for this here so these bytes can be pushed back on in
5533   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5534   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5535                          getTargetMachine().Options.GuaranteedTailCallOpt)
5536                             ? NumBytes
5537                             : 0;
5538 
5539   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5540                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5541                              Glue, dl);
5542   Glue = Chain.getValue(1);
5543 
5544   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5545                          DAG, InVals);
5546 }
5547 
5548 SDValue
5549 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5550                              SmallVectorImpl<SDValue> &InVals) const {
5551   SelectionDAG &DAG                     = CLI.DAG;
5552   SDLoc &dl                             = CLI.DL;
5553   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5554   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5555   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5556   SDValue Chain                         = CLI.Chain;
5557   SDValue Callee                        = CLI.Callee;
5558   bool &isTailCall                      = CLI.IsTailCall;
5559   CallingConv::ID CallConv              = CLI.CallConv;
5560   bool isVarArg                         = CLI.IsVarArg;
5561   bool isPatchPoint                     = CLI.IsPatchPoint;
5562   const CallBase *CB                    = CLI.CB;
5563 
5564   if (isTailCall) {
5565     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5566       isTailCall = false;
5567     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5568       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5569           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5570     else
5571       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5572                                                      Ins, DAG);
5573     if (isTailCall) {
5574       ++NumTailCalls;
5575       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5576         ++NumSiblingCalls;
5577 
5578       assert(isa<GlobalAddressSDNode>(Callee) &&
5579              "Callee should be an llvm::Function object.");
5580       LLVM_DEBUG(
5581           const GlobalValue *GV =
5582               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5583           const unsigned Width =
5584               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5585           dbgs() << "TCO caller: "
5586                  << left_justify(DAG.getMachineFunction().getName(), Width)
5587                  << ", callee linkage: " << GV->getVisibility() << ", "
5588                  << GV->getLinkage() << "\n");
5589     }
5590   }
5591 
5592   if (!isTailCall && CB && CB->isMustTailCall())
5593     report_fatal_error("failed to perform tail call elimination on a call "
5594                        "site marked musttail");
5595 
5596   // When long calls (i.e. indirect calls) are always used, calls are always
5597   // made via function pointer. If we have a function name, first translate it
5598   // into a pointer.
5599   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5600       !isTailCall)
5601     Callee = LowerGlobalAddress(Callee, DAG);
5602 
5603   CallFlags CFlags(
5604       CallConv, isTailCall, isVarArg, isPatchPoint,
5605       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5606       // hasNest
5607       Subtarget.is64BitELFABI() &&
5608           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5609 
5610   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5611     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5612                             InVals, CB);
5613 
5614   if (Subtarget.isSVR4ABI())
5615     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5616                             InVals, CB);
5617 
5618   if (Subtarget.isAIXABI())
5619     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5620                          InVals, CB);
5621 
5622   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5623                           InVals, CB);
5624 }
5625 
5626 SDValue PPCTargetLowering::LowerCall_32SVR4(
5627     SDValue Chain, SDValue Callee, CallFlags CFlags,
5628     const SmallVectorImpl<ISD::OutputArg> &Outs,
5629     const SmallVectorImpl<SDValue> &OutVals,
5630     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5631     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5632     const CallBase *CB) const {
5633   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5634   // of the 32-bit SVR4 ABI stack frame layout.
5635 
5636   const CallingConv::ID CallConv = CFlags.CallConv;
5637   const bool IsVarArg = CFlags.IsVarArg;
5638   const bool IsTailCall = CFlags.IsTailCall;
5639 
5640   assert((CallConv == CallingConv::C ||
5641           CallConv == CallingConv::Cold ||
5642           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5643 
5644   unsigned PtrByteSize = 4;
5645 
5646   MachineFunction &MF = DAG.getMachineFunction();
5647 
5648   // Mark this function as potentially containing a function that contains a
5649   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5650   // and restoring the callers stack pointer in this functions epilog. This is
5651   // done because by tail calling the called function might overwrite the value
5652   // in this function's (MF) stack pointer stack slot 0(SP).
5653   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5654       CallConv == CallingConv::Fast)
5655     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5656 
5657   // Count how many bytes are to be pushed on the stack, including the linkage
5658   // area, parameter list area and the part of the local variable space which
5659   // contains copies of aggregates which are passed by value.
5660 
5661   // Assign locations to all of the outgoing arguments.
5662   SmallVector<CCValAssign, 16> ArgLocs;
5663   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5664 
5665   // Reserve space for the linkage area on the stack.
5666   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5667                        PtrByteSize);
5668   if (useSoftFloat())
5669     CCInfo.PreAnalyzeCallOperands(Outs);
5670 
5671   if (IsVarArg) {
5672     // Handle fixed and variable vector arguments differently.
5673     // Fixed vector arguments go into registers as long as registers are
5674     // available. Variable vector arguments always go into memory.
5675     unsigned NumArgs = Outs.size();
5676 
5677     for (unsigned i = 0; i != NumArgs; ++i) {
5678       MVT ArgVT = Outs[i].VT;
5679       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5680       bool Result;
5681 
5682       if (Outs[i].IsFixed) {
5683         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5684                                CCInfo);
5685       } else {
5686         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5687                                       ArgFlags, CCInfo);
5688       }
5689 
5690       if (Result) {
5691 #ifndef NDEBUG
5692         errs() << "Call operand #" << i << " has unhandled type "
5693              << EVT(ArgVT).getEVTString() << "\n";
5694 #endif
5695         llvm_unreachable(nullptr);
5696       }
5697     }
5698   } else {
5699     // All arguments are treated the same.
5700     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5701   }
5702   CCInfo.clearWasPPCF128();
5703 
5704   // Assign locations to all of the outgoing aggregate by value arguments.
5705   SmallVector<CCValAssign, 16> ByValArgLocs;
5706   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5707 
5708   // Reserve stack space for the allocations in CCInfo.
5709   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5710 
5711   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5712 
5713   // Size of the linkage area, parameter list area and the part of the local
5714   // space variable where copies of aggregates which are passed by value are
5715   // stored.
5716   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5717 
5718   // Calculate by how many bytes the stack has to be adjusted in case of tail
5719   // call optimization.
5720   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5721 
5722   // Adjust the stack pointer for the new arguments...
5723   // These operations are automatically eliminated by the prolog/epilog pass
5724   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5725   SDValue CallSeqStart = Chain;
5726 
5727   // Load the return address and frame pointer so it can be moved somewhere else
5728   // later.
5729   SDValue LROp, FPOp;
5730   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5731 
5732   // Set up a copy of the stack pointer for use loading and storing any
5733   // arguments that may not fit in the registers available for argument
5734   // passing.
5735   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5736 
5737   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5738   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5739   SmallVector<SDValue, 8> MemOpChains;
5740 
5741   bool seenFloatArg = false;
5742   // Walk the register/memloc assignments, inserting copies/loads.
5743   // i - Tracks the index into the list of registers allocated for the call
5744   // RealArgIdx - Tracks the index into the list of actual function arguments
5745   // j - Tracks the index into the list of byval arguments
5746   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5747        i != e;
5748        ++i, ++RealArgIdx) {
5749     CCValAssign &VA = ArgLocs[i];
5750     SDValue Arg = OutVals[RealArgIdx];
5751     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5752 
5753     if (Flags.isByVal()) {
5754       // Argument is an aggregate which is passed by value, thus we need to
5755       // create a copy of it in the local variable space of the current stack
5756       // frame (which is the stack frame of the caller) and pass the address of
5757       // this copy to the callee.
5758       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5759       CCValAssign &ByValVA = ByValArgLocs[j++];
5760       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5761 
5762       // Memory reserved in the local variable space of the callers stack frame.
5763       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5764 
5765       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5766       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5767                            StackPtr, PtrOff);
5768 
5769       // Create a copy of the argument in the local area of the current
5770       // stack frame.
5771       SDValue MemcpyCall =
5772         CreateCopyOfByValArgument(Arg, PtrOff,
5773                                   CallSeqStart.getNode()->getOperand(0),
5774                                   Flags, DAG, dl);
5775 
5776       // This must go outside the CALLSEQ_START..END.
5777       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5778                                                      SDLoc(MemcpyCall));
5779       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5780                              NewCallSeqStart.getNode());
5781       Chain = CallSeqStart = NewCallSeqStart;
5782 
5783       // Pass the address of the aggregate copy on the stack either in a
5784       // physical register or in the parameter list area of the current stack
5785       // frame to the callee.
5786       Arg = PtrOff;
5787     }
5788 
5789     // When useCRBits() is true, there can be i1 arguments.
5790     // It is because getRegisterType(MVT::i1) => MVT::i1,
5791     // and for other integer types getRegisterType() => MVT::i32.
5792     // Extend i1 and ensure callee will get i32.
5793     if (Arg.getValueType() == MVT::i1)
5794       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5795                         dl, MVT::i32, Arg);
5796 
5797     if (VA.isRegLoc()) {
5798       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5799       // Put argument in a physical register.
5800       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5801         bool IsLE = Subtarget.isLittleEndian();
5802         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5803                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5804         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5805         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5806                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5807         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5808                              SVal.getValue(0)));
5809       } else
5810         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5811     } else {
5812       // Put argument in the parameter list area of the current stack frame.
5813       assert(VA.isMemLoc());
5814       unsigned LocMemOffset = VA.getLocMemOffset();
5815 
5816       if (!IsTailCall) {
5817         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5818         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5819                              StackPtr, PtrOff);
5820 
5821         MemOpChains.push_back(
5822             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5823       } else {
5824         // Calculate and remember argument location.
5825         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5826                                  TailCallArguments);
5827       }
5828     }
5829   }
5830 
5831   if (!MemOpChains.empty())
5832     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5833 
5834   // Build a sequence of copy-to-reg nodes chained together with token chain
5835   // and flag operands which copy the outgoing args into the appropriate regs.
5836   SDValue InFlag;
5837   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5838     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5839                              RegsToPass[i].second, InFlag);
5840     InFlag = Chain.getValue(1);
5841   }
5842 
5843   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5844   // registers.
5845   if (IsVarArg) {
5846     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5847     SDValue Ops[] = { Chain, InFlag };
5848 
5849     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5850                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5851 
5852     InFlag = Chain.getValue(1);
5853   }
5854 
5855   if (IsTailCall)
5856     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5857                     TailCallArguments);
5858 
5859   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5860                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5861 }
5862 
5863 // Copy an argument into memory, being careful to do this outside the
5864 // call sequence for the call to which the argument belongs.
5865 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5866     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5867     SelectionDAG &DAG, const SDLoc &dl) const {
5868   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5869                         CallSeqStart.getNode()->getOperand(0),
5870                         Flags, DAG, dl);
5871   // The MEMCPY must go outside the CALLSEQ_START..END.
5872   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5873   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5874                                                  SDLoc(MemcpyCall));
5875   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5876                          NewCallSeqStart.getNode());
5877   return NewCallSeqStart;
5878 }
5879 
5880 SDValue PPCTargetLowering::LowerCall_64SVR4(
5881     SDValue Chain, SDValue Callee, CallFlags CFlags,
5882     const SmallVectorImpl<ISD::OutputArg> &Outs,
5883     const SmallVectorImpl<SDValue> &OutVals,
5884     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5885     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5886     const CallBase *CB) const {
5887   bool isELFv2ABI = Subtarget.isELFv2ABI();
5888   bool isLittleEndian = Subtarget.isLittleEndian();
5889   unsigned NumOps = Outs.size();
5890   bool IsSibCall = false;
5891   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5892 
5893   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5894   unsigned PtrByteSize = 8;
5895 
5896   MachineFunction &MF = DAG.getMachineFunction();
5897 
5898   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5899     IsSibCall = true;
5900 
5901   // Mark this function as potentially containing a function that contains a
5902   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5903   // and restoring the callers stack pointer in this functions epilog. This is
5904   // done because by tail calling the called function might overwrite the value
5905   // in this function's (MF) stack pointer stack slot 0(SP).
5906   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5907     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5908 
5909   assert(!(IsFastCall && CFlags.IsVarArg) &&
5910          "fastcc not supported on varargs functions");
5911 
5912   // Count how many bytes are to be pushed on the stack, including the linkage
5913   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5914   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5915   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5916   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5917   unsigned NumBytes = LinkageSize;
5918   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5919   unsigned &QFPR_idx = FPR_idx;
5920 
5921   static const MCPhysReg GPR[] = {
5922     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5923     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5924   };
5925   static const MCPhysReg VR[] = {
5926     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5927     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5928   };
5929 
5930   const unsigned NumGPRs = array_lengthof(GPR);
5931   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5932   const unsigned NumVRs  = array_lengthof(VR);
5933   const unsigned NumQFPRs = NumFPRs;
5934 
5935   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5936   // can be passed to the callee in registers.
5937   // For the fast calling convention, there is another check below.
5938   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5939   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5940   if (!HasParameterArea) {
5941     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5942     unsigned AvailableFPRs = NumFPRs;
5943     unsigned AvailableVRs = NumVRs;
5944     unsigned NumBytesTmp = NumBytes;
5945     for (unsigned i = 0; i != NumOps; ++i) {
5946       if (Outs[i].Flags.isNest()) continue;
5947       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5948                                 PtrByteSize, LinkageSize, ParamAreaSize,
5949                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5950                                 Subtarget.hasQPX()))
5951         HasParameterArea = true;
5952     }
5953   }
5954 
5955   // When using the fast calling convention, we don't provide backing for
5956   // arguments that will be in registers.
5957   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5958 
5959   // Avoid allocating parameter area for fastcc functions if all the arguments
5960   // can be passed in the registers.
5961   if (IsFastCall)
5962     HasParameterArea = false;
5963 
5964   // Add up all the space actually used.
5965   for (unsigned i = 0; i != NumOps; ++i) {
5966     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5967     EVT ArgVT = Outs[i].VT;
5968     EVT OrigVT = Outs[i].ArgVT;
5969 
5970     if (Flags.isNest())
5971       continue;
5972 
5973     if (IsFastCall) {
5974       if (Flags.isByVal()) {
5975         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5976         if (NumGPRsUsed > NumGPRs)
5977           HasParameterArea = true;
5978       } else {
5979         switch (ArgVT.getSimpleVT().SimpleTy) {
5980         default: llvm_unreachable("Unexpected ValueType for argument!");
5981         case MVT::i1:
5982         case MVT::i32:
5983         case MVT::i64:
5984           if (++NumGPRsUsed <= NumGPRs)
5985             continue;
5986           break;
5987         case MVT::v4i32:
5988         case MVT::v8i16:
5989         case MVT::v16i8:
5990         case MVT::v2f64:
5991         case MVT::v2i64:
5992         case MVT::v1i128:
5993         case MVT::f128:
5994           if (++NumVRsUsed <= NumVRs)
5995             continue;
5996           break;
5997         case MVT::v4f32:
5998           // When using QPX, this is handled like a FP register, otherwise, it
5999           // is an Altivec register.
6000           if (Subtarget.hasQPX()) {
6001             if (++NumFPRsUsed <= NumFPRs)
6002               continue;
6003           } else {
6004             if (++NumVRsUsed <= NumVRs)
6005               continue;
6006           }
6007           break;
6008         case MVT::f32:
6009         case MVT::f64:
6010         case MVT::v4f64: // QPX
6011         case MVT::v4i1:  // QPX
6012           if (++NumFPRsUsed <= NumFPRs)
6013             continue;
6014           break;
6015         }
6016         HasParameterArea = true;
6017       }
6018     }
6019 
6020     /* Respect alignment of argument on the stack.  */
6021     auto Alignement =
6022         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6023     NumBytes = alignTo(NumBytes, Alignement);
6024 
6025     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6026     if (Flags.isInConsecutiveRegsLast())
6027       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6028   }
6029 
6030   unsigned NumBytesActuallyUsed = NumBytes;
6031 
6032   // In the old ELFv1 ABI,
6033   // the prolog code of the callee may store up to 8 GPR argument registers to
6034   // the stack, allowing va_start to index over them in memory if its varargs.
6035   // Because we cannot tell if this is needed on the caller side, we have to
6036   // conservatively assume that it is needed.  As such, make sure we have at
6037   // least enough stack space for the caller to store the 8 GPRs.
6038   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6039   // really requires memory operands, e.g. a vararg function.
6040   if (HasParameterArea)
6041     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6042   else
6043     NumBytes = LinkageSize;
6044 
6045   // Tail call needs the stack to be aligned.
6046   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6047     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6048 
6049   int SPDiff = 0;
6050 
6051   // Calculate by how many bytes the stack has to be adjusted in case of tail
6052   // call optimization.
6053   if (!IsSibCall)
6054     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6055 
6056   // To protect arguments on the stack from being clobbered in a tail call,
6057   // force all the loads to happen before doing any other lowering.
6058   if (CFlags.IsTailCall)
6059     Chain = DAG.getStackArgumentTokenFactor(Chain);
6060 
6061   // Adjust the stack pointer for the new arguments...
6062   // These operations are automatically eliminated by the prolog/epilog pass
6063   if (!IsSibCall)
6064     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6065   SDValue CallSeqStart = Chain;
6066 
6067   // Load the return address and frame pointer so it can be move somewhere else
6068   // later.
6069   SDValue LROp, FPOp;
6070   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6071 
6072   // Set up a copy of the stack pointer for use loading and storing any
6073   // arguments that may not fit in the registers available for argument
6074   // passing.
6075   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6076 
6077   // Figure out which arguments are going to go in registers, and which in
6078   // memory.  Also, if this is a vararg function, floating point operations
6079   // must be stored to our stack, and loaded into integer regs as well, if
6080   // any integer regs are available for argument passing.
6081   unsigned ArgOffset = LinkageSize;
6082 
6083   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6084   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6085 
6086   SmallVector<SDValue, 8> MemOpChains;
6087   for (unsigned i = 0; i != NumOps; ++i) {
6088     SDValue Arg = OutVals[i];
6089     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6090     EVT ArgVT = Outs[i].VT;
6091     EVT OrigVT = Outs[i].ArgVT;
6092 
6093     // PtrOff will be used to store the current argument to the stack if a
6094     // register cannot be found for it.
6095     SDValue PtrOff;
6096 
6097     // We re-align the argument offset for each argument, except when using the
6098     // fast calling convention, when we need to make sure we do that only when
6099     // we'll actually use a stack slot.
6100     auto ComputePtrOff = [&]() {
6101       /* Respect alignment of argument on the stack.  */
6102       auto Alignment =
6103           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6104       ArgOffset = alignTo(ArgOffset, Alignment);
6105 
6106       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6107 
6108       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6109     };
6110 
6111     if (!IsFastCall) {
6112       ComputePtrOff();
6113 
6114       /* Compute GPR index associated with argument offset.  */
6115       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6116       GPR_idx = std::min(GPR_idx, NumGPRs);
6117     }
6118 
6119     // Promote integers to 64-bit values.
6120     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6121       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6122       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6123       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6124     }
6125 
6126     // FIXME memcpy is used way more than necessary.  Correctness first.
6127     // Note: "by value" is code for passing a structure by value, not
6128     // basic types.
6129     if (Flags.isByVal()) {
6130       // Note: Size includes alignment padding, so
6131       //   struct x { short a; char b; }
6132       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6133       // These are the proper values we need for right-justifying the
6134       // aggregate in a parameter register.
6135       unsigned Size = Flags.getByValSize();
6136 
6137       // An empty aggregate parameter takes up no storage and no
6138       // registers.
6139       if (Size == 0)
6140         continue;
6141 
6142       if (IsFastCall)
6143         ComputePtrOff();
6144 
6145       // All aggregates smaller than 8 bytes must be passed right-justified.
6146       if (Size==1 || Size==2 || Size==4) {
6147         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6148         if (GPR_idx != NumGPRs) {
6149           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6150                                         MachinePointerInfo(), VT);
6151           MemOpChains.push_back(Load.getValue(1));
6152           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6153 
6154           ArgOffset += PtrByteSize;
6155           continue;
6156         }
6157       }
6158 
6159       if (GPR_idx == NumGPRs && Size < 8) {
6160         SDValue AddPtr = PtrOff;
6161         if (!isLittleEndian) {
6162           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6163                                           PtrOff.getValueType());
6164           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6165         }
6166         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6167                                                           CallSeqStart,
6168                                                           Flags, DAG, dl);
6169         ArgOffset += PtrByteSize;
6170         continue;
6171       }
6172       // Copy entire object into memory.  There are cases where gcc-generated
6173       // code assumes it is there, even if it could be put entirely into
6174       // registers.  (This is not what the doc says.)
6175 
6176       // FIXME: The above statement is likely due to a misunderstanding of the
6177       // documents.  All arguments must be copied into the parameter area BY
6178       // THE CALLEE in the event that the callee takes the address of any
6179       // formal argument.  That has not yet been implemented.  However, it is
6180       // reasonable to use the stack area as a staging area for the register
6181       // load.
6182 
6183       // Skip this for small aggregates, as we will use the same slot for a
6184       // right-justified copy, below.
6185       if (Size >= 8)
6186         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6187                                                           CallSeqStart,
6188                                                           Flags, DAG, dl);
6189 
6190       // When a register is available, pass a small aggregate right-justified.
6191       if (Size < 8 && GPR_idx != NumGPRs) {
6192         // The easiest way to get this right-justified in a register
6193         // is to copy the structure into the rightmost portion of a
6194         // local variable slot, then load the whole slot into the
6195         // register.
6196         // FIXME: The memcpy seems to produce pretty awful code for
6197         // small aggregates, particularly for packed ones.
6198         // FIXME: It would be preferable to use the slot in the
6199         // parameter save area instead of a new local variable.
6200         SDValue AddPtr = PtrOff;
6201         if (!isLittleEndian) {
6202           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6203           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6204         }
6205         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6206                                                           CallSeqStart,
6207                                                           Flags, DAG, dl);
6208 
6209         // Load the slot into the register.
6210         SDValue Load =
6211             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6212         MemOpChains.push_back(Load.getValue(1));
6213         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6214 
6215         // Done with this argument.
6216         ArgOffset += PtrByteSize;
6217         continue;
6218       }
6219 
6220       // For aggregates larger than PtrByteSize, copy the pieces of the
6221       // object that fit into registers from the parameter save area.
6222       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6223         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6224         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6225         if (GPR_idx != NumGPRs) {
6226           SDValue Load =
6227               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6228           MemOpChains.push_back(Load.getValue(1));
6229           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6230           ArgOffset += PtrByteSize;
6231         } else {
6232           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6233           break;
6234         }
6235       }
6236       continue;
6237     }
6238 
6239     switch (Arg.getSimpleValueType().SimpleTy) {
6240     default: llvm_unreachable("Unexpected ValueType for argument!");
6241     case MVT::i1:
6242     case MVT::i32:
6243     case MVT::i64:
6244       if (Flags.isNest()) {
6245         // The 'nest' parameter, if any, is passed in R11.
6246         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6247         break;
6248       }
6249 
6250       // These can be scalar arguments or elements of an integer array type
6251       // passed directly.  Clang may use those instead of "byval" aggregate
6252       // types to avoid forcing arguments to memory unnecessarily.
6253       if (GPR_idx != NumGPRs) {
6254         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6255       } else {
6256         if (IsFastCall)
6257           ComputePtrOff();
6258 
6259         assert(HasParameterArea &&
6260                "Parameter area must exist to pass an argument in memory.");
6261         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6262                          true, CFlags.IsTailCall, false, MemOpChains,
6263                          TailCallArguments, dl);
6264         if (IsFastCall)
6265           ArgOffset += PtrByteSize;
6266       }
6267       if (!IsFastCall)
6268         ArgOffset += PtrByteSize;
6269       break;
6270     case MVT::f32:
6271     case MVT::f64: {
6272       // These can be scalar arguments or elements of a float array type
6273       // passed directly.  The latter are used to implement ELFv2 homogenous
6274       // float aggregates.
6275 
6276       // Named arguments go into FPRs first, and once they overflow, the
6277       // remaining arguments go into GPRs and then the parameter save area.
6278       // Unnamed arguments for vararg functions always go to GPRs and
6279       // then the parameter save area.  For now, put all arguments to vararg
6280       // routines always in both locations (FPR *and* GPR or stack slot).
6281       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6282       bool NeededLoad = false;
6283 
6284       // First load the argument into the next available FPR.
6285       if (FPR_idx != NumFPRs)
6286         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6287 
6288       // Next, load the argument into GPR or stack slot if needed.
6289       if (!NeedGPROrStack)
6290         ;
6291       else if (GPR_idx != NumGPRs && !IsFastCall) {
6292         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6293         // once we support fp <-> gpr moves.
6294 
6295         // In the non-vararg case, this can only ever happen in the
6296         // presence of f32 array types, since otherwise we never run
6297         // out of FPRs before running out of GPRs.
6298         SDValue ArgVal;
6299 
6300         // Double values are always passed in a single GPR.
6301         if (Arg.getValueType() != MVT::f32) {
6302           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6303 
6304         // Non-array float values are extended and passed in a GPR.
6305         } else if (!Flags.isInConsecutiveRegs()) {
6306           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6307           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6308 
6309         // If we have an array of floats, we collect every odd element
6310         // together with its predecessor into one GPR.
6311         } else if (ArgOffset % PtrByteSize != 0) {
6312           SDValue Lo, Hi;
6313           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6314           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6315           if (!isLittleEndian)
6316             std::swap(Lo, Hi);
6317           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6318 
6319         // The final element, if even, goes into the first half of a GPR.
6320         } else if (Flags.isInConsecutiveRegsLast()) {
6321           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6322           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6323           if (!isLittleEndian)
6324             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6325                                  DAG.getConstant(32, dl, MVT::i32));
6326 
6327         // Non-final even elements are skipped; they will be handled
6328         // together the with subsequent argument on the next go-around.
6329         } else
6330           ArgVal = SDValue();
6331 
6332         if (ArgVal.getNode())
6333           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6334       } else {
6335         if (IsFastCall)
6336           ComputePtrOff();
6337 
6338         // Single-precision floating-point values are mapped to the
6339         // second (rightmost) word of the stack doubleword.
6340         if (Arg.getValueType() == MVT::f32 &&
6341             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6342           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6343           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6344         }
6345 
6346         assert(HasParameterArea &&
6347                "Parameter area must exist to pass an argument in memory.");
6348         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6349                          true, CFlags.IsTailCall, false, MemOpChains,
6350                          TailCallArguments, dl);
6351 
6352         NeededLoad = true;
6353       }
6354       // When passing an array of floats, the array occupies consecutive
6355       // space in the argument area; only round up to the next doubleword
6356       // at the end of the array.  Otherwise, each float takes 8 bytes.
6357       if (!IsFastCall || NeededLoad) {
6358         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6359                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6360         if (Flags.isInConsecutiveRegsLast())
6361           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6362       }
6363       break;
6364     }
6365     case MVT::v4f32:
6366     case MVT::v4i32:
6367     case MVT::v8i16:
6368     case MVT::v16i8:
6369     case MVT::v2f64:
6370     case MVT::v2i64:
6371     case MVT::v1i128:
6372     case MVT::f128:
6373       if (!Subtarget.hasQPX()) {
6374       // These can be scalar arguments or elements of a vector array type
6375       // passed directly.  The latter are used to implement ELFv2 homogenous
6376       // vector aggregates.
6377 
6378       // For a varargs call, named arguments go into VRs or on the stack as
6379       // usual; unnamed arguments always go to the stack or the corresponding
6380       // GPRs when within range.  For now, we always put the value in both
6381       // locations (or even all three).
6382       if (CFlags.IsVarArg) {
6383         assert(HasParameterArea &&
6384                "Parameter area must exist if we have a varargs call.");
6385         // We could elide this store in the case where the object fits
6386         // entirely in R registers.  Maybe later.
6387         SDValue Store =
6388             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6389         MemOpChains.push_back(Store);
6390         if (VR_idx != NumVRs) {
6391           SDValue Load =
6392               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6393           MemOpChains.push_back(Load.getValue(1));
6394           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6395         }
6396         ArgOffset += 16;
6397         for (unsigned i=0; i<16; i+=PtrByteSize) {
6398           if (GPR_idx == NumGPRs)
6399             break;
6400           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6401                                    DAG.getConstant(i, dl, PtrVT));
6402           SDValue Load =
6403               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6404           MemOpChains.push_back(Load.getValue(1));
6405           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6406         }
6407         break;
6408       }
6409 
6410       // Non-varargs Altivec params go into VRs or on the stack.
6411       if (VR_idx != NumVRs) {
6412         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6413       } else {
6414         if (IsFastCall)
6415           ComputePtrOff();
6416 
6417         assert(HasParameterArea &&
6418                "Parameter area must exist to pass an argument in memory.");
6419         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6420                          true, CFlags.IsTailCall, true, MemOpChains,
6421                          TailCallArguments, dl);
6422         if (IsFastCall)
6423           ArgOffset += 16;
6424       }
6425 
6426       if (!IsFastCall)
6427         ArgOffset += 16;
6428       break;
6429       } // not QPX
6430 
6431       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6432              "Invalid QPX parameter type");
6433 
6434       LLVM_FALLTHROUGH;
6435     case MVT::v4f64:
6436     case MVT::v4i1: {
6437       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6438       if (CFlags.IsVarArg) {
6439         assert(HasParameterArea &&
6440                "Parameter area must exist if we have a varargs call.");
6441         // We could elide this store in the case where the object fits
6442         // entirely in R registers.  Maybe later.
6443         SDValue Store =
6444             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6445         MemOpChains.push_back(Store);
6446         if (QFPR_idx != NumQFPRs) {
6447           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6448                                      PtrOff, MachinePointerInfo());
6449           MemOpChains.push_back(Load.getValue(1));
6450           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6451         }
6452         ArgOffset += (IsF32 ? 16 : 32);
6453         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6454           if (GPR_idx == NumGPRs)
6455             break;
6456           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6457                                    DAG.getConstant(i, dl, PtrVT));
6458           SDValue Load =
6459               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6460           MemOpChains.push_back(Load.getValue(1));
6461           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6462         }
6463         break;
6464       }
6465 
6466       // Non-varargs QPX params go into registers or on the stack.
6467       if (QFPR_idx != NumQFPRs) {
6468         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6469       } else {
6470         if (IsFastCall)
6471           ComputePtrOff();
6472 
6473         assert(HasParameterArea &&
6474                "Parameter area must exist to pass an argument in memory.");
6475         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6476                          true, CFlags.IsTailCall, true, MemOpChains,
6477                          TailCallArguments, dl);
6478         if (IsFastCall)
6479           ArgOffset += (IsF32 ? 16 : 32);
6480       }
6481 
6482       if (!IsFastCall)
6483         ArgOffset += (IsF32 ? 16 : 32);
6484       break;
6485       }
6486     }
6487   }
6488 
6489   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6490          "mismatch in size of parameter area");
6491   (void)NumBytesActuallyUsed;
6492 
6493   if (!MemOpChains.empty())
6494     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6495 
6496   // Check if this is an indirect call (MTCTR/BCTRL).
6497   // See prepareDescriptorIndirectCall and buildCallOperands for more
6498   // information about calls through function pointers in the 64-bit SVR4 ABI.
6499   if (CFlags.IsIndirect) {
6500     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6501     // Load r2 into a virtual register and store it to the TOC save area.
6502     setUsesTOCBasePtr(DAG);
6503     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6504     // TOC save area offset.
6505     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6506     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6507     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6508     Chain = DAG.getStore(
6509         Val.getValue(1), dl, Val, AddPtr,
6510         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6511     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6512     // This does not mean the MTCTR instruction must use R12; it's easier
6513     // to model this as an extra parameter, so do that.
6514     if (isELFv2ABI && !CFlags.IsPatchPoint)
6515       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6516   }
6517 
6518   // Build a sequence of copy-to-reg nodes chained together with token chain
6519   // and flag operands which copy the outgoing args into the appropriate regs.
6520   SDValue InFlag;
6521   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6522     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6523                              RegsToPass[i].second, InFlag);
6524     InFlag = Chain.getValue(1);
6525   }
6526 
6527   if (CFlags.IsTailCall && !IsSibCall)
6528     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6529                     TailCallArguments);
6530 
6531   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6532                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6533 }
6534 
6535 SDValue PPCTargetLowering::LowerCall_Darwin(
6536     SDValue Chain, SDValue Callee, CallFlags CFlags,
6537     const SmallVectorImpl<ISD::OutputArg> &Outs,
6538     const SmallVectorImpl<SDValue> &OutVals,
6539     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6540     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6541     const CallBase *CB) const {
6542   unsigned NumOps = Outs.size();
6543 
6544   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6545   bool isPPC64 = PtrVT == MVT::i64;
6546   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6547 
6548   MachineFunction &MF = DAG.getMachineFunction();
6549 
6550   // Mark this function as potentially containing a function that contains a
6551   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6552   // and restoring the callers stack pointer in this functions epilog. This is
6553   // done because by tail calling the called function might overwrite the value
6554   // in this function's (MF) stack pointer stack slot 0(SP).
6555   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6556       CFlags.CallConv == CallingConv::Fast)
6557     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6558 
6559   // Count how many bytes are to be pushed on the stack, including the linkage
6560   // area, and parameter passing area.  We start with 24/48 bytes, which is
6561   // prereserved space for [SP][CR][LR][3 x unused].
6562   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6563   unsigned NumBytes = LinkageSize;
6564 
6565   // Add up all the space actually used.
6566   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6567   // they all go in registers, but we must reserve stack space for them for
6568   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6569   // assigned stack space in order, with padding so Altivec parameters are
6570   // 16-byte aligned.
6571   unsigned nAltivecParamsAtEnd = 0;
6572   for (unsigned i = 0; i != NumOps; ++i) {
6573     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6574     EVT ArgVT = Outs[i].VT;
6575     // Varargs Altivec parameters are padded to a 16 byte boundary.
6576     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6577         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6578         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6579       if (!CFlags.IsVarArg && !isPPC64) {
6580         // Non-varargs Altivec parameters go after all the non-Altivec
6581         // parameters; handle those later so we know how much padding we need.
6582         nAltivecParamsAtEnd++;
6583         continue;
6584       }
6585       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6586       NumBytes = ((NumBytes+15)/16)*16;
6587     }
6588     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6589   }
6590 
6591   // Allow for Altivec parameters at the end, if needed.
6592   if (nAltivecParamsAtEnd) {
6593     NumBytes = ((NumBytes+15)/16)*16;
6594     NumBytes += 16*nAltivecParamsAtEnd;
6595   }
6596 
6597   // The prolog code of the callee may store up to 8 GPR argument registers to
6598   // the stack, allowing va_start to index over them in memory if its varargs.
6599   // Because we cannot tell if this is needed on the caller side, we have to
6600   // conservatively assume that it is needed.  As such, make sure we have at
6601   // least enough stack space for the caller to store the 8 GPRs.
6602   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6603 
6604   // Tail call needs the stack to be aligned.
6605   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6606       CFlags.CallConv == CallingConv::Fast)
6607     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6608 
6609   // Calculate by how many bytes the stack has to be adjusted in case of tail
6610   // call optimization.
6611   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6612 
6613   // To protect arguments on the stack from being clobbered in a tail call,
6614   // force all the loads to happen before doing any other lowering.
6615   if (CFlags.IsTailCall)
6616     Chain = DAG.getStackArgumentTokenFactor(Chain);
6617 
6618   // Adjust the stack pointer for the new arguments...
6619   // These operations are automatically eliminated by the prolog/epilog pass
6620   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6621   SDValue CallSeqStart = Chain;
6622 
6623   // Load the return address and frame pointer so it can be move somewhere else
6624   // later.
6625   SDValue LROp, FPOp;
6626   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6627 
6628   // Set up a copy of the stack pointer for use loading and storing any
6629   // arguments that may not fit in the registers available for argument
6630   // passing.
6631   SDValue StackPtr;
6632   if (isPPC64)
6633     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6634   else
6635     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6636 
6637   // Figure out which arguments are going to go in registers, and which in
6638   // memory.  Also, if this is a vararg function, floating point operations
6639   // must be stored to our stack, and loaded into integer regs as well, if
6640   // any integer regs are available for argument passing.
6641   unsigned ArgOffset = LinkageSize;
6642   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6643 
6644   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6645     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6646     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6647   };
6648   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6649     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6650     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6651   };
6652   static const MCPhysReg VR[] = {
6653     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6654     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6655   };
6656   const unsigned NumGPRs = array_lengthof(GPR_32);
6657   const unsigned NumFPRs = 13;
6658   const unsigned NumVRs  = array_lengthof(VR);
6659 
6660   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6661 
6662   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6663   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6664 
6665   SmallVector<SDValue, 8> MemOpChains;
6666   for (unsigned i = 0; i != NumOps; ++i) {
6667     SDValue Arg = OutVals[i];
6668     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6669 
6670     // PtrOff will be used to store the current argument to the stack if a
6671     // register cannot be found for it.
6672     SDValue PtrOff;
6673 
6674     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6675 
6676     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6677 
6678     // On PPC64, promote integers to 64-bit values.
6679     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6680       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6681       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6682       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6683     }
6684 
6685     // FIXME memcpy is used way more than necessary.  Correctness first.
6686     // Note: "by value" is code for passing a structure by value, not
6687     // basic types.
6688     if (Flags.isByVal()) {
6689       unsigned Size = Flags.getByValSize();
6690       // Very small objects are passed right-justified.  Everything else is
6691       // passed left-justified.
6692       if (Size==1 || Size==2) {
6693         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6694         if (GPR_idx != NumGPRs) {
6695           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6696                                         MachinePointerInfo(), VT);
6697           MemOpChains.push_back(Load.getValue(1));
6698           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6699 
6700           ArgOffset += PtrByteSize;
6701         } else {
6702           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6703                                           PtrOff.getValueType());
6704           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6705           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6706                                                             CallSeqStart,
6707                                                             Flags, DAG, dl);
6708           ArgOffset += PtrByteSize;
6709         }
6710         continue;
6711       }
6712       // Copy entire object into memory.  There are cases where gcc-generated
6713       // code assumes it is there, even if it could be put entirely into
6714       // registers.  (This is not what the doc says.)
6715       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6716                                                         CallSeqStart,
6717                                                         Flags, DAG, dl);
6718 
6719       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6720       // copy the pieces of the object that fit into registers from the
6721       // parameter save area.
6722       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6723         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6724         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6725         if (GPR_idx != NumGPRs) {
6726           SDValue Load =
6727               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6728           MemOpChains.push_back(Load.getValue(1));
6729           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6730           ArgOffset += PtrByteSize;
6731         } else {
6732           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6733           break;
6734         }
6735       }
6736       continue;
6737     }
6738 
6739     switch (Arg.getSimpleValueType().SimpleTy) {
6740     default: llvm_unreachable("Unexpected ValueType for argument!");
6741     case MVT::i1:
6742     case MVT::i32:
6743     case MVT::i64:
6744       if (GPR_idx != NumGPRs) {
6745         if (Arg.getValueType() == MVT::i1)
6746           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6747 
6748         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6749       } else {
6750         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6751                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6752                          TailCallArguments, dl);
6753       }
6754       ArgOffset += PtrByteSize;
6755       break;
6756     case MVT::f32:
6757     case MVT::f64:
6758       if (FPR_idx != NumFPRs) {
6759         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6760 
6761         if (CFlags.IsVarArg) {
6762           SDValue Store =
6763               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6764           MemOpChains.push_back(Store);
6765 
6766           // Float varargs are always shadowed in available integer registers
6767           if (GPR_idx != NumGPRs) {
6768             SDValue Load =
6769                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6770             MemOpChains.push_back(Load.getValue(1));
6771             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6772           }
6773           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6774             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6775             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6776             SDValue Load =
6777                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6778             MemOpChains.push_back(Load.getValue(1));
6779             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6780           }
6781         } else {
6782           // If we have any FPRs remaining, we may also have GPRs remaining.
6783           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6784           // GPRs.
6785           if (GPR_idx != NumGPRs)
6786             ++GPR_idx;
6787           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6788               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6789             ++GPR_idx;
6790         }
6791       } else
6792         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6793                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6794                          TailCallArguments, dl);
6795       if (isPPC64)
6796         ArgOffset += 8;
6797       else
6798         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6799       break;
6800     case MVT::v4f32:
6801     case MVT::v4i32:
6802     case MVT::v8i16:
6803     case MVT::v16i8:
6804       if (CFlags.IsVarArg) {
6805         // These go aligned on the stack, or in the corresponding R registers
6806         // when within range.  The Darwin PPC ABI doc claims they also go in
6807         // V registers; in fact gcc does this only for arguments that are
6808         // prototyped, not for those that match the ...  We do it for all
6809         // arguments, seems to work.
6810         while (ArgOffset % 16 !=0) {
6811           ArgOffset += PtrByteSize;
6812           if (GPR_idx != NumGPRs)
6813             GPR_idx++;
6814         }
6815         // We could elide this store in the case where the object fits
6816         // entirely in R registers.  Maybe later.
6817         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6818                              DAG.getConstant(ArgOffset, dl, PtrVT));
6819         SDValue Store =
6820             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6821         MemOpChains.push_back(Store);
6822         if (VR_idx != NumVRs) {
6823           SDValue Load =
6824               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6825           MemOpChains.push_back(Load.getValue(1));
6826           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6827         }
6828         ArgOffset += 16;
6829         for (unsigned i=0; i<16; i+=PtrByteSize) {
6830           if (GPR_idx == NumGPRs)
6831             break;
6832           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6833                                    DAG.getConstant(i, dl, PtrVT));
6834           SDValue Load =
6835               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6836           MemOpChains.push_back(Load.getValue(1));
6837           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6838         }
6839         break;
6840       }
6841 
6842       // Non-varargs Altivec params generally go in registers, but have
6843       // stack space allocated at the end.
6844       if (VR_idx != NumVRs) {
6845         // Doesn't have GPR space allocated.
6846         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6847       } else if (nAltivecParamsAtEnd==0) {
6848         // We are emitting Altivec params in order.
6849         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6850                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6851                          TailCallArguments, dl);
6852         ArgOffset += 16;
6853       }
6854       break;
6855     }
6856   }
6857   // If all Altivec parameters fit in registers, as they usually do,
6858   // they get stack space following the non-Altivec parameters.  We
6859   // don't track this here because nobody below needs it.
6860   // If there are more Altivec parameters than fit in registers emit
6861   // the stores here.
6862   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6863     unsigned j = 0;
6864     // Offset is aligned; skip 1st 12 params which go in V registers.
6865     ArgOffset = ((ArgOffset+15)/16)*16;
6866     ArgOffset += 12*16;
6867     for (unsigned i = 0; i != NumOps; ++i) {
6868       SDValue Arg = OutVals[i];
6869       EVT ArgType = Outs[i].VT;
6870       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6871           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6872         if (++j > NumVRs) {
6873           SDValue PtrOff;
6874           // We are emitting Altivec params in order.
6875           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6876                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6877                            TailCallArguments, dl);
6878           ArgOffset += 16;
6879         }
6880       }
6881     }
6882   }
6883 
6884   if (!MemOpChains.empty())
6885     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6886 
6887   // On Darwin, R12 must contain the address of an indirect callee.  This does
6888   // not mean the MTCTR instruction must use R12; it's easier to model this as
6889   // an extra parameter, so do that.
6890   if (CFlags.IsIndirect) {
6891     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6892     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6893                                                    PPC::R12), Callee));
6894   }
6895 
6896   // Build a sequence of copy-to-reg nodes chained together with token chain
6897   // and flag operands which copy the outgoing args into the appropriate regs.
6898   SDValue InFlag;
6899   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6900     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6901                              RegsToPass[i].second, InFlag);
6902     InFlag = Chain.getValue(1);
6903   }
6904 
6905   if (CFlags.IsTailCall)
6906     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6907                     TailCallArguments);
6908 
6909   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6910                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6911 }
6912 
6913 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6914                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6915                    CCState &State) {
6916 
6917   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6918       State.getMachineFunction().getSubtarget());
6919   const bool IsPPC64 = Subtarget.isPPC64();
6920   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6921   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6922 
6923   assert((!ValVT.isInteger() ||
6924           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6925          "Integer argument exceeds register size: should have been legalized");
6926 
6927   if (ValVT == MVT::f128)
6928     report_fatal_error("f128 is unimplemented on AIX.");
6929 
6930   if (ArgFlags.isNest())
6931     report_fatal_error("Nest arguments are unimplemented.");
6932 
6933   if (ValVT.isVector() || LocVT.isVector())
6934     report_fatal_error("Vector arguments are unimplemented on AIX.");
6935 
6936   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6937                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6938                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6939   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6940                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6941                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6942 
6943   if (ArgFlags.isByVal()) {
6944     if (ArgFlags.getNonZeroByValAlign() > PtrByteSize)
6945       report_fatal_error("Pass-by-value arguments with alignment greater than "
6946                          "register width are not supported.");
6947 
6948     const unsigned ByValSize = ArgFlags.getByValSize();
6949 
6950     // An empty aggregate parameter takes up no storage and no registers,
6951     // but needs a MemLoc for a stack slot for the formal arguments side.
6952     if (ByValSize == 0) {
6953       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6954                                        State.getNextStackOffset(), RegVT,
6955                                        LocInfo));
6956       return false;
6957     }
6958 
6959     const unsigned StackSize = alignTo(ByValSize, PtrByteSize);
6960     unsigned Offset = State.AllocateStack(StackSize, PtrByteSize);
6961     for (const unsigned E = Offset + StackSize; Offset < E;
6962          Offset += PtrByteSize) {
6963       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6964         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6965       else {
6966         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6967                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6968                                          LocInfo));
6969         break;
6970       }
6971     }
6972     return false;
6973   }
6974 
6975   // Arguments always reserve parameter save area.
6976   switch (ValVT.SimpleTy) {
6977   default:
6978     report_fatal_error("Unhandled value type for argument.");
6979   case MVT::i64:
6980     // i64 arguments should have been split to i32 for PPC32.
6981     assert(IsPPC64 && "PPC32 should have split i64 values.");
6982     LLVM_FALLTHROUGH;
6983   case MVT::i1:
6984   case MVT::i32: {
6985     const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize);
6986     // AIX integer arguments are always passed in register width.
6987     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6988       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6989                                   : CCValAssign::LocInfo::ZExt;
6990     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6991       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6992     else
6993       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6994 
6995     return false;
6996   }
6997   case MVT::f32:
6998   case MVT::f64: {
6999     // Parameter save area (PSA) is reserved even if the float passes in fpr.
7000     const unsigned StoreSize = LocVT.getStoreSize();
7001     // Floats are always 4-byte aligned in the PSA on AIX.
7002     // This includes f64 in 64-bit mode for ABI compatibility.
7003     const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
7004     unsigned FReg = State.AllocateReg(FPR);
7005     if (FReg)
7006       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
7007 
7008     // Reserve and initialize GPRs or initialize the PSA as required.
7009     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
7010       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
7011         assert(FReg && "An FPR should be available when a GPR is reserved.");
7012         if (State.isVarArg()) {
7013           // Successfully reserved GPRs are only initialized for vararg calls.
7014           // Custom handling is required for:
7015           //   f64 in PPC32 needs to be split into 2 GPRs.
7016           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
7017           State.addLoc(
7018               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7019         }
7020       } else {
7021         // If there are insufficient GPRs, the PSA needs to be initialized.
7022         // Initialization occurs even if an FPR was initialized for
7023         // compatibility with the AIX XL compiler. The full memory for the
7024         // argument will be initialized even if a prior word is saved in GPR.
7025         // A custom memLoc is used when the argument also passes in FPR so
7026         // that the callee handling can skip over it easily.
7027         State.addLoc(
7028             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
7029                                              LocInfo)
7030                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7031         break;
7032       }
7033     }
7034 
7035     return false;
7036   }
7037   }
7038   return true;
7039 }
7040 
7041 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
7042                                                     bool IsPPC64) {
7043   assert((IsPPC64 || SVT != MVT::i64) &&
7044          "i64 should have been split for 32-bit codegen.");
7045 
7046   switch (SVT) {
7047   default:
7048     report_fatal_error("Unexpected value type for formal argument");
7049   case MVT::i1:
7050   case MVT::i32:
7051   case MVT::i64:
7052     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7053   case MVT::f32:
7054     return &PPC::F4RCRegClass;
7055   case MVT::f64:
7056     return &PPC::F8RCRegClass;
7057   }
7058 }
7059 
7060 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7061                                         SelectionDAG &DAG, SDValue ArgValue,
7062                                         MVT LocVT, const SDLoc &dl) {
7063   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7064   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7065 
7066   if (Flags.isSExt())
7067     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7068                            DAG.getValueType(ValVT));
7069   else if (Flags.isZExt())
7070     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7071                            DAG.getValueType(ValVT));
7072 
7073   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7074 }
7075 
7076 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7077   const unsigned LASize = FL->getLinkageSize();
7078 
7079   if (PPC::GPRCRegClass.contains(Reg)) {
7080     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7081            "Reg must be a valid argument register!");
7082     return LASize + 4 * (Reg - PPC::R3);
7083   }
7084 
7085   if (PPC::G8RCRegClass.contains(Reg)) {
7086     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7087            "Reg must be a valid argument register!");
7088     return LASize + 8 * (Reg - PPC::X3);
7089   }
7090 
7091   llvm_unreachable("Only general purpose registers expected.");
7092 }
7093 
7094 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7095     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7096     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7097     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7098 
7099   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7100           CallConv == CallingConv::Fast) &&
7101          "Unexpected calling convention!");
7102 
7103   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7104     report_fatal_error("Tail call support is unimplemented on AIX.");
7105 
7106   if (useSoftFloat())
7107     report_fatal_error("Soft float support is unimplemented on AIX.");
7108 
7109   const PPCSubtarget &Subtarget =
7110       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7111   if (Subtarget.hasQPX())
7112     report_fatal_error("QPX support is not supported on AIX.");
7113 
7114   const bool IsPPC64 = Subtarget.isPPC64();
7115   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7116 
7117   // Assign locations to all of the incoming arguments.
7118   SmallVector<CCValAssign, 16> ArgLocs;
7119   MachineFunction &MF = DAG.getMachineFunction();
7120   MachineFrameInfo &MFI = MF.getFrameInfo();
7121   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7122 
7123   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7124   // Reserve space for the linkage area on the stack.
7125   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7126   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7127   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7128 
7129   SmallVector<SDValue, 8> MemOps;
7130 
7131   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7132     CCValAssign &VA = ArgLocs[I++];
7133     MVT LocVT = VA.getLocVT();
7134     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7135 
7136     // For compatibility with the AIX XL compiler, the float args in the
7137     // parameter save area are initialized even if the argument is available
7138     // in register.  The caller is required to initialize both the register
7139     // and memory, however, the callee can choose to expect it in either.
7140     // The memloc is dismissed here because the argument is retrieved from
7141     // the register.
7142     if (VA.isMemLoc() && VA.needsCustom())
7143       continue;
7144 
7145     if (Flags.isByVal() && VA.isMemLoc()) {
7146       const unsigned Size =
7147           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7148                   PtrByteSize);
7149       const int FI = MF.getFrameInfo().CreateFixedObject(
7150           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7151           /* IsAliased */ true);
7152       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7153       InVals.push_back(FIN);
7154 
7155       continue;
7156     }
7157 
7158     if (Flags.isByVal()) {
7159       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7160 
7161       const MCPhysReg ArgReg = VA.getLocReg();
7162       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7163 
7164       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7165         report_fatal_error("Over aligned byvals not supported yet.");
7166 
7167       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7168       const int FI = MF.getFrameInfo().CreateFixedObject(
7169           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7170           /* IsAliased */ true);
7171       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7172       InVals.push_back(FIN);
7173 
7174       // Add live ins for all the RegLocs for the same ByVal.
7175       const TargetRegisterClass *RegClass =
7176           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7177 
7178       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7179                                                unsigned Offset) {
7180         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7181         // Since the callers side has left justified the aggregate in the
7182         // register, we can simply store the entire register into the stack
7183         // slot.
7184         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7185         // The store to the fixedstack object is needed becuase accessing a
7186         // field of the ByVal will use a gep and load. Ideally we will optimize
7187         // to extracting the value from the register directly, and elide the
7188         // stores when the arguments address is not taken, but that will need to
7189         // be future work.
7190         SDValue Store =
7191             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7192                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7193                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7194 
7195         MemOps.push_back(Store);
7196       };
7197 
7198       unsigned Offset = 0;
7199       HandleRegLoc(VA.getLocReg(), Offset);
7200       Offset += PtrByteSize;
7201       for (; Offset != StackSize; Offset += PtrByteSize) {
7202         assert(I != End &&
7203                "Expecting enough RegLocs to copy entire ByVal arg.");
7204 
7205         if (!ArgLocs[I].isRegLoc())
7206           report_fatal_error("Passing ByVals split between registers and stack "
7207                              "not yet implemented.");
7208 
7209         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7210                "Expecting more RegLocs for ByVal argument.");
7211 
7212         const CCValAssign RL = ArgLocs[I++];
7213         HandleRegLoc(RL.getLocReg(), Offset);
7214       }
7215       continue;
7216     }
7217 
7218     EVT ValVT = VA.getValVT();
7219     if (VA.isRegLoc() && !VA.needsCustom()) {
7220       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7221       unsigned VReg =
7222           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7223       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7224       if (ValVT.isScalarInteger() &&
7225           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7226         ArgValue =
7227             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7228       }
7229       InVals.push_back(ArgValue);
7230       continue;
7231     }
7232     if (VA.isMemLoc()) {
7233       const unsigned LocSize = LocVT.getStoreSize();
7234       const unsigned ValSize = ValVT.getStoreSize();
7235       assert((ValSize <= LocSize) &&
7236              "Object size is larger than size of MemLoc");
7237       int CurArgOffset = VA.getLocMemOffset();
7238       // Objects are right-justified because AIX is big-endian.
7239       if (LocSize > ValSize)
7240         CurArgOffset += LocSize - ValSize;
7241       // Potential tail calls could cause overwriting of argument stack slots.
7242       const bool IsImmutable =
7243           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7244             (CallConv == CallingConv::Fast));
7245       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7246       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7247       SDValue ArgValue =
7248           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7249       InVals.push_back(ArgValue);
7250       continue;
7251     }
7252   }
7253 
7254   // On AIX a minimum of 8 words is saved to the parameter save area.
7255   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7256   // Area that is at least reserved in the caller of this function.
7257   unsigned CallerReservedArea =
7258       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7259 
7260   // Set the size that is at least reserved in caller of this function. Tail
7261   // call optimized function's reserved stack space needs to be aligned so
7262   // that taking the difference between two stack areas will result in an
7263   // aligned stack.
7264   CallerReservedArea =
7265       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7266   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7267   FuncInfo->setMinReservedArea(CallerReservedArea);
7268 
7269   if (isVarArg) {
7270     FuncInfo->setVarArgsFrameIndex(
7271         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7272     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7273 
7274     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7275                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7276 
7277     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7278                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7279     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7280 
7281     // The fixed integer arguments of a variadic function are stored to the
7282     // VarArgsFrameIndex on the stack so that they may be loaded by
7283     // dereferencing the result of va_next.
7284     for (unsigned GPRIndex =
7285              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7286          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7287 
7288       const unsigned VReg =
7289           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7290                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7291 
7292       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7293       SDValue Store =
7294           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7295       MemOps.push_back(Store);
7296       // Increment the address for the next argument to store.
7297       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7298       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7299     }
7300   }
7301 
7302   if (!MemOps.empty())
7303     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7304 
7305   return Chain;
7306 }
7307 
7308 SDValue PPCTargetLowering::LowerCall_AIX(
7309     SDValue Chain, SDValue Callee, CallFlags CFlags,
7310     const SmallVectorImpl<ISD::OutputArg> &Outs,
7311     const SmallVectorImpl<SDValue> &OutVals,
7312     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7313     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7314     const CallBase *CB) const {
7315 
7316   assert((CFlags.CallConv == CallingConv::C ||
7317           CFlags.CallConv == CallingConv::Cold ||
7318           CFlags.CallConv == CallingConv::Fast) &&
7319          "Unexpected calling convention!");
7320 
7321   if (CFlags.IsPatchPoint)
7322     report_fatal_error("This call type is unimplemented on AIX.");
7323 
7324   const PPCSubtarget& Subtarget =
7325       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7326   if (Subtarget.hasQPX())
7327     report_fatal_error("QPX is not supported on AIX.");
7328   if (Subtarget.hasAltivec())
7329     report_fatal_error("Altivec support is unimplemented on AIX.");
7330 
7331   MachineFunction &MF = DAG.getMachineFunction();
7332   SmallVector<CCValAssign, 16> ArgLocs;
7333   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7334                  *DAG.getContext());
7335 
7336   // Reserve space for the linkage save area (LSA) on the stack.
7337   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7338   //   [SP][CR][LR][2 x reserved][TOC].
7339   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7340   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7341   const bool IsPPC64 = Subtarget.isPPC64();
7342   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7343   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7344   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7345   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7346 
7347   // The prolog code of the callee may store up to 8 GPR argument registers to
7348   // the stack, allowing va_start to index over them in memory if the callee
7349   // is variadic.
7350   // Because we cannot tell if this is needed on the caller side, we have to
7351   // conservatively assume that it is needed.  As such, make sure we have at
7352   // least enough stack space for the caller to store the 8 GPRs.
7353   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7354   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7355                                      CCInfo.getNextStackOffset());
7356 
7357   // Adjust the stack pointer for the new arguments...
7358   // These operations are automatically eliminated by the prolog/epilog pass.
7359   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7360   SDValue CallSeqStart = Chain;
7361 
7362   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7363   SmallVector<SDValue, 8> MemOpChains;
7364 
7365   // Set up a copy of the stack pointer for loading and storing any
7366   // arguments that may not fit in the registers available for argument
7367   // passing.
7368   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7369                                    : DAG.getRegister(PPC::R1, MVT::i32);
7370 
7371   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7372     const unsigned ValNo = ArgLocs[I].getValNo();
7373     SDValue Arg = OutVals[ValNo];
7374     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7375 
7376     if (Flags.isByVal()) {
7377       const unsigned ByValSize = Flags.getByValSize();
7378 
7379       // Nothing to do for zero-sized ByVals on the caller side.
7380       if (!ByValSize) {
7381         ++I;
7382         continue;
7383       }
7384 
7385       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7386         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7387                               (LoadOffset != 0)
7388                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7389                                   : Arg,
7390                               MachinePointerInfo(), VT);
7391       };
7392 
7393       unsigned LoadOffset = 0;
7394 
7395       // Initialize registers, which are fully occupied by the by-val argument.
7396       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7397         SDValue Load = GetLoad(PtrVT, LoadOffset);
7398         MemOpChains.push_back(Load.getValue(1));
7399         LoadOffset += PtrByteSize;
7400         const CCValAssign &ByValVA = ArgLocs[I++];
7401         assert(ByValVA.getValNo() == ValNo &&
7402                "Unexpected location for pass-by-value argument.");
7403         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7404       }
7405 
7406       if (LoadOffset == ByValSize)
7407         continue;
7408 
7409       // There must be one more loc to handle the remainder.
7410       assert(ArgLocs[I].getValNo() == ValNo &&
7411              "Expected additional location for by-value argument.");
7412 
7413       if (ArgLocs[I].isMemLoc()) {
7414         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7415         const CCValAssign &ByValVA = ArgLocs[I++];
7416         ISD::ArgFlagsTy MemcpyFlags = Flags;
7417         // Only memcpy the bytes that don't pass in register.
7418         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7419         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7420             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7421                               : Arg,
7422             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7423             CallSeqStart, MemcpyFlags, DAG, dl);
7424         continue;
7425       }
7426 
7427       // Initialize the final register residue.
7428       // Any residue that occupies the final by-val arg register must be
7429       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7430       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7431       // 2 and 1 byte loads.
7432       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7433       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7434              "Unexpected register residue for by-value argument.");
7435       SDValue ResidueVal;
7436       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7437         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7438         const MVT VT =
7439             N == 1 ? MVT::i8
7440                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7441         SDValue Load = GetLoad(VT, LoadOffset);
7442         MemOpChains.push_back(Load.getValue(1));
7443         LoadOffset += N;
7444         Bytes += N;
7445 
7446         // By-val arguments are passed left-justfied in register.
7447         // Every load here needs to be shifted, otherwise a full register load
7448         // should have been used.
7449         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7450                "Unexpected load emitted during handling of pass-by-value "
7451                "argument.");
7452         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7453         EVT ShiftAmountTy =
7454             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7455         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7456         SDValue ShiftedLoad =
7457             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7458         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7459                                               ShiftedLoad)
7460                                 : ShiftedLoad;
7461       }
7462 
7463       const CCValAssign &ByValVA = ArgLocs[I++];
7464       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7465       continue;
7466     }
7467 
7468     CCValAssign &VA = ArgLocs[I++];
7469     const MVT LocVT = VA.getLocVT();
7470     const MVT ValVT = VA.getValVT();
7471 
7472     switch (VA.getLocInfo()) {
7473     default:
7474       report_fatal_error("Unexpected argument extension type.");
7475     case CCValAssign::Full:
7476       break;
7477     case CCValAssign::ZExt:
7478       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7479       break;
7480     case CCValAssign::SExt:
7481       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7482       break;
7483     }
7484 
7485     if (VA.isRegLoc() && !VA.needsCustom()) {
7486       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7487       continue;
7488     }
7489 
7490     if (VA.isMemLoc()) {
7491       SDValue PtrOff =
7492           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7493       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7494       MemOpChains.push_back(
7495           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7496 
7497       continue;
7498     }
7499 
7500     // Custom handling is used for GPR initializations for vararg float
7501     // arguments.
7502     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7503            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7504            "Unexpected register handling for calling convention.");
7505 
7506     SDValue ArgAsInt =
7507         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7508 
7509     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7510       // f32 in 32-bit GPR
7511       // f64 in 64-bit GPR
7512       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7513     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7514       // f32 in 64-bit GPR.
7515       RegsToPass.push_back(std::make_pair(
7516           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7517     else {
7518       // f64 in two 32-bit GPRs
7519       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7520       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7521              "Unexpected custom register for argument!");
7522       CCValAssign &GPR1 = VA;
7523       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7524                                      DAG.getConstant(32, dl, MVT::i8));
7525       RegsToPass.push_back(std::make_pair(
7526           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7527 
7528       if (I != E) {
7529         // If only 1 GPR was available, there will only be one custom GPR and
7530         // the argument will also pass in memory.
7531         CCValAssign &PeekArg = ArgLocs[I];
7532         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7533           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7534           CCValAssign &GPR2 = ArgLocs[I++];
7535           RegsToPass.push_back(std::make_pair(
7536               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7537         }
7538       }
7539     }
7540   }
7541 
7542   if (!MemOpChains.empty())
7543     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7544 
7545   // For indirect calls, we need to save the TOC base to the stack for
7546   // restoration after the call.
7547   if (CFlags.IsIndirect) {
7548     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7549     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7550     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7551     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7552     const unsigned TOCSaveOffset =
7553         Subtarget.getFrameLowering()->getTOCSaveOffset();
7554 
7555     setUsesTOCBasePtr(DAG);
7556     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7557     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7558     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7559     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7560     Chain = DAG.getStore(
7561         Val.getValue(1), dl, Val, AddPtr,
7562         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7563   }
7564 
7565   // Build a sequence of copy-to-reg nodes chained together with token chain
7566   // and flag operands which copy the outgoing args into the appropriate regs.
7567   SDValue InFlag;
7568   for (auto Reg : RegsToPass) {
7569     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7570     InFlag = Chain.getValue(1);
7571   }
7572 
7573   const int SPDiff = 0;
7574   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7575                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7576 }
7577 
7578 bool
7579 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7580                                   MachineFunction &MF, bool isVarArg,
7581                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7582                                   LLVMContext &Context) const {
7583   SmallVector<CCValAssign, 16> RVLocs;
7584   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7585   return CCInfo.CheckReturn(
7586       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7587                 ? RetCC_PPC_Cold
7588                 : RetCC_PPC);
7589 }
7590 
7591 SDValue
7592 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7593                                bool isVarArg,
7594                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7595                                const SmallVectorImpl<SDValue> &OutVals,
7596                                const SDLoc &dl, SelectionDAG &DAG) const {
7597   SmallVector<CCValAssign, 16> RVLocs;
7598   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7599                  *DAG.getContext());
7600   CCInfo.AnalyzeReturn(Outs,
7601                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7602                            ? RetCC_PPC_Cold
7603                            : RetCC_PPC);
7604 
7605   SDValue Flag;
7606   SmallVector<SDValue, 4> RetOps(1, Chain);
7607 
7608   // Copy the result values into the output registers.
7609   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7610     CCValAssign &VA = RVLocs[i];
7611     assert(VA.isRegLoc() && "Can only return in registers!");
7612 
7613     SDValue Arg = OutVals[RealResIdx];
7614 
7615     switch (VA.getLocInfo()) {
7616     default: llvm_unreachable("Unknown loc info!");
7617     case CCValAssign::Full: break;
7618     case CCValAssign::AExt:
7619       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7620       break;
7621     case CCValAssign::ZExt:
7622       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7623       break;
7624     case CCValAssign::SExt:
7625       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7626       break;
7627     }
7628     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7629       bool isLittleEndian = Subtarget.isLittleEndian();
7630       // Legalize ret f64 -> ret 2 x i32.
7631       SDValue SVal =
7632           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7633                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7634       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7635       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7636       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7637                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7638       Flag = Chain.getValue(1);
7639       VA = RVLocs[++i]; // skip ahead to next loc
7640       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7641     } else
7642       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7643     Flag = Chain.getValue(1);
7644     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7645   }
7646 
7647   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7648   const MCPhysReg *I =
7649     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7650   if (I) {
7651     for (; *I; ++I) {
7652 
7653       if (PPC::G8RCRegClass.contains(*I))
7654         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7655       else if (PPC::F8RCRegClass.contains(*I))
7656         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7657       else if (PPC::CRRCRegClass.contains(*I))
7658         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7659       else if (PPC::VRRCRegClass.contains(*I))
7660         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7661       else
7662         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7663     }
7664   }
7665 
7666   RetOps[0] = Chain;  // Update chain.
7667 
7668   // Add the flag if we have it.
7669   if (Flag.getNode())
7670     RetOps.push_back(Flag);
7671 
7672   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7673 }
7674 
7675 SDValue
7676 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7677                                                 SelectionDAG &DAG) const {
7678   SDLoc dl(Op);
7679 
7680   // Get the correct type for integers.
7681   EVT IntVT = Op.getValueType();
7682 
7683   // Get the inputs.
7684   SDValue Chain = Op.getOperand(0);
7685   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7686   // Build a DYNAREAOFFSET node.
7687   SDValue Ops[2] = {Chain, FPSIdx};
7688   SDVTList VTs = DAG.getVTList(IntVT);
7689   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7690 }
7691 
7692 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7693                                              SelectionDAG &DAG) const {
7694   // When we pop the dynamic allocation we need to restore the SP link.
7695   SDLoc dl(Op);
7696 
7697   // Get the correct type for pointers.
7698   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7699 
7700   // Construct the stack pointer operand.
7701   bool isPPC64 = Subtarget.isPPC64();
7702   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7703   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7704 
7705   // Get the operands for the STACKRESTORE.
7706   SDValue Chain = Op.getOperand(0);
7707   SDValue SaveSP = Op.getOperand(1);
7708 
7709   // Load the old link SP.
7710   SDValue LoadLinkSP =
7711       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7712 
7713   // Restore the stack pointer.
7714   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7715 
7716   // Store the old link SP.
7717   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7718 }
7719 
7720 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7721   MachineFunction &MF = DAG.getMachineFunction();
7722   bool isPPC64 = Subtarget.isPPC64();
7723   EVT PtrVT = getPointerTy(MF.getDataLayout());
7724 
7725   // Get current frame pointer save index.  The users of this index will be
7726   // primarily DYNALLOC instructions.
7727   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7728   int RASI = FI->getReturnAddrSaveIndex();
7729 
7730   // If the frame pointer save index hasn't been defined yet.
7731   if (!RASI) {
7732     // Find out what the fix offset of the frame pointer save area.
7733     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7734     // Allocate the frame index for frame pointer save area.
7735     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7736     // Save the result.
7737     FI->setReturnAddrSaveIndex(RASI);
7738   }
7739   return DAG.getFrameIndex(RASI, PtrVT);
7740 }
7741 
7742 SDValue
7743 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7744   MachineFunction &MF = DAG.getMachineFunction();
7745   bool isPPC64 = Subtarget.isPPC64();
7746   EVT PtrVT = getPointerTy(MF.getDataLayout());
7747 
7748   // Get current frame pointer save index.  The users of this index will be
7749   // primarily DYNALLOC instructions.
7750   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7751   int FPSI = FI->getFramePointerSaveIndex();
7752 
7753   // If the frame pointer save index hasn't been defined yet.
7754   if (!FPSI) {
7755     // Find out what the fix offset of the frame pointer save area.
7756     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7757     // Allocate the frame index for frame pointer save area.
7758     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7759     // Save the result.
7760     FI->setFramePointerSaveIndex(FPSI);
7761   }
7762   return DAG.getFrameIndex(FPSI, PtrVT);
7763 }
7764 
7765 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7766                                                    SelectionDAG &DAG) const {
7767   // Get the inputs.
7768   SDValue Chain = Op.getOperand(0);
7769   SDValue Size  = Op.getOperand(1);
7770   SDLoc dl(Op);
7771 
7772   // Get the correct type for pointers.
7773   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7774   // Negate the size.
7775   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7776                                 DAG.getConstant(0, dl, PtrVT), Size);
7777   // Construct a node for the frame pointer save index.
7778   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7779   // Build a DYNALLOC node.
7780   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7781   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7782   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7783 }
7784 
7785 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7786                                                      SelectionDAG &DAG) const {
7787   MachineFunction &MF = DAG.getMachineFunction();
7788 
7789   bool isPPC64 = Subtarget.isPPC64();
7790   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7791 
7792   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7793   return DAG.getFrameIndex(FI, PtrVT);
7794 }
7795 
7796 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7797                                                SelectionDAG &DAG) const {
7798   SDLoc DL(Op);
7799   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7800                      DAG.getVTList(MVT::i32, MVT::Other),
7801                      Op.getOperand(0), Op.getOperand(1));
7802 }
7803 
7804 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7805                                                 SelectionDAG &DAG) const {
7806   SDLoc DL(Op);
7807   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7808                      Op.getOperand(0), Op.getOperand(1));
7809 }
7810 
7811 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7812   if (Op.getValueType().isVector())
7813     return LowerVectorLoad(Op, DAG);
7814 
7815   assert(Op.getValueType() == MVT::i1 &&
7816          "Custom lowering only for i1 loads");
7817 
7818   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7819 
7820   SDLoc dl(Op);
7821   LoadSDNode *LD = cast<LoadSDNode>(Op);
7822 
7823   SDValue Chain = LD->getChain();
7824   SDValue BasePtr = LD->getBasePtr();
7825   MachineMemOperand *MMO = LD->getMemOperand();
7826 
7827   SDValue NewLD =
7828       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7829                      BasePtr, MVT::i8, MMO);
7830   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7831 
7832   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7833   return DAG.getMergeValues(Ops, dl);
7834 }
7835 
7836 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7837   if (Op.getOperand(1).getValueType().isVector())
7838     return LowerVectorStore(Op, DAG);
7839 
7840   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7841          "Custom lowering only for i1 stores");
7842 
7843   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7844 
7845   SDLoc dl(Op);
7846   StoreSDNode *ST = cast<StoreSDNode>(Op);
7847 
7848   SDValue Chain = ST->getChain();
7849   SDValue BasePtr = ST->getBasePtr();
7850   SDValue Value = ST->getValue();
7851   MachineMemOperand *MMO = ST->getMemOperand();
7852 
7853   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7854                       Value);
7855   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7856 }
7857 
7858 // FIXME: Remove this once the ANDI glue bug is fixed:
7859 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7860   assert(Op.getValueType() == MVT::i1 &&
7861          "Custom lowering only for i1 results");
7862 
7863   SDLoc DL(Op);
7864   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7865 }
7866 
7867 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7868                                                SelectionDAG &DAG) const {
7869 
7870   // Implements a vector truncate that fits in a vector register as a shuffle.
7871   // We want to legalize vector truncates down to where the source fits in
7872   // a vector register (and target is therefore smaller than vector register
7873   // size).  At that point legalization will try to custom lower the sub-legal
7874   // result and get here - where we can contain the truncate as a single target
7875   // operation.
7876 
7877   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7878   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7879   //
7880   // We will implement it for big-endian ordering as this (where x denotes
7881   // undefined):
7882   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7883   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7884   //
7885   // The same operation in little-endian ordering will be:
7886   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7887   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7888 
7889   assert(Op.getValueType().isVector() && "Vector type expected.");
7890 
7891   SDLoc DL(Op);
7892   SDValue N1 = Op.getOperand(0);
7893   unsigned SrcSize = N1.getValueType().getSizeInBits();
7894   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7895   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7896 
7897   EVT TrgVT = Op.getValueType();
7898   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7899   EVT EltVT = TrgVT.getVectorElementType();
7900   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7901   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7902 
7903   // First list the elements we want to keep.
7904   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7905   SmallVector<int, 16> ShuffV;
7906   if (Subtarget.isLittleEndian())
7907     for (unsigned i = 0; i < TrgNumElts; ++i)
7908       ShuffV.push_back(i * SizeMult);
7909   else
7910     for (unsigned i = 1; i <= TrgNumElts; ++i)
7911       ShuffV.push_back(i * SizeMult - 1);
7912 
7913   // Populate the remaining elements with undefs.
7914   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7915     // ShuffV.push_back(i + WideNumElts);
7916     ShuffV.push_back(WideNumElts + 1);
7917 
7918   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7919   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7920 }
7921 
7922 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7923 /// possible.
7924 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7925   // Not FP? Not a fsel.
7926   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7927       !Op.getOperand(2).getValueType().isFloatingPoint())
7928     return Op;
7929 
7930   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7931 
7932   EVT ResVT = Op.getValueType();
7933   EVT CmpVT = Op.getOperand(0).getValueType();
7934   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7935   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7936   SDLoc dl(Op);
7937 
7938   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7939   // presence of infinities.
7940   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7941     switch (CC) {
7942     default:
7943       break;
7944     case ISD::SETOGT:
7945     case ISD::SETGT:
7946       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7947     case ISD::SETOLT:
7948     case ISD::SETLT:
7949       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7950     }
7951   }
7952 
7953   // We might be able to do better than this under some circumstances, but in
7954   // general, fsel-based lowering of select is a finite-math-only optimization.
7955   // For more information, see section F.3 of the 2.06 ISA specification.
7956   // With ISA 3.0
7957   if (!DAG.getTarget().Options.NoInfsFPMath ||
7958       !DAG.getTarget().Options.NoNaNsFPMath)
7959     return Op;
7960 
7961   // TODO: Propagate flags from the select rather than global settings.
7962   SDNodeFlags Flags;
7963   Flags.setNoInfs(true);
7964   Flags.setNoNaNs(true);
7965 
7966   // If the RHS of the comparison is a 0.0, we don't need to do the
7967   // subtraction at all.
7968   SDValue Sel1;
7969   if (isFloatingPointZero(RHS))
7970     switch (CC) {
7971     default: break;       // SETUO etc aren't handled by fsel.
7972     case ISD::SETNE:
7973       std::swap(TV, FV);
7974       LLVM_FALLTHROUGH;
7975     case ISD::SETEQ:
7976       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7977         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7978       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7979       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7980         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7981       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7982                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7983     case ISD::SETULT:
7984     case ISD::SETLT:
7985       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7986       LLVM_FALLTHROUGH;
7987     case ISD::SETOGE:
7988     case ISD::SETGE:
7989       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7990         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7991       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7992     case ISD::SETUGT:
7993     case ISD::SETGT:
7994       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7995       LLVM_FALLTHROUGH;
7996     case ISD::SETOLE:
7997     case ISD::SETLE:
7998       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7999         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8000       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8001                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8002     }
8003 
8004   SDValue Cmp;
8005   switch (CC) {
8006   default: break;       // SETUO etc aren't handled by fsel.
8007   case ISD::SETNE:
8008     std::swap(TV, FV);
8009     LLVM_FALLTHROUGH;
8010   case ISD::SETEQ:
8011     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8012     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8013       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8014     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8015     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8016       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8017     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8018                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8019   case ISD::SETULT:
8020   case ISD::SETLT:
8021     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8022     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8023       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8024     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8025   case ISD::SETOGE:
8026   case ISD::SETGE:
8027     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8028     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8029       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8030     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8031   case ISD::SETUGT:
8032   case ISD::SETGT:
8033     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8034     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8035       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8036     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8037   case ISD::SETOLE:
8038   case ISD::SETLE:
8039     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8040     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8041       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8042     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8043   }
8044   return Op;
8045 }
8046 
8047 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8048                                                SelectionDAG &DAG,
8049                                                const SDLoc &dl) const {
8050   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8051   SDValue Src = Op.getOperand(0);
8052   if (Src.getValueType() == MVT::f32)
8053     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8054 
8055   SDValue Tmp;
8056   switch (Op.getSimpleValueType().SimpleTy) {
8057   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8058   case MVT::i32:
8059     Tmp = DAG.getNode(
8060         Op.getOpcode() == ISD::FP_TO_SINT
8061             ? PPCISD::FCTIWZ
8062             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8063         dl, MVT::f64, Src);
8064     break;
8065   case MVT::i64:
8066     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8067            "i64 FP_TO_UINT is supported only with FPCVT");
8068     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8069                                                         PPCISD::FCTIDUZ,
8070                       dl, MVT::f64, Src);
8071     break;
8072   }
8073 
8074   // Convert the FP value to an int value through memory.
8075   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8076     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
8077   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8078   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8079   MachinePointerInfo MPI =
8080       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8081 
8082   // Emit a store to the stack slot.
8083   SDValue Chain;
8084   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8085   if (i32Stack) {
8086     MachineFunction &MF = DAG.getMachineFunction();
8087     Alignment = Align(4);
8088     MachineMemOperand *MMO =
8089         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8090     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
8091     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8092               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8093   } else
8094     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
8095 
8096   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8097   // add in a bias on big endian.
8098   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8099     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8100                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8101     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8102   }
8103 
8104   RLI.Chain = Chain;
8105   RLI.Ptr = FIPtr;
8106   RLI.MPI = MPI;
8107   RLI.Alignment = Alignment;
8108 }
8109 
8110 /// Custom lowers floating point to integer conversions to use
8111 /// the direct move instructions available in ISA 2.07 to avoid the
8112 /// need for load/store combinations.
8113 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8114                                                     SelectionDAG &DAG,
8115                                                     const SDLoc &dl) const {
8116   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8117   SDValue Src = Op.getOperand(0);
8118 
8119   if (Src.getValueType() == MVT::f32)
8120     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8121 
8122   SDValue Tmp;
8123   switch (Op.getSimpleValueType().SimpleTy) {
8124   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8125   case MVT::i32:
8126     Tmp = DAG.getNode(
8127         Op.getOpcode() == ISD::FP_TO_SINT
8128             ? PPCISD::FCTIWZ
8129             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
8130         dl, MVT::f64, Src);
8131     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
8132     break;
8133   case MVT::i64:
8134     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
8135            "i64 FP_TO_UINT is supported only with FPCVT");
8136     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8137                                                         PPCISD::FCTIDUZ,
8138                       dl, MVT::f64, Src);
8139     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
8140     break;
8141   }
8142   return Tmp;
8143 }
8144 
8145 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8146                                           const SDLoc &dl) const {
8147 
8148   // FP to INT conversions are legal for f128.
8149   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
8150     return Op;
8151 
8152   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8153   // PPC (the libcall is not available).
8154   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
8155     if (Op.getValueType() == MVT::i32) {
8156       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8157         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8158                                  MVT::f64, Op.getOperand(0),
8159                                  DAG.getIntPtrConstant(0, dl));
8160         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8161                                  MVT::f64, Op.getOperand(0),
8162                                  DAG.getIntPtrConstant(1, dl));
8163 
8164         // Add the two halves of the long double in round-to-zero mode.
8165         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8166 
8167         // Now use a smaller FP_TO_SINT.
8168         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8169       }
8170       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8171         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8172         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8173         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8174         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8175         // FIXME: generated code sucks.
8176         // TODO: Are there fast-math-flags to propagate to this FSUB?
8177         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
8178                                    Op.getOperand(0), Tmp);
8179         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8180         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8181                            DAG.getConstant(0x80000000, dl, MVT::i32));
8182         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
8183                                     Op.getOperand(0));
8184         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
8185                                ISD::SETGE);
8186       }
8187     }
8188 
8189     return SDValue();
8190   }
8191 
8192   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8193     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8194 
8195   ReuseLoadInfo RLI;
8196   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8197 
8198   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8199                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8200 }
8201 
8202 // We're trying to insert a regular store, S, and then a load, L. If the
8203 // incoming value, O, is a load, we might just be able to have our load use the
8204 // address used by O. However, we don't know if anything else will store to
8205 // that address before we can load from it. To prevent this situation, we need
8206 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8207 // the same chain operand as O, we create a token factor from the chain results
8208 // of O and L, and we replace all uses of O's chain result with that token
8209 // factor (see spliceIntoChain below for this last part).
8210 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8211                                             ReuseLoadInfo &RLI,
8212                                             SelectionDAG &DAG,
8213                                             ISD::LoadExtType ET) const {
8214   SDLoc dl(Op);
8215   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8216                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8217   if (ET == ISD::NON_EXTLOAD &&
8218       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8219       isOperationLegalOrCustom(Op.getOpcode(),
8220                                Op.getOperand(0).getValueType())) {
8221 
8222     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8223     return true;
8224   }
8225 
8226   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8227   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8228       LD->isNonTemporal())
8229     return false;
8230   if (LD->getMemoryVT() != MemVT)
8231     return false;
8232 
8233   RLI.Ptr = LD->getBasePtr();
8234   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8235     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8236            "Non-pre-inc AM on PPC?");
8237     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8238                           LD->getOffset());
8239   }
8240 
8241   RLI.Chain = LD->getChain();
8242   RLI.MPI = LD->getPointerInfo();
8243   RLI.IsDereferenceable = LD->isDereferenceable();
8244   RLI.IsInvariant = LD->isInvariant();
8245   RLI.Alignment = LD->getAlign();
8246   RLI.AAInfo = LD->getAAInfo();
8247   RLI.Ranges = LD->getRanges();
8248 
8249   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8250   return true;
8251 }
8252 
8253 // Given the head of the old chain, ResChain, insert a token factor containing
8254 // it and NewResChain, and make users of ResChain now be users of that token
8255 // factor.
8256 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8257 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8258                                         SDValue NewResChain,
8259                                         SelectionDAG &DAG) const {
8260   if (!ResChain)
8261     return;
8262 
8263   SDLoc dl(NewResChain);
8264 
8265   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8266                            NewResChain, DAG.getUNDEF(MVT::Other));
8267   assert(TF.getNode() != NewResChain.getNode() &&
8268          "A new TF really is required here");
8269 
8270   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8271   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8272 }
8273 
8274 /// Analyze profitability of direct move
8275 /// prefer float load to int load plus direct move
8276 /// when there is no integer use of int load
8277 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8278   SDNode *Origin = Op.getOperand(0).getNode();
8279   if (Origin->getOpcode() != ISD::LOAD)
8280     return true;
8281 
8282   // If there is no LXSIBZX/LXSIHZX, like Power8,
8283   // prefer direct move if the memory size is 1 or 2 bytes.
8284   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8285   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8286     return true;
8287 
8288   for (SDNode::use_iterator UI = Origin->use_begin(),
8289                             UE = Origin->use_end();
8290        UI != UE; ++UI) {
8291 
8292     // Only look at the users of the loaded value.
8293     if (UI.getUse().get().getResNo() != 0)
8294       continue;
8295 
8296     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8297         UI->getOpcode() != ISD::UINT_TO_FP)
8298       return true;
8299   }
8300 
8301   return false;
8302 }
8303 
8304 /// Custom lowers integer to floating point conversions to use
8305 /// the direct move instructions available in ISA 2.07 to avoid the
8306 /// need for load/store combinations.
8307 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8308                                                     SelectionDAG &DAG,
8309                                                     const SDLoc &dl) const {
8310   assert((Op.getValueType() == MVT::f32 ||
8311           Op.getValueType() == MVT::f64) &&
8312          "Invalid floating point type as target of conversion");
8313   assert(Subtarget.hasFPCVT() &&
8314          "Int to FP conversions with direct moves require FPCVT");
8315   SDValue FP;
8316   SDValue Src = Op.getOperand(0);
8317   bool SinglePrec = Op.getValueType() == MVT::f32;
8318   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8319   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8320   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
8321                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
8322 
8323   if (WordInt) {
8324     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
8325                      dl, MVT::f64, Src);
8326     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8327   }
8328   else {
8329     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
8330     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
8331   }
8332 
8333   return FP;
8334 }
8335 
8336 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8337 
8338   EVT VecVT = Vec.getValueType();
8339   assert(VecVT.isVector() && "Expected a vector type.");
8340   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8341 
8342   EVT EltVT = VecVT.getVectorElementType();
8343   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8344   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8345 
8346   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8347   SmallVector<SDValue, 16> Ops(NumConcat);
8348   Ops[0] = Vec;
8349   SDValue UndefVec = DAG.getUNDEF(VecVT);
8350   for (unsigned i = 1; i < NumConcat; ++i)
8351     Ops[i] = UndefVec;
8352 
8353   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8354 }
8355 
8356 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8357                                                 const SDLoc &dl) const {
8358 
8359   unsigned Opc = Op.getOpcode();
8360   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8361          "Unexpected conversion type");
8362   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8363          "Supports conversions to v2f64/v4f32 only.");
8364 
8365   bool SignedConv = Opc == ISD::SINT_TO_FP;
8366   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8367 
8368   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8369   EVT WideVT = Wide.getValueType();
8370   unsigned WideNumElts = WideVT.getVectorNumElements();
8371   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8372 
8373   SmallVector<int, 16> ShuffV;
8374   for (unsigned i = 0; i < WideNumElts; ++i)
8375     ShuffV.push_back(i + WideNumElts);
8376 
8377   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8378   int SaveElts = FourEltRes ? 4 : 2;
8379   if (Subtarget.isLittleEndian())
8380     for (int i = 0; i < SaveElts; i++)
8381       ShuffV[i * Stride] = i;
8382   else
8383     for (int i = 1; i <= SaveElts; i++)
8384       ShuffV[i * Stride - 1] = i - 1;
8385 
8386   SDValue ShuffleSrc2 =
8387       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8388   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8389 
8390   SDValue Extend;
8391   if (SignedConv) {
8392     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8393     EVT ExtVT = Op.getOperand(0).getValueType();
8394     if (Subtarget.hasP9Altivec())
8395       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8396                                IntermediateVT.getVectorNumElements());
8397 
8398     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8399                          DAG.getValueType(ExtVT));
8400   } else
8401     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8402 
8403   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8404 }
8405 
8406 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8407                                           SelectionDAG &DAG) const {
8408   SDLoc dl(Op);
8409 
8410   EVT InVT = Op.getOperand(0).getValueType();
8411   EVT OutVT = Op.getValueType();
8412   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8413       isOperationCustom(Op.getOpcode(), InVT))
8414     return LowerINT_TO_FPVector(Op, DAG, dl);
8415 
8416   // Conversions to f128 are legal.
8417   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
8418     return Op;
8419 
8420   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
8421     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
8422       return SDValue();
8423 
8424     SDValue Value = Op.getOperand(0);
8425     // The values are now known to be -1 (false) or 1 (true). To convert this
8426     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8427     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8428     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8429 
8430     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8431 
8432     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8433 
8434     if (Op.getValueType() != MVT::v4f64)
8435       Value = DAG.getNode(ISD::FP_ROUND, dl,
8436                           Op.getValueType(), Value,
8437                           DAG.getIntPtrConstant(1, dl));
8438     return Value;
8439   }
8440 
8441   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8442   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8443     return SDValue();
8444 
8445   if (Op.getOperand(0).getValueType() == MVT::i1)
8446     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8447                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8448                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8449 
8450   // If we have direct moves, we can do all the conversion, skip the store/load
8451   // however, without FPCVT we can't do most conversions.
8452   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8453       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8454     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8455 
8456   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8457          "UINT_TO_FP is supported only with FPCVT");
8458 
8459   // If we have FCFIDS, then use it when converting to single-precision.
8460   // Otherwise, convert to double-precision and then round.
8461   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8462                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8463                                                             : PPCISD::FCFIDS)
8464                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8465                                                             : PPCISD::FCFID);
8466   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8467                   ? MVT::f32
8468                   : MVT::f64;
8469 
8470   if (Op.getOperand(0).getValueType() == MVT::i64) {
8471     SDValue SINT = Op.getOperand(0);
8472     // When converting to single-precision, we actually need to convert
8473     // to double-precision first and then round to single-precision.
8474     // To avoid double-rounding effects during that operation, we have
8475     // to prepare the input operand.  Bits that might be truncated when
8476     // converting to double-precision are replaced by a bit that won't
8477     // be lost at this stage, but is below the single-precision rounding
8478     // position.
8479     //
8480     // However, if -enable-unsafe-fp-math is in effect, accept double
8481     // rounding to avoid the extra overhead.
8482     if (Op.getValueType() == MVT::f32 &&
8483         !Subtarget.hasFPCVT() &&
8484         !DAG.getTarget().Options.UnsafeFPMath) {
8485 
8486       // Twiddle input to make sure the low 11 bits are zero.  (If this
8487       // is the case, we are guaranteed the value will fit into the 53 bit
8488       // mantissa of an IEEE double-precision value without rounding.)
8489       // If any of those low 11 bits were not zero originally, make sure
8490       // bit 12 (value 2048) is set instead, so that the final rounding
8491       // to single-precision gets the correct result.
8492       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8493                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8494       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8495                           Round, DAG.getConstant(2047, dl, MVT::i64));
8496       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8497       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8498                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8499 
8500       // However, we cannot use that value unconditionally: if the magnitude
8501       // of the input value is small, the bit-twiddling we did above might
8502       // end up visibly changing the output.  Fortunately, in that case, we
8503       // don't need to twiddle bits since the original input will convert
8504       // exactly to double-precision floating-point already.  Therefore,
8505       // construct a conditional to use the original value if the top 11
8506       // bits are all sign-bit copies, and use the rounded value computed
8507       // above otherwise.
8508       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8509                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8510       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8511                          Cond, DAG.getConstant(1, dl, MVT::i64));
8512       Cond = DAG.getSetCC(
8513           dl,
8514           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8515           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8516 
8517       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8518     }
8519 
8520     ReuseLoadInfo RLI;
8521     SDValue Bits;
8522 
8523     MachineFunction &MF = DAG.getMachineFunction();
8524     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8525       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8526                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8527       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8528     } else if (Subtarget.hasLFIWAX() &&
8529                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8530       MachineMemOperand *MMO =
8531         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8532                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8533       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8534       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8535                                      DAG.getVTList(MVT::f64, MVT::Other),
8536                                      Ops, MVT::i32, MMO);
8537       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8538     } else if (Subtarget.hasFPCVT() &&
8539                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8540       MachineMemOperand *MMO =
8541         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8542                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8543       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8544       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8545                                      DAG.getVTList(MVT::f64, MVT::Other),
8546                                      Ops, MVT::i32, MMO);
8547       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8548     } else if (((Subtarget.hasLFIWAX() &&
8549                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8550                 (Subtarget.hasFPCVT() &&
8551                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8552                SINT.getOperand(0).getValueType() == MVT::i32) {
8553       MachineFrameInfo &MFI = MF.getFrameInfo();
8554       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8555 
8556       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8557       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8558 
8559       SDValue Store =
8560           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8561                        MachinePointerInfo::getFixedStack(
8562                            DAG.getMachineFunction(), FrameIdx));
8563 
8564       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8565              "Expected an i32 store");
8566 
8567       RLI.Ptr = FIdx;
8568       RLI.Chain = Store;
8569       RLI.MPI =
8570           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8571       RLI.Alignment = Align(4);
8572 
8573       MachineMemOperand *MMO =
8574         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8575                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8576       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8577       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8578                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8579                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8580                                      Ops, MVT::i32, MMO);
8581     } else
8582       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8583 
8584     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8585 
8586     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8587       FP = DAG.getNode(ISD::FP_ROUND, dl,
8588                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8589     return FP;
8590   }
8591 
8592   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8593          "Unhandled INT_TO_FP type in custom expander!");
8594   // Since we only generate this in 64-bit mode, we can take advantage of
8595   // 64-bit registers.  In particular, sign extend the input value into the
8596   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8597   // then lfd it and fcfid it.
8598   MachineFunction &MF = DAG.getMachineFunction();
8599   MachineFrameInfo &MFI = MF.getFrameInfo();
8600   EVT PtrVT = getPointerTy(MF.getDataLayout());
8601 
8602   SDValue Ld;
8603   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8604     ReuseLoadInfo RLI;
8605     bool ReusingLoad;
8606     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8607                                             DAG))) {
8608       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8609       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8610 
8611       SDValue Store =
8612           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8613                        MachinePointerInfo::getFixedStack(
8614                            DAG.getMachineFunction(), FrameIdx));
8615 
8616       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8617              "Expected an i32 store");
8618 
8619       RLI.Ptr = FIdx;
8620       RLI.Chain = Store;
8621       RLI.MPI =
8622           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8623       RLI.Alignment = Align(4);
8624     }
8625 
8626     MachineMemOperand *MMO =
8627       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8628                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8629     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8630     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8631                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8632                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8633                                  Ops, MVT::i32, MMO);
8634     if (ReusingLoad)
8635       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8636   } else {
8637     assert(Subtarget.isPPC64() &&
8638            "i32->FP without LFIWAX supported only on PPC64");
8639 
8640     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8641     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8642 
8643     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8644                                 Op.getOperand(0));
8645 
8646     // STD the extended value into the stack slot.
8647     SDValue Store = DAG.getStore(
8648         DAG.getEntryNode(), dl, Ext64, FIdx,
8649         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8650 
8651     // Load the value as a double.
8652     Ld = DAG.getLoad(
8653         MVT::f64, dl, Store, FIdx,
8654         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8655   }
8656 
8657   // FCFID it and return it.
8658   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8659   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8660     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8661                      DAG.getIntPtrConstant(0, dl));
8662   return FP;
8663 }
8664 
8665 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8666                                             SelectionDAG &DAG) const {
8667   SDLoc dl(Op);
8668   /*
8669    The rounding mode is in bits 30:31 of FPSR, and has the following
8670    settings:
8671      00 Round to nearest
8672      01 Round to 0
8673      10 Round to +inf
8674      11 Round to -inf
8675 
8676   FLT_ROUNDS, on the other hand, expects the following:
8677     -1 Undefined
8678      0 Round to 0
8679      1 Round to nearest
8680      2 Round to +inf
8681      3 Round to -inf
8682 
8683   To perform the conversion, we do:
8684     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8685   */
8686 
8687   MachineFunction &MF = DAG.getMachineFunction();
8688   EVT VT = Op.getValueType();
8689   EVT PtrVT = getPointerTy(MF.getDataLayout());
8690 
8691   // Save FP Control Word to register
8692   SDValue Chain = Op.getOperand(0);
8693   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8694   Chain = MFFS.getValue(1);
8695 
8696   // Save FP register to stack slot
8697   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8698   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8699   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8700 
8701   // Load FP Control Word from low 32 bits of stack slot.
8702   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8703   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8704   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8705   Chain = CWD.getValue(1);
8706 
8707   // Transform as necessary
8708   SDValue CWD1 =
8709     DAG.getNode(ISD::AND, dl, MVT::i32,
8710                 CWD, DAG.getConstant(3, dl, MVT::i32));
8711   SDValue CWD2 =
8712     DAG.getNode(ISD::SRL, dl, MVT::i32,
8713                 DAG.getNode(ISD::AND, dl, MVT::i32,
8714                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8715                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8716                             DAG.getConstant(3, dl, MVT::i32)),
8717                 DAG.getConstant(1, dl, MVT::i32));
8718 
8719   SDValue RetVal =
8720     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8721 
8722   RetVal =
8723       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8724                   dl, VT, RetVal);
8725 
8726   return DAG.getMergeValues({RetVal, Chain}, dl);
8727 }
8728 
8729 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8730   EVT VT = Op.getValueType();
8731   unsigned BitWidth = VT.getSizeInBits();
8732   SDLoc dl(Op);
8733   assert(Op.getNumOperands() == 3 &&
8734          VT == Op.getOperand(1).getValueType() &&
8735          "Unexpected SHL!");
8736 
8737   // Expand into a bunch of logical ops.  Note that these ops
8738   // depend on the PPC behavior for oversized shift amounts.
8739   SDValue Lo = Op.getOperand(0);
8740   SDValue Hi = Op.getOperand(1);
8741   SDValue Amt = Op.getOperand(2);
8742   EVT AmtVT = Amt.getValueType();
8743 
8744   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8745                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8746   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8747   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8748   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8749   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8750                              DAG.getConstant(-BitWidth, dl, AmtVT));
8751   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8752   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8753   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8754   SDValue OutOps[] = { OutLo, OutHi };
8755   return DAG.getMergeValues(OutOps, dl);
8756 }
8757 
8758 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8759   EVT VT = Op.getValueType();
8760   SDLoc dl(Op);
8761   unsigned BitWidth = VT.getSizeInBits();
8762   assert(Op.getNumOperands() == 3 &&
8763          VT == Op.getOperand(1).getValueType() &&
8764          "Unexpected SRL!");
8765 
8766   // Expand into a bunch of logical ops.  Note that these ops
8767   // depend on the PPC behavior for oversized shift amounts.
8768   SDValue Lo = Op.getOperand(0);
8769   SDValue Hi = Op.getOperand(1);
8770   SDValue Amt = Op.getOperand(2);
8771   EVT AmtVT = Amt.getValueType();
8772 
8773   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8774                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8775   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8776   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8777   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8778   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8779                              DAG.getConstant(-BitWidth, dl, AmtVT));
8780   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8781   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8782   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8783   SDValue OutOps[] = { OutLo, OutHi };
8784   return DAG.getMergeValues(OutOps, dl);
8785 }
8786 
8787 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8788   SDLoc dl(Op);
8789   EVT VT = Op.getValueType();
8790   unsigned BitWidth = VT.getSizeInBits();
8791   assert(Op.getNumOperands() == 3 &&
8792          VT == Op.getOperand(1).getValueType() &&
8793          "Unexpected SRA!");
8794 
8795   // Expand into a bunch of logical ops, followed by a select_cc.
8796   SDValue Lo = Op.getOperand(0);
8797   SDValue Hi = Op.getOperand(1);
8798   SDValue Amt = Op.getOperand(2);
8799   EVT AmtVT = Amt.getValueType();
8800 
8801   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8802                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8803   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8804   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8805   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8806   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8807                              DAG.getConstant(-BitWidth, dl, AmtVT));
8808   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8809   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8810   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8811                                   Tmp4, Tmp6, ISD::SETLE);
8812   SDValue OutOps[] = { OutLo, OutHi };
8813   return DAG.getMergeValues(OutOps, dl);
8814 }
8815 
8816 //===----------------------------------------------------------------------===//
8817 // Vector related lowering.
8818 //
8819 
8820 /// BuildSplatI - Build a canonical splati of Val with an element size of
8821 /// SplatSize.  Cast the result to VT.
8822 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8823                            SelectionDAG &DAG, const SDLoc &dl) {
8824   static const MVT VTys[] = { // canonical VT to use for each size.
8825     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8826   };
8827 
8828   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8829 
8830   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8831   if (Val == -1)
8832     SplatSize = 1;
8833 
8834   EVT CanonicalVT = VTys[SplatSize-1];
8835 
8836   // Build a canonical splat for this value.
8837   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8838 }
8839 
8840 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8841 /// specified intrinsic ID.
8842 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8843                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8844   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8845   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8846                      DAG.getConstant(IID, dl, MVT::i32), Op);
8847 }
8848 
8849 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8850 /// specified intrinsic ID.
8851 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8852                                 SelectionDAG &DAG, const SDLoc &dl,
8853                                 EVT DestVT = MVT::Other) {
8854   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8855   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8856                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8857 }
8858 
8859 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8860 /// specified intrinsic ID.
8861 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8862                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8863                                 EVT DestVT = MVT::Other) {
8864   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8865   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8866                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8867 }
8868 
8869 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8870 /// amount.  The result has the specified value type.
8871 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8872                            SelectionDAG &DAG, const SDLoc &dl) {
8873   // Force LHS/RHS to be the right type.
8874   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8875   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8876 
8877   int Ops[16];
8878   for (unsigned i = 0; i != 16; ++i)
8879     Ops[i] = i + Amt;
8880   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8881   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8882 }
8883 
8884 /// Do we have an efficient pattern in a .td file for this node?
8885 ///
8886 /// \param V - pointer to the BuildVectorSDNode being matched
8887 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8888 ///
8889 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8890 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8891 /// the opposite is true (expansion is beneficial) are:
8892 /// - The node builds a vector out of integers that are not 32 or 64-bits
8893 /// - The node builds a vector out of constants
8894 /// - The node is a "load-and-splat"
8895 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8896 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8897                                             bool HasDirectMove,
8898                                             bool HasP8Vector) {
8899   EVT VecVT = V->getValueType(0);
8900   bool RightType = VecVT == MVT::v2f64 ||
8901     (HasP8Vector && VecVT == MVT::v4f32) ||
8902     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8903   if (!RightType)
8904     return false;
8905 
8906   bool IsSplat = true;
8907   bool IsLoad = false;
8908   SDValue Op0 = V->getOperand(0);
8909 
8910   // This function is called in a block that confirms the node is not a constant
8911   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8912   // different constants.
8913   if (V->isConstant())
8914     return false;
8915   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8916     if (V->getOperand(i).isUndef())
8917       return false;
8918     // We want to expand nodes that represent load-and-splat even if the
8919     // loaded value is a floating point truncation or conversion to int.
8920     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8921         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8922          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8923         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8924          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8925         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8926          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8927       IsLoad = true;
8928     // If the operands are different or the input is not a load and has more
8929     // uses than just this BV node, then it isn't a splat.
8930     if (V->getOperand(i) != Op0 ||
8931         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8932       IsSplat = false;
8933   }
8934   return !(IsSplat && IsLoad);
8935 }
8936 
8937 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8938 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8939 
8940   SDLoc dl(Op);
8941   SDValue Op0 = Op->getOperand(0);
8942 
8943   if (!EnableQuadPrecision ||
8944       (Op.getValueType() != MVT::f128 ) ||
8945       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8946       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8947       (Op0.getOperand(1).getValueType() != MVT::i64))
8948     return SDValue();
8949 
8950   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8951                      Op0.getOperand(1));
8952 }
8953 
8954 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8955   const SDValue *InputLoad = &Op;
8956   if (InputLoad->getOpcode() == ISD::BITCAST)
8957     InputLoad = &InputLoad->getOperand(0);
8958   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8959     InputLoad = &InputLoad->getOperand(0);
8960   if (InputLoad->getOpcode() != ISD::LOAD)
8961     return nullptr;
8962   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8963   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8964 }
8965 
8966 // If this is a case we can't handle, return null and let the default
8967 // expansion code take care of it.  If we CAN select this case, and if it
8968 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8969 // this case more efficiently than a constant pool load, lower it to the
8970 // sequence of ops that should be used.
8971 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8972                                              SelectionDAG &DAG) const {
8973   SDLoc dl(Op);
8974   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8975   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8976 
8977   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8978     // We first build an i32 vector, load it into a QPX register,
8979     // then convert it to a floating-point vector and compare it
8980     // to a zero vector to get the boolean result.
8981     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8982     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8983     MachinePointerInfo PtrInfo =
8984         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8985     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8986     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8987 
8988     assert(BVN->getNumOperands() == 4 &&
8989       "BUILD_VECTOR for v4i1 does not have 4 operands");
8990 
8991     bool IsConst = true;
8992     for (unsigned i = 0; i < 4; ++i) {
8993       if (BVN->getOperand(i).isUndef()) continue;
8994       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8995         IsConst = false;
8996         break;
8997       }
8998     }
8999 
9000     if (IsConst) {
9001       Constant *One =
9002         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
9003       Constant *NegOne =
9004         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
9005 
9006       Constant *CV[4];
9007       for (unsigned i = 0; i < 4; ++i) {
9008         if (BVN->getOperand(i).isUndef())
9009           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
9010         else if (isNullConstant(BVN->getOperand(i)))
9011           CV[i] = NegOne;
9012         else
9013           CV[i] = One;
9014       }
9015 
9016       Constant *CP = ConstantVector::get(CV);
9017       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
9018                                           16 /* alignment */);
9019 
9020       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
9021       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
9022       return DAG.getMemIntrinsicNode(
9023           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
9024           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
9025     }
9026 
9027     SmallVector<SDValue, 4> Stores;
9028     for (unsigned i = 0; i < 4; ++i) {
9029       if (BVN->getOperand(i).isUndef()) continue;
9030 
9031       unsigned Offset = 4*i;
9032       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9033       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9034 
9035       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
9036       if (StoreSize > 4) {
9037         Stores.push_back(
9038             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
9039                               PtrInfo.getWithOffset(Offset), MVT::i32));
9040       } else {
9041         SDValue StoreValue = BVN->getOperand(i);
9042         if (StoreSize < 4)
9043           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
9044 
9045         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
9046                                       PtrInfo.getWithOffset(Offset)));
9047       }
9048     }
9049 
9050     SDValue StoreChain;
9051     if (!Stores.empty())
9052       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9053     else
9054       StoreChain = DAG.getEntryNode();
9055 
9056     // Now load from v4i32 into the QPX register; this will extend it to
9057     // v4i64 but not yet convert it to a floating point. Nevertheless, this
9058     // is typed as v4f64 because the QPX register integer states are not
9059     // explicitly represented.
9060 
9061     SDValue Ops[] = {StoreChain,
9062                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
9063                      FIdx};
9064     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
9065 
9066     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
9067       dl, VTs, Ops, MVT::v4i32, PtrInfo);
9068     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9069       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
9070       LoadedVect);
9071 
9072     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
9073 
9074     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
9075   }
9076 
9077   // All other QPX vectors are handled by generic code.
9078   if (Subtarget.hasQPX())
9079     return SDValue();
9080 
9081   // Check if this is a splat of a constant value.
9082   APInt APSplatBits, APSplatUndef;
9083   unsigned SplatBitSize;
9084   bool HasAnyUndefs;
9085   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9086                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9087       SplatBitSize > 32) {
9088 
9089     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
9090     // Handle load-and-splat patterns as we have instructions that will do this
9091     // in one go.
9092     if (InputLoad && DAG.isSplatValue(Op, true)) {
9093       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9094 
9095       // We have handling for 4 and 8 byte elements.
9096       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9097 
9098       // Checking for a single use of this load, we have to check for vector
9099       // width (128 bits) / ElementSize uses (since each operand of the
9100       // BUILD_VECTOR is a separate use of the value.
9101       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9102           ((Subtarget.hasVSX() && ElementSize == 64) ||
9103            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9104         SDValue Ops[] = {
9105           LD->getChain(),    // Chain
9106           LD->getBasePtr(),  // Ptr
9107           DAG.getValueType(Op.getValueType()) // VT
9108         };
9109         return
9110           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9111                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9112                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9113       }
9114     }
9115 
9116     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9117     // lowered to VSX instructions under certain conditions.
9118     // Without VSX, there is no pattern more efficient than expanding the node.
9119     if (Subtarget.hasVSX() &&
9120         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9121                                         Subtarget.hasP8Vector()))
9122       return Op;
9123     return SDValue();
9124   }
9125 
9126   unsigned SplatBits = APSplatBits.getZExtValue();
9127   unsigned SplatUndef = APSplatUndef.getZExtValue();
9128   unsigned SplatSize = SplatBitSize / 8;
9129 
9130   // First, handle single instruction cases.
9131 
9132   // All zeros?
9133   if (SplatBits == 0) {
9134     // Canonicalize all zero vectors to be v4i32.
9135     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9136       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9137       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9138     }
9139     return Op;
9140   }
9141 
9142   // We have XXSPLTIB for constant splats one byte wide
9143   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
9144   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
9145   if (Subtarget.hasP9Vector() && SplatSize == 1)
9146     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
9147 
9148   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9149   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9150                     (32-SplatBitSize));
9151   if (SextVal >= -16 && SextVal <= 15)
9152     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
9153 
9154   // Two instruction sequences.
9155 
9156   // If this value is in the range [-32,30] and is even, use:
9157   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9158   // If this value is in the range [17,31] and is odd, use:
9159   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9160   // If this value is in the range [-31,-17] and is odd, use:
9161   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9162   // Note the last two are three-instruction sequences.
9163   if (SextVal >= -32 && SextVal <= 31) {
9164     // To avoid having these optimizations undone by constant folding,
9165     // we convert to a pseudo that will be expanded later into one of
9166     // the above forms.
9167     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9168     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9169               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9170     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9171     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9172     if (VT == Op.getValueType())
9173       return RetVal;
9174     else
9175       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9176   }
9177 
9178   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9179   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9180   // for fneg/fabs.
9181   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9182     // Make -1 and vspltisw -1:
9183     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
9184 
9185     // Make the VSLW intrinsic, computing 0x8000_0000.
9186     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9187                                    OnesV, DAG, dl);
9188 
9189     // xor by OnesV to invert it.
9190     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9191     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9192   }
9193 
9194   // Check to see if this is a wide variety of vsplti*, binop self cases.
9195   static const signed char SplatCsts[] = {
9196     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9197     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9198   };
9199 
9200   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9201     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9202     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9203     int i = SplatCsts[idx];
9204 
9205     // Figure out what shift amount will be used by altivec if shifted by i in
9206     // this splat size.
9207     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9208 
9209     // vsplti + shl self.
9210     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9211       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9212       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9213         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9214         Intrinsic::ppc_altivec_vslw
9215       };
9216       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9217       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9218     }
9219 
9220     // vsplti + srl self.
9221     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9222       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9223       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9224         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9225         Intrinsic::ppc_altivec_vsrw
9226       };
9227       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9228       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9229     }
9230 
9231     // vsplti + sra self.
9232     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9233       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9234       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9235         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9236         Intrinsic::ppc_altivec_vsraw
9237       };
9238       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9239       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9240     }
9241 
9242     // vsplti + rol self.
9243     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9244                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9245       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
9246       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9247         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9248         Intrinsic::ppc_altivec_vrlw
9249       };
9250       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9251       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9252     }
9253 
9254     // t = vsplti c, result = vsldoi t, t, 1
9255     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9256       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9257       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9258       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9259     }
9260     // t = vsplti c, result = vsldoi t, t, 2
9261     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9262       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9263       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9264       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9265     }
9266     // t = vsplti c, result = vsldoi t, t, 3
9267     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9268       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
9269       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9270       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9271     }
9272   }
9273 
9274   return SDValue();
9275 }
9276 
9277 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9278 /// the specified operations to build the shuffle.
9279 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9280                                       SDValue RHS, SelectionDAG &DAG,
9281                                       const SDLoc &dl) {
9282   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9283   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9284   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9285 
9286   enum {
9287     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9288     OP_VMRGHW,
9289     OP_VMRGLW,
9290     OP_VSPLTISW0,
9291     OP_VSPLTISW1,
9292     OP_VSPLTISW2,
9293     OP_VSPLTISW3,
9294     OP_VSLDOI4,
9295     OP_VSLDOI8,
9296     OP_VSLDOI12
9297   };
9298 
9299   if (OpNum == OP_COPY) {
9300     if (LHSID == (1*9+2)*9+3) return LHS;
9301     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9302     return RHS;
9303   }
9304 
9305   SDValue OpLHS, OpRHS;
9306   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9307   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9308 
9309   int ShufIdxs[16];
9310   switch (OpNum) {
9311   default: llvm_unreachable("Unknown i32 permute!");
9312   case OP_VMRGHW:
9313     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9314     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9315     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9316     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9317     break;
9318   case OP_VMRGLW:
9319     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9320     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9321     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9322     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9323     break;
9324   case OP_VSPLTISW0:
9325     for (unsigned i = 0; i != 16; ++i)
9326       ShufIdxs[i] = (i&3)+0;
9327     break;
9328   case OP_VSPLTISW1:
9329     for (unsigned i = 0; i != 16; ++i)
9330       ShufIdxs[i] = (i&3)+4;
9331     break;
9332   case OP_VSPLTISW2:
9333     for (unsigned i = 0; i != 16; ++i)
9334       ShufIdxs[i] = (i&3)+8;
9335     break;
9336   case OP_VSPLTISW3:
9337     for (unsigned i = 0; i != 16; ++i)
9338       ShufIdxs[i] = (i&3)+12;
9339     break;
9340   case OP_VSLDOI4:
9341     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9342   case OP_VSLDOI8:
9343     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9344   case OP_VSLDOI12:
9345     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9346   }
9347   EVT VT = OpLHS.getValueType();
9348   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9349   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9350   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9351   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9352 }
9353 
9354 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9355 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9356 /// SDValue.
9357 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9358                                            SelectionDAG &DAG) const {
9359   const unsigned BytesInVector = 16;
9360   bool IsLE = Subtarget.isLittleEndian();
9361   SDLoc dl(N);
9362   SDValue V1 = N->getOperand(0);
9363   SDValue V2 = N->getOperand(1);
9364   unsigned ShiftElts = 0, InsertAtByte = 0;
9365   bool Swap = false;
9366 
9367   // Shifts required to get the byte we want at element 7.
9368   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9369                                    0, 15, 14, 13, 12, 11, 10, 9};
9370   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9371                                 1, 2,  3,  4,  5,  6,  7,  8};
9372 
9373   ArrayRef<int> Mask = N->getMask();
9374   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9375 
9376   // For each mask element, find out if we're just inserting something
9377   // from V2 into V1 or vice versa.
9378   // Possible permutations inserting an element from V2 into V1:
9379   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9380   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9381   //   ...
9382   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9383   // Inserting from V1 into V2 will be similar, except mask range will be
9384   // [16,31].
9385 
9386   bool FoundCandidate = false;
9387   // If both vector operands for the shuffle are the same vector, the mask
9388   // will contain only elements from the first one and the second one will be
9389   // undef.
9390   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9391   // Go through the mask of half-words to find an element that's being moved
9392   // from one vector to the other.
9393   for (unsigned i = 0; i < BytesInVector; ++i) {
9394     unsigned CurrentElement = Mask[i];
9395     // If 2nd operand is undefined, we should only look for element 7 in the
9396     // Mask.
9397     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9398       continue;
9399 
9400     bool OtherElementsInOrder = true;
9401     // Examine the other elements in the Mask to see if they're in original
9402     // order.
9403     for (unsigned j = 0; j < BytesInVector; ++j) {
9404       if (j == i)
9405         continue;
9406       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9407       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9408       // in which we always assume we're always picking from the 1st operand.
9409       int MaskOffset =
9410           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9411       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9412         OtherElementsInOrder = false;
9413         break;
9414       }
9415     }
9416     // If other elements are in original order, we record the number of shifts
9417     // we need to get the element we want into element 7. Also record which byte
9418     // in the vector we should insert into.
9419     if (OtherElementsInOrder) {
9420       // If 2nd operand is undefined, we assume no shifts and no swapping.
9421       if (V2.isUndef()) {
9422         ShiftElts = 0;
9423         Swap = false;
9424       } else {
9425         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9426         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9427                          : BigEndianShifts[CurrentElement & 0xF];
9428         Swap = CurrentElement < BytesInVector;
9429       }
9430       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9431       FoundCandidate = true;
9432       break;
9433     }
9434   }
9435 
9436   if (!FoundCandidate)
9437     return SDValue();
9438 
9439   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9440   // optionally with VECSHL if shift is required.
9441   if (Swap)
9442     std::swap(V1, V2);
9443   if (V2.isUndef())
9444     V2 = V1;
9445   if (ShiftElts) {
9446     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9447                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9448     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9449                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9450   }
9451   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9452                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9453 }
9454 
9455 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9456 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9457 /// SDValue.
9458 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9459                                            SelectionDAG &DAG) const {
9460   const unsigned NumHalfWords = 8;
9461   const unsigned BytesInVector = NumHalfWords * 2;
9462   // Check that the shuffle is on half-words.
9463   if (!isNByteElemShuffleMask(N, 2, 1))
9464     return SDValue();
9465 
9466   bool IsLE = Subtarget.isLittleEndian();
9467   SDLoc dl(N);
9468   SDValue V1 = N->getOperand(0);
9469   SDValue V2 = N->getOperand(1);
9470   unsigned ShiftElts = 0, InsertAtByte = 0;
9471   bool Swap = false;
9472 
9473   // Shifts required to get the half-word we want at element 3.
9474   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9475   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9476 
9477   uint32_t Mask = 0;
9478   uint32_t OriginalOrderLow = 0x1234567;
9479   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9480   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9481   // 32-bit space, only need 4-bit nibbles per element.
9482   for (unsigned i = 0; i < NumHalfWords; ++i) {
9483     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9484     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9485   }
9486 
9487   // For each mask element, find out if we're just inserting something
9488   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9489   // from V2 into V1:
9490   //   X, 1, 2, 3, 4, 5, 6, 7
9491   //   0, X, 2, 3, 4, 5, 6, 7
9492   //   0, 1, X, 3, 4, 5, 6, 7
9493   //   0, 1, 2, X, 4, 5, 6, 7
9494   //   0, 1, 2, 3, X, 5, 6, 7
9495   //   0, 1, 2, 3, 4, X, 6, 7
9496   //   0, 1, 2, 3, 4, 5, X, 7
9497   //   0, 1, 2, 3, 4, 5, 6, X
9498   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9499 
9500   bool FoundCandidate = false;
9501   // Go through the mask of half-words to find an element that's being moved
9502   // from one vector to the other.
9503   for (unsigned i = 0; i < NumHalfWords; ++i) {
9504     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9505     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9506     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9507     uint32_t TargetOrder = 0x0;
9508 
9509     // If both vector operands for the shuffle are the same vector, the mask
9510     // will contain only elements from the first one and the second one will be
9511     // undef.
9512     if (V2.isUndef()) {
9513       ShiftElts = 0;
9514       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9515       TargetOrder = OriginalOrderLow;
9516       Swap = false;
9517       // Skip if not the correct element or mask of other elements don't equal
9518       // to our expected order.
9519       if (MaskOneElt == VINSERTHSrcElem &&
9520           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9521         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9522         FoundCandidate = true;
9523         break;
9524       }
9525     } else { // If both operands are defined.
9526       // Target order is [8,15] if the current mask is between [0,7].
9527       TargetOrder =
9528           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9529       // Skip if mask of other elements don't equal our expected order.
9530       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9531         // We only need the last 3 bits for the number of shifts.
9532         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9533                          : BigEndianShifts[MaskOneElt & 0x7];
9534         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9535         Swap = MaskOneElt < NumHalfWords;
9536         FoundCandidate = true;
9537         break;
9538       }
9539     }
9540   }
9541 
9542   if (!FoundCandidate)
9543     return SDValue();
9544 
9545   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9546   // optionally with VECSHL if shift is required.
9547   if (Swap)
9548     std::swap(V1, V2);
9549   if (V2.isUndef())
9550     V2 = V1;
9551   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9552   if (ShiftElts) {
9553     // Double ShiftElts because we're left shifting on v16i8 type.
9554     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9555                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9556     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9557     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9558                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9559     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9560   }
9561   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9562   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9563                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9564   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9565 }
9566 
9567 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9568 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9569 /// return the code it can be lowered into.  Worst case, it can always be
9570 /// lowered into a vperm.
9571 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9572                                                SelectionDAG &DAG) const {
9573   SDLoc dl(Op);
9574   SDValue V1 = Op.getOperand(0);
9575   SDValue V2 = Op.getOperand(1);
9576   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9577   EVT VT = Op.getValueType();
9578   bool isLittleEndian = Subtarget.isLittleEndian();
9579 
9580   unsigned ShiftElts, InsertAtByte;
9581   bool Swap = false;
9582 
9583   // If this is a load-and-splat, we can do that with a single instruction
9584   // in some cases. However if the load has multiple uses, we don't want to
9585   // combine it because that will just produce multiple loads.
9586   const SDValue *InputLoad = getNormalLoadInput(V1);
9587   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9588       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9589       InputLoad->hasOneUse()) {
9590     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9591     int SplatIdx =
9592       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9593 
9594     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9595     // For 4-byte load-and-splat, we need Power9.
9596     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9597       uint64_t Offset = 0;
9598       if (IsFourByte)
9599         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9600       else
9601         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9602       SDValue BasePtr = LD->getBasePtr();
9603       if (Offset != 0)
9604         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9605                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9606       SDValue Ops[] = {
9607         LD->getChain(),    // Chain
9608         BasePtr,           // BasePtr
9609         DAG.getValueType(Op.getValueType()) // VT
9610       };
9611       SDVTList VTL =
9612         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9613       SDValue LdSplt =
9614         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9615                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9616       if (LdSplt.getValueType() != SVOp->getValueType(0))
9617         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9618       return LdSplt;
9619     }
9620   }
9621   if (Subtarget.hasP9Vector() &&
9622       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9623                            isLittleEndian)) {
9624     if (Swap)
9625       std::swap(V1, V2);
9626     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9627     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9628     if (ShiftElts) {
9629       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9630                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9631       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9632                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9633       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9634     }
9635     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9636                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9637     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9638   }
9639 
9640   if (Subtarget.hasP9Altivec()) {
9641     SDValue NewISDNode;
9642     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9643       return NewISDNode;
9644 
9645     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9646       return NewISDNode;
9647   }
9648 
9649   if (Subtarget.hasVSX() &&
9650       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9651     if (Swap)
9652       std::swap(V1, V2);
9653     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9654     SDValue Conv2 =
9655         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9656 
9657     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9658                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9659     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9660   }
9661 
9662   if (Subtarget.hasVSX() &&
9663     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9664     if (Swap)
9665       std::swap(V1, V2);
9666     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9667     SDValue Conv2 =
9668         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9669 
9670     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9671                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9672     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9673   }
9674 
9675   if (Subtarget.hasP9Vector()) {
9676      if (PPC::isXXBRHShuffleMask(SVOp)) {
9677       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9678       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9679       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9680     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9681       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9682       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9683       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9684     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9685       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9686       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9687       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9688     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9689       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9690       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9691       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9692     }
9693   }
9694 
9695   if (Subtarget.hasVSX()) {
9696     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9697       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9698 
9699       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9700       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9701                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9702       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9703     }
9704 
9705     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9706     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9707       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9708       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9709       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9710     }
9711   }
9712 
9713   if (Subtarget.hasQPX()) {
9714     if (VT.getVectorNumElements() != 4)
9715       return SDValue();
9716 
9717     if (V2.isUndef()) V2 = V1;
9718 
9719     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9720     if (AlignIdx != -1) {
9721       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9722                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9723     } else if (SVOp->isSplat()) {
9724       int SplatIdx = SVOp->getSplatIndex();
9725       if (SplatIdx >= 4) {
9726         std::swap(V1, V2);
9727         SplatIdx -= 4;
9728       }
9729 
9730       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9731                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9732     }
9733 
9734     // Lower this into a qvgpci/qvfperm pair.
9735 
9736     // Compute the qvgpci literal
9737     unsigned idx = 0;
9738     for (unsigned i = 0; i < 4; ++i) {
9739       int m = SVOp->getMaskElt(i);
9740       unsigned mm = m >= 0 ? (unsigned) m : i;
9741       idx |= mm << (3-i)*3;
9742     }
9743 
9744     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9745                              DAG.getConstant(idx, dl, MVT::i32));
9746     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9747   }
9748 
9749   // Cases that are handled by instructions that take permute immediates
9750   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9751   // selected by the instruction selector.
9752   if (V2.isUndef()) {
9753     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9754         PPC::isSplatShuffleMask(SVOp, 2) ||
9755         PPC::isSplatShuffleMask(SVOp, 4) ||
9756         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9757         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9758         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9759         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9760         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9761         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9762         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9763         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9764         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9765         (Subtarget.hasP8Altivec() && (
9766          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9767          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9768          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9769       return Op;
9770     }
9771   }
9772 
9773   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9774   // and produce a fixed permutation.  If any of these match, do not lower to
9775   // VPERM.
9776   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9777   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9778       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9779       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9780       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9781       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9782       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9783       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9784       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9785       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9786       (Subtarget.hasP8Altivec() && (
9787        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9788        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9789        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9790     return Op;
9791 
9792   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9793   // perfect shuffle table to emit an optimal matching sequence.
9794   ArrayRef<int> PermMask = SVOp->getMask();
9795 
9796   unsigned PFIndexes[4];
9797   bool isFourElementShuffle = true;
9798   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9799     unsigned EltNo = 8;   // Start out undef.
9800     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9801       if (PermMask[i*4+j] < 0)
9802         continue;   // Undef, ignore it.
9803 
9804       unsigned ByteSource = PermMask[i*4+j];
9805       if ((ByteSource & 3) != j) {
9806         isFourElementShuffle = false;
9807         break;
9808       }
9809 
9810       if (EltNo == 8) {
9811         EltNo = ByteSource/4;
9812       } else if (EltNo != ByteSource/4) {
9813         isFourElementShuffle = false;
9814         break;
9815       }
9816     }
9817     PFIndexes[i] = EltNo;
9818   }
9819 
9820   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9821   // perfect shuffle vector to determine if it is cost effective to do this as
9822   // discrete instructions, or whether we should use a vperm.
9823   // For now, we skip this for little endian until such time as we have a
9824   // little-endian perfect shuffle table.
9825   if (isFourElementShuffle && !isLittleEndian) {
9826     // Compute the index in the perfect shuffle table.
9827     unsigned PFTableIndex =
9828       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9829 
9830     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9831     unsigned Cost  = (PFEntry >> 30);
9832 
9833     // Determining when to avoid vperm is tricky.  Many things affect the cost
9834     // of vperm, particularly how many times the perm mask needs to be computed.
9835     // For example, if the perm mask can be hoisted out of a loop or is already
9836     // used (perhaps because there are multiple permutes with the same shuffle
9837     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9838     // the loop requires an extra register.
9839     //
9840     // As a compromise, we only emit discrete instructions if the shuffle can be
9841     // generated in 3 or fewer operations.  When we have loop information
9842     // available, if this block is within a loop, we should avoid using vperm
9843     // for 3-operation perms and use a constant pool load instead.
9844     if (Cost < 3)
9845       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9846   }
9847 
9848   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9849   // vector that will get spilled to the constant pool.
9850   if (V2.isUndef()) V2 = V1;
9851 
9852   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9853   // that it is in input element units, not in bytes.  Convert now.
9854 
9855   // For little endian, the order of the input vectors is reversed, and
9856   // the permutation mask is complemented with respect to 31.  This is
9857   // necessary to produce proper semantics with the big-endian-biased vperm
9858   // instruction.
9859   EVT EltVT = V1.getValueType().getVectorElementType();
9860   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9861 
9862   SmallVector<SDValue, 16> ResultMask;
9863   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9864     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9865 
9866     for (unsigned j = 0; j != BytesPerElement; ++j)
9867       if (isLittleEndian)
9868         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9869                                              dl, MVT::i32));
9870       else
9871         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9872                                              MVT::i32));
9873   }
9874 
9875   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9876   if (isLittleEndian)
9877     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9878                        V2, V1, VPermMask);
9879   else
9880     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9881                        V1, V2, VPermMask);
9882 }
9883 
9884 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9885 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9886 /// information about the intrinsic.
9887 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9888                                  bool &isDot, const PPCSubtarget &Subtarget) {
9889   unsigned IntrinsicID =
9890       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9891   CompareOpc = -1;
9892   isDot = false;
9893   switch (IntrinsicID) {
9894   default:
9895     return false;
9896   // Comparison predicates.
9897   case Intrinsic::ppc_altivec_vcmpbfp_p:
9898     CompareOpc = 966;
9899     isDot = true;
9900     break;
9901   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9902     CompareOpc = 198;
9903     isDot = true;
9904     break;
9905   case Intrinsic::ppc_altivec_vcmpequb_p:
9906     CompareOpc = 6;
9907     isDot = true;
9908     break;
9909   case Intrinsic::ppc_altivec_vcmpequh_p:
9910     CompareOpc = 70;
9911     isDot = true;
9912     break;
9913   case Intrinsic::ppc_altivec_vcmpequw_p:
9914     CompareOpc = 134;
9915     isDot = true;
9916     break;
9917   case Intrinsic::ppc_altivec_vcmpequd_p:
9918     if (Subtarget.hasP8Altivec()) {
9919       CompareOpc = 199;
9920       isDot = true;
9921     } else
9922       return false;
9923     break;
9924   case Intrinsic::ppc_altivec_vcmpneb_p:
9925   case Intrinsic::ppc_altivec_vcmpneh_p:
9926   case Intrinsic::ppc_altivec_vcmpnew_p:
9927   case Intrinsic::ppc_altivec_vcmpnezb_p:
9928   case Intrinsic::ppc_altivec_vcmpnezh_p:
9929   case Intrinsic::ppc_altivec_vcmpnezw_p:
9930     if (Subtarget.hasP9Altivec()) {
9931       switch (IntrinsicID) {
9932       default:
9933         llvm_unreachable("Unknown comparison intrinsic.");
9934       case Intrinsic::ppc_altivec_vcmpneb_p:
9935         CompareOpc = 7;
9936         break;
9937       case Intrinsic::ppc_altivec_vcmpneh_p:
9938         CompareOpc = 71;
9939         break;
9940       case Intrinsic::ppc_altivec_vcmpnew_p:
9941         CompareOpc = 135;
9942         break;
9943       case Intrinsic::ppc_altivec_vcmpnezb_p:
9944         CompareOpc = 263;
9945         break;
9946       case Intrinsic::ppc_altivec_vcmpnezh_p:
9947         CompareOpc = 327;
9948         break;
9949       case Intrinsic::ppc_altivec_vcmpnezw_p:
9950         CompareOpc = 391;
9951         break;
9952       }
9953       isDot = true;
9954     } else
9955       return false;
9956     break;
9957   case Intrinsic::ppc_altivec_vcmpgefp_p:
9958     CompareOpc = 454;
9959     isDot = true;
9960     break;
9961   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9962     CompareOpc = 710;
9963     isDot = true;
9964     break;
9965   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9966     CompareOpc = 774;
9967     isDot = true;
9968     break;
9969   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9970     CompareOpc = 838;
9971     isDot = true;
9972     break;
9973   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9974     CompareOpc = 902;
9975     isDot = true;
9976     break;
9977   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9978     if (Subtarget.hasP8Altivec()) {
9979       CompareOpc = 967;
9980       isDot = true;
9981     } else
9982       return false;
9983     break;
9984   case Intrinsic::ppc_altivec_vcmpgtub_p:
9985     CompareOpc = 518;
9986     isDot = true;
9987     break;
9988   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9989     CompareOpc = 582;
9990     isDot = true;
9991     break;
9992   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9993     CompareOpc = 646;
9994     isDot = true;
9995     break;
9996   case Intrinsic::ppc_altivec_vcmpgtud_p:
9997     if (Subtarget.hasP8Altivec()) {
9998       CompareOpc = 711;
9999       isDot = true;
10000     } else
10001       return false;
10002     break;
10003 
10004   // VSX predicate comparisons use the same infrastructure
10005   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10006   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10007   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10008   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10009   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10010   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10011     if (Subtarget.hasVSX()) {
10012       switch (IntrinsicID) {
10013       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10014         CompareOpc = 99;
10015         break;
10016       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10017         CompareOpc = 115;
10018         break;
10019       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10020         CompareOpc = 107;
10021         break;
10022       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10023         CompareOpc = 67;
10024         break;
10025       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10026         CompareOpc = 83;
10027         break;
10028       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10029         CompareOpc = 75;
10030         break;
10031       }
10032       isDot = true;
10033     } else
10034       return false;
10035     break;
10036 
10037   // Normal Comparisons.
10038   case Intrinsic::ppc_altivec_vcmpbfp:
10039     CompareOpc = 966;
10040     break;
10041   case Intrinsic::ppc_altivec_vcmpeqfp:
10042     CompareOpc = 198;
10043     break;
10044   case Intrinsic::ppc_altivec_vcmpequb:
10045     CompareOpc = 6;
10046     break;
10047   case Intrinsic::ppc_altivec_vcmpequh:
10048     CompareOpc = 70;
10049     break;
10050   case Intrinsic::ppc_altivec_vcmpequw:
10051     CompareOpc = 134;
10052     break;
10053   case Intrinsic::ppc_altivec_vcmpequd:
10054     if (Subtarget.hasP8Altivec())
10055       CompareOpc = 199;
10056     else
10057       return false;
10058     break;
10059   case Intrinsic::ppc_altivec_vcmpneb:
10060   case Intrinsic::ppc_altivec_vcmpneh:
10061   case Intrinsic::ppc_altivec_vcmpnew:
10062   case Intrinsic::ppc_altivec_vcmpnezb:
10063   case Intrinsic::ppc_altivec_vcmpnezh:
10064   case Intrinsic::ppc_altivec_vcmpnezw:
10065     if (Subtarget.hasP9Altivec())
10066       switch (IntrinsicID) {
10067       default:
10068         llvm_unreachable("Unknown comparison intrinsic.");
10069       case Intrinsic::ppc_altivec_vcmpneb:
10070         CompareOpc = 7;
10071         break;
10072       case Intrinsic::ppc_altivec_vcmpneh:
10073         CompareOpc = 71;
10074         break;
10075       case Intrinsic::ppc_altivec_vcmpnew:
10076         CompareOpc = 135;
10077         break;
10078       case Intrinsic::ppc_altivec_vcmpnezb:
10079         CompareOpc = 263;
10080         break;
10081       case Intrinsic::ppc_altivec_vcmpnezh:
10082         CompareOpc = 327;
10083         break;
10084       case Intrinsic::ppc_altivec_vcmpnezw:
10085         CompareOpc = 391;
10086         break;
10087       }
10088     else
10089       return false;
10090     break;
10091   case Intrinsic::ppc_altivec_vcmpgefp:
10092     CompareOpc = 454;
10093     break;
10094   case Intrinsic::ppc_altivec_vcmpgtfp:
10095     CompareOpc = 710;
10096     break;
10097   case Intrinsic::ppc_altivec_vcmpgtsb:
10098     CompareOpc = 774;
10099     break;
10100   case Intrinsic::ppc_altivec_vcmpgtsh:
10101     CompareOpc = 838;
10102     break;
10103   case Intrinsic::ppc_altivec_vcmpgtsw:
10104     CompareOpc = 902;
10105     break;
10106   case Intrinsic::ppc_altivec_vcmpgtsd:
10107     if (Subtarget.hasP8Altivec())
10108       CompareOpc = 967;
10109     else
10110       return false;
10111     break;
10112   case Intrinsic::ppc_altivec_vcmpgtub:
10113     CompareOpc = 518;
10114     break;
10115   case Intrinsic::ppc_altivec_vcmpgtuh:
10116     CompareOpc = 582;
10117     break;
10118   case Intrinsic::ppc_altivec_vcmpgtuw:
10119     CompareOpc = 646;
10120     break;
10121   case Intrinsic::ppc_altivec_vcmpgtud:
10122     if (Subtarget.hasP8Altivec())
10123       CompareOpc = 711;
10124     else
10125       return false;
10126     break;
10127   }
10128   return true;
10129 }
10130 
10131 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10132 /// lower, do it, otherwise return null.
10133 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10134                                                    SelectionDAG &DAG) const {
10135   unsigned IntrinsicID =
10136     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10137 
10138   SDLoc dl(Op);
10139 
10140   if (IntrinsicID == Intrinsic::thread_pointer) {
10141     // Reads the thread pointer register, used for __builtin_thread_pointer.
10142     if (Subtarget.isPPC64())
10143       return DAG.getRegister(PPC::X13, MVT::i64);
10144     return DAG.getRegister(PPC::R2, MVT::i32);
10145   }
10146 
10147   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10148   // opcode number of the comparison.
10149   int CompareOpc;
10150   bool isDot;
10151   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10152     return SDValue();    // Don't custom lower most intrinsics.
10153 
10154   // If this is a non-dot comparison, make the VCMP node and we are done.
10155   if (!isDot) {
10156     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10157                               Op.getOperand(1), Op.getOperand(2),
10158                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10159     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10160   }
10161 
10162   // Create the PPCISD altivec 'dot' comparison node.
10163   SDValue Ops[] = {
10164     Op.getOperand(2),  // LHS
10165     Op.getOperand(3),  // RHS
10166     DAG.getConstant(CompareOpc, dl, MVT::i32)
10167   };
10168   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10169   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10170 
10171   // Now that we have the comparison, emit a copy from the CR to a GPR.
10172   // This is flagged to the above dot comparison.
10173   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10174                                 DAG.getRegister(PPC::CR6, MVT::i32),
10175                                 CompNode.getValue(1));
10176 
10177   // Unpack the result based on how the target uses it.
10178   unsigned BitNo;   // Bit # of CR6.
10179   bool InvertBit;   // Invert result?
10180   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10181   default:  // Can't happen, don't crash on invalid number though.
10182   case 0:   // Return the value of the EQ bit of CR6.
10183     BitNo = 0; InvertBit = false;
10184     break;
10185   case 1:   // Return the inverted value of the EQ bit of CR6.
10186     BitNo = 0; InvertBit = true;
10187     break;
10188   case 2:   // Return the value of the LT bit of CR6.
10189     BitNo = 2; InvertBit = false;
10190     break;
10191   case 3:   // Return the inverted value of the LT bit of CR6.
10192     BitNo = 2; InvertBit = true;
10193     break;
10194   }
10195 
10196   // Shift the bit into the low position.
10197   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10198                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10199   // Isolate the bit.
10200   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10201                       DAG.getConstant(1, dl, MVT::i32));
10202 
10203   // If we are supposed to, toggle the bit.
10204   if (InvertBit)
10205     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10206                         DAG.getConstant(1, dl, MVT::i32));
10207   return Flags;
10208 }
10209 
10210 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10211                                                SelectionDAG &DAG) const {
10212   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10213   // the beginning of the argument list.
10214   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10215   SDLoc DL(Op);
10216   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10217   case Intrinsic::ppc_cfence: {
10218     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10219     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10220     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10221                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10222                                                   Op.getOperand(ArgStart + 1)),
10223                                       Op.getOperand(0)),
10224                    0);
10225   }
10226   default:
10227     break;
10228   }
10229   return SDValue();
10230 }
10231 
10232 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
10233   // Check for a DIV with the same operands as this REM.
10234   for (auto UI : Op.getOperand(1)->uses()) {
10235     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
10236         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
10237       if (UI->getOperand(0) == Op.getOperand(0) &&
10238           UI->getOperand(1) == Op.getOperand(1))
10239         return SDValue();
10240   }
10241   return Op;
10242 }
10243 
10244 // Lower scalar BSWAP64 to xxbrd.
10245 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10246   SDLoc dl(Op);
10247   // MTVSRDD
10248   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10249                    Op.getOperand(0));
10250   // XXBRD
10251   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10252   // MFVSRD
10253   int VectorIndex = 0;
10254   if (Subtarget.isLittleEndian())
10255     VectorIndex = 1;
10256   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10257                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10258   return Op;
10259 }
10260 
10261 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10262 // compared to a value that is atomically loaded (atomic loads zero-extend).
10263 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10264                                                 SelectionDAG &DAG) const {
10265   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10266          "Expecting an atomic compare-and-swap here.");
10267   SDLoc dl(Op);
10268   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10269   EVT MemVT = AtomicNode->getMemoryVT();
10270   if (MemVT.getSizeInBits() >= 32)
10271     return Op;
10272 
10273   SDValue CmpOp = Op.getOperand(2);
10274   // If this is already correctly zero-extended, leave it alone.
10275   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10276   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10277     return Op;
10278 
10279   // Clear the high bits of the compare operand.
10280   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10281   SDValue NewCmpOp =
10282     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10283                 DAG.getConstant(MaskVal, dl, MVT::i32));
10284 
10285   // Replace the existing compare operand with the properly zero-extended one.
10286   SmallVector<SDValue, 4> Ops;
10287   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10288     Ops.push_back(AtomicNode->getOperand(i));
10289   Ops[2] = NewCmpOp;
10290   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10291   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10292   auto NodeTy =
10293     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10294   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10295 }
10296 
10297 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10298                                                  SelectionDAG &DAG) const {
10299   SDLoc dl(Op);
10300   // Create a stack slot that is 16-byte aligned.
10301   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10302   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10303   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10304   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10305 
10306   // Store the input value into Value#0 of the stack slot.
10307   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10308                                MachinePointerInfo());
10309   // Load it out.
10310   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10311 }
10312 
10313 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10314                                                   SelectionDAG &DAG) const {
10315   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10316          "Should only be called for ISD::INSERT_VECTOR_ELT");
10317 
10318   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10319   // We have legal lowering for constant indices but not for variable ones.
10320   if (!C)
10321     return SDValue();
10322 
10323   EVT VT = Op.getValueType();
10324   SDLoc dl(Op);
10325   SDValue V1 = Op.getOperand(0);
10326   SDValue V2 = Op.getOperand(1);
10327   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10328   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10329     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10330     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10331     unsigned InsertAtElement = C->getZExtValue();
10332     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10333     if (Subtarget.isLittleEndian()) {
10334       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10335     }
10336     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10337                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10338   }
10339   return Op;
10340 }
10341 
10342 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10343                                                    SelectionDAG &DAG) const {
10344   SDLoc dl(Op);
10345   SDNode *N = Op.getNode();
10346 
10347   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
10348          "Unknown extract_vector_elt type");
10349 
10350   SDValue Value = N->getOperand(0);
10351 
10352   // The first part of this is like the store lowering except that we don't
10353   // need to track the chain.
10354 
10355   // The values are now known to be -1 (false) or 1 (true). To convert this
10356   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10357   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10358   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10359 
10360   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10361   // understand how to form the extending load.
10362   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10363 
10364   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10365 
10366   // Now convert to an integer and store.
10367   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10368     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10369     Value);
10370 
10371   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10372   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10373   MachinePointerInfo PtrInfo =
10374       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10375   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10376   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10377 
10378   SDValue StoreChain = DAG.getEntryNode();
10379   SDValue Ops[] = {StoreChain,
10380                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10381                    Value, FIdx};
10382   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10383 
10384   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10385     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10386 
10387   // Extract the value requested.
10388   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10389   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10390   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10391 
10392   SDValue IntVal =
10393       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
10394 
10395   if (!Subtarget.useCRBits())
10396     return IntVal;
10397 
10398   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
10399 }
10400 
10401 /// Lowering for QPX v4i1 loads
10402 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10403                                            SelectionDAG &DAG) const {
10404   SDLoc dl(Op);
10405   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10406   SDValue LoadChain = LN->getChain();
10407   SDValue BasePtr = LN->getBasePtr();
10408 
10409   if (Op.getValueType() == MVT::v4f64 ||
10410       Op.getValueType() == MVT::v4f32) {
10411     EVT MemVT = LN->getMemoryVT();
10412     unsigned Alignment = LN->getAlignment();
10413 
10414     // If this load is properly aligned, then it is legal.
10415     if (Alignment >= MemVT.getStoreSize())
10416       return Op;
10417 
10418     EVT ScalarVT = Op.getValueType().getScalarType(),
10419         ScalarMemVT = MemVT.getScalarType();
10420     unsigned Stride = ScalarMemVT.getStoreSize();
10421 
10422     SDValue Vals[4], LoadChains[4];
10423     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10424       SDValue Load;
10425       if (ScalarVT != ScalarMemVT)
10426         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
10427                               BasePtr,
10428                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10429                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10430                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10431       else
10432         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10433                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10434                            MinAlign(Alignment, Idx * Stride),
10435                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10436 
10437       if (Idx == 0 && LN->isIndexed()) {
10438         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10439                "Unknown addressing mode on vector load");
10440         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10441                                   LN->getAddressingMode());
10442       }
10443 
10444       Vals[Idx] = Load;
10445       LoadChains[Idx] = Load.getValue(1);
10446 
10447       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10448                             DAG.getConstant(Stride, dl,
10449                                             BasePtr.getValueType()));
10450     }
10451 
10452     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10453     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10454 
10455     if (LN->isIndexed()) {
10456       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10457       return DAG.getMergeValues(RetOps, dl);
10458     }
10459 
10460     SDValue RetOps[] = { Value, TF };
10461     return DAG.getMergeValues(RetOps, dl);
10462   }
10463 
10464   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10465   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10466 
10467   // To lower v4i1 from a byte array, we load the byte elements of the
10468   // vector and then reuse the BUILD_VECTOR logic.
10469 
10470   SDValue VectElmts[4], VectElmtChains[4];
10471   for (unsigned i = 0; i < 4; ++i) {
10472     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10473     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10474 
10475     VectElmts[i] = DAG.getExtLoad(
10476         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10477         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10478         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10479     VectElmtChains[i] = VectElmts[i].getValue(1);
10480   }
10481 
10482   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10483   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10484 
10485   SDValue RVals[] = { Value, LoadChain };
10486   return DAG.getMergeValues(RVals, dl);
10487 }
10488 
10489 /// Lowering for QPX v4i1 stores
10490 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10491                                             SelectionDAG &DAG) const {
10492   SDLoc dl(Op);
10493   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10494   SDValue StoreChain = SN->getChain();
10495   SDValue BasePtr = SN->getBasePtr();
10496   SDValue Value = SN->getValue();
10497 
10498   if (Value.getValueType() == MVT::v4f64 ||
10499       Value.getValueType() == MVT::v4f32) {
10500     EVT MemVT = SN->getMemoryVT();
10501     unsigned Alignment = SN->getAlignment();
10502 
10503     // If this store is properly aligned, then it is legal.
10504     if (Alignment >= MemVT.getStoreSize())
10505       return Op;
10506 
10507     EVT ScalarVT = Value.getValueType().getScalarType(),
10508         ScalarMemVT = MemVT.getScalarType();
10509     unsigned Stride = ScalarMemVT.getStoreSize();
10510 
10511     SDValue Stores[4];
10512     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10513       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10514                                DAG.getVectorIdxConstant(Idx, dl));
10515       SDValue Store;
10516       if (ScalarVT != ScalarMemVT)
10517         Store =
10518             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10519                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10520                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10521                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10522       else
10523         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10524                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10525                              MinAlign(Alignment, Idx * Stride),
10526                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10527 
10528       if (Idx == 0 && SN->isIndexed()) {
10529         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10530                "Unknown addressing mode on vector store");
10531         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10532                                     SN->getAddressingMode());
10533       }
10534 
10535       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10536                             DAG.getConstant(Stride, dl,
10537                                             BasePtr.getValueType()));
10538       Stores[Idx] = Store;
10539     }
10540 
10541     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10542 
10543     if (SN->isIndexed()) {
10544       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10545       return DAG.getMergeValues(RetOps, dl);
10546     }
10547 
10548     return TF;
10549   }
10550 
10551   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10552   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10553 
10554   // The values are now known to be -1 (false) or 1 (true). To convert this
10555   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10556   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10557   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10558 
10559   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10560   // understand how to form the extending load.
10561   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10562 
10563   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10564 
10565   // Now convert to an integer and store.
10566   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10567     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10568     Value);
10569 
10570   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10571   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10572   MachinePointerInfo PtrInfo =
10573       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10574   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10575   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10576 
10577   SDValue Ops[] = {StoreChain,
10578                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10579                    Value, FIdx};
10580   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10581 
10582   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10583     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10584 
10585   // Move data into the byte array.
10586   SDValue Loads[4], LoadChains[4];
10587   for (unsigned i = 0; i < 4; ++i) {
10588     unsigned Offset = 4*i;
10589     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10590     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10591 
10592     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10593                            PtrInfo.getWithOffset(Offset));
10594     LoadChains[i] = Loads[i].getValue(1);
10595   }
10596 
10597   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10598 
10599   SDValue Stores[4];
10600   for (unsigned i = 0; i < 4; ++i) {
10601     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10602     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10603 
10604     Stores[i] = DAG.getTruncStore(
10605         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10606         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10607         SN->getAAInfo());
10608   }
10609 
10610   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10611 
10612   return StoreChain;
10613 }
10614 
10615 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10616   SDLoc dl(Op);
10617   if (Op.getValueType() == MVT::v4i32) {
10618     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10619 
10620     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10621     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10622 
10623     SDValue RHSSwap =   // = vrlw RHS, 16
10624       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10625 
10626     // Shrinkify inputs to v8i16.
10627     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10628     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10629     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10630 
10631     // Low parts multiplied together, generating 32-bit results (we ignore the
10632     // top parts).
10633     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10634                                         LHS, RHS, DAG, dl, MVT::v4i32);
10635 
10636     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10637                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10638     // Shift the high parts up 16 bits.
10639     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10640                               Neg16, DAG, dl);
10641     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10642   } else if (Op.getValueType() == MVT::v16i8) {
10643     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10644     bool isLittleEndian = Subtarget.isLittleEndian();
10645 
10646     // Multiply the even 8-bit parts, producing 16-bit sums.
10647     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10648                                            LHS, RHS, DAG, dl, MVT::v8i16);
10649     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10650 
10651     // Multiply the odd 8-bit parts, producing 16-bit sums.
10652     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10653                                           LHS, RHS, DAG, dl, MVT::v8i16);
10654     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10655 
10656     // Merge the results together.  Because vmuleub and vmuloub are
10657     // instructions with a big-endian bias, we must reverse the
10658     // element numbering and reverse the meaning of "odd" and "even"
10659     // when generating little endian code.
10660     int Ops[16];
10661     for (unsigned i = 0; i != 8; ++i) {
10662       if (isLittleEndian) {
10663         Ops[i*2  ] = 2*i;
10664         Ops[i*2+1] = 2*i+16;
10665       } else {
10666         Ops[i*2  ] = 2*i+1;
10667         Ops[i*2+1] = 2*i+1+16;
10668       }
10669     }
10670     if (isLittleEndian)
10671       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10672     else
10673       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10674   } else {
10675     llvm_unreachable("Unknown mul to lower!");
10676   }
10677 }
10678 
10679 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10680 
10681   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10682 
10683   EVT VT = Op.getValueType();
10684   assert(VT.isVector() &&
10685          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10686   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10687           VT == MVT::v16i8) &&
10688          "Unexpected vector element type!");
10689   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10690          "Current subtarget doesn't support smax v2i64!");
10691 
10692   // For vector abs, it can be lowered to:
10693   // abs x
10694   // ==>
10695   // y = -x
10696   // smax(x, y)
10697 
10698   SDLoc dl(Op);
10699   SDValue X = Op.getOperand(0);
10700   SDValue Zero = DAG.getConstant(0, dl, VT);
10701   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10702 
10703   // SMAX patch https://reviews.llvm.org/D47332
10704   // hasn't landed yet, so use intrinsic first here.
10705   // TODO: Should use SMAX directly once SMAX patch landed
10706   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10707   if (VT == MVT::v2i64)
10708     BifID = Intrinsic::ppc_altivec_vmaxsd;
10709   else if (VT == MVT::v8i16)
10710     BifID = Intrinsic::ppc_altivec_vmaxsh;
10711   else if (VT == MVT::v16i8)
10712     BifID = Intrinsic::ppc_altivec_vmaxsb;
10713 
10714   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10715 }
10716 
10717 // Custom lowering for fpext vf32 to v2f64
10718 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10719 
10720   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10721          "Should only be called for ISD::FP_EXTEND");
10722 
10723   // We only want to custom lower an extend from v2f32 to v2f64.
10724   if (Op.getValueType() != MVT::v2f64 ||
10725       Op.getOperand(0).getValueType() != MVT::v2f32)
10726     return SDValue();
10727 
10728   SDLoc dl(Op);
10729   SDValue Op0 = Op.getOperand(0);
10730 
10731   switch (Op0.getOpcode()) {
10732   default:
10733     return SDValue();
10734   case ISD::EXTRACT_SUBVECTOR: {
10735     assert(Op0.getNumOperands() == 2 &&
10736            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10737            "Node should have 2 operands with second one being a constant!");
10738 
10739     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10740       return SDValue();
10741 
10742     // Custom lower is only done for high or low doubleword.
10743     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10744     if (Idx % 2 != 0)
10745       return SDValue();
10746 
10747     // Since input is v4f32, at this point Idx is either 0 or 2.
10748     // Shift to get the doubleword position we want.
10749     int DWord = Idx >> 1;
10750 
10751     // High and low word positions are different on little endian.
10752     if (Subtarget.isLittleEndian())
10753       DWord ^= 0x1;
10754 
10755     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10756                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10757   }
10758   case ISD::FADD:
10759   case ISD::FMUL:
10760   case ISD::FSUB: {
10761     SDValue NewLoad[2];
10762     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10763       // Ensure both input are loads.
10764       SDValue LdOp = Op0.getOperand(i);
10765       if (LdOp.getOpcode() != ISD::LOAD)
10766         return SDValue();
10767       // Generate new load node.
10768       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10769       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10770       NewLoad[i] = DAG.getMemIntrinsicNode(
10771           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10772           LD->getMemoryVT(), LD->getMemOperand());
10773     }
10774     SDValue NewOp =
10775         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10776                     NewLoad[1], Op0.getNode()->getFlags());
10777     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10778                        DAG.getConstant(0, dl, MVT::i32));
10779   }
10780   case ISD::LOAD: {
10781     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10782     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10783     SDValue NewLd = DAG.getMemIntrinsicNode(
10784         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10785         LD->getMemoryVT(), LD->getMemOperand());
10786     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10787                        DAG.getConstant(0, dl, MVT::i32));
10788   }
10789   }
10790   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10791 }
10792 
10793 /// LowerOperation - Provide custom lowering hooks for some operations.
10794 ///
10795 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10796   switch (Op.getOpcode()) {
10797   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10798   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10799   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10800   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10801   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10802   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10803   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10804   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10805   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10806 
10807   // Variable argument lowering.
10808   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10809   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10810   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10811 
10812   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10813   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10814   case ISD::GET_DYNAMIC_AREA_OFFSET:
10815     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10816 
10817   // Exception handling lowering.
10818   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10819   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10820   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10821 
10822   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10823   case ISD::STORE:              return LowerSTORE(Op, DAG);
10824   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10825   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10826   case ISD::FP_TO_UINT:
10827   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10828   case ISD::UINT_TO_FP:
10829   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10830   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10831 
10832   // Lower 64-bit shifts.
10833   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10834   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10835   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10836 
10837   // Vector-related lowering.
10838   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10839   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10840   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10841   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10842   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10843   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10844   case ISD::MUL:                return LowerMUL(Op, DAG);
10845   case ISD::ABS:                return LowerABS(Op, DAG);
10846   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10847 
10848   // For counter-based loop handling.
10849   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10850 
10851   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10852 
10853   // Frame & Return address.
10854   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10855   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10856 
10857   case ISD::INTRINSIC_VOID:
10858     return LowerINTRINSIC_VOID(Op, DAG);
10859   case ISD::SREM:
10860   case ISD::UREM:
10861     return LowerREM(Op, DAG);
10862   case ISD::BSWAP:
10863     return LowerBSWAP(Op, DAG);
10864   case ISD::ATOMIC_CMP_SWAP:
10865     return LowerATOMIC_CMP_SWAP(Op, DAG);
10866   }
10867 }
10868 
10869 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10870                                            SmallVectorImpl<SDValue>&Results,
10871                                            SelectionDAG &DAG) const {
10872   SDLoc dl(N);
10873   switch (N->getOpcode()) {
10874   default:
10875     llvm_unreachable("Do not know how to custom type legalize this operation!");
10876   case ISD::READCYCLECOUNTER: {
10877     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10878     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10879 
10880     Results.push_back(
10881         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10882     Results.push_back(RTB.getValue(2));
10883     break;
10884   }
10885   case ISD::INTRINSIC_W_CHAIN: {
10886     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10887         Intrinsic::loop_decrement)
10888       break;
10889 
10890     assert(N->getValueType(0) == MVT::i1 &&
10891            "Unexpected result type for CTR decrement intrinsic");
10892     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10893                                  N->getValueType(0));
10894     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10895     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10896                                  N->getOperand(1));
10897 
10898     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10899     Results.push_back(NewInt.getValue(1));
10900     break;
10901   }
10902   case ISD::VAARG: {
10903     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10904       return;
10905 
10906     EVT VT = N->getValueType(0);
10907 
10908     if (VT == MVT::i64) {
10909       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10910 
10911       Results.push_back(NewNode);
10912       Results.push_back(NewNode.getValue(1));
10913     }
10914     return;
10915   }
10916   case ISD::FP_TO_SINT:
10917   case ISD::FP_TO_UINT:
10918     // LowerFP_TO_INT() can only handle f32 and f64.
10919     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10920       return;
10921     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10922     return;
10923   case ISD::TRUNCATE: {
10924     EVT TrgVT = N->getValueType(0);
10925     EVT OpVT = N->getOperand(0).getValueType();
10926     if (TrgVT.isVector() &&
10927         isOperationCustom(N->getOpcode(), TrgVT) &&
10928         OpVT.getSizeInBits() <= 128 &&
10929         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10930       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10931     return;
10932   }
10933   case ISD::BITCAST:
10934     // Don't handle bitcast here.
10935     return;
10936   }
10937 }
10938 
10939 //===----------------------------------------------------------------------===//
10940 //  Other Lowering Code
10941 //===----------------------------------------------------------------------===//
10942 
10943 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10944   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10945   Function *Func = Intrinsic::getDeclaration(M, Id);
10946   return Builder.CreateCall(Func, {});
10947 }
10948 
10949 // The mappings for emitLeading/TrailingFence is taken from
10950 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10951 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10952                                                  Instruction *Inst,
10953                                                  AtomicOrdering Ord) const {
10954   if (Ord == AtomicOrdering::SequentiallyConsistent)
10955     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10956   if (isReleaseOrStronger(Ord))
10957     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10958   return nullptr;
10959 }
10960 
10961 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10962                                                   Instruction *Inst,
10963                                                   AtomicOrdering Ord) const {
10964   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10965     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10966     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10967     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10968     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10969       return Builder.CreateCall(
10970           Intrinsic::getDeclaration(
10971               Builder.GetInsertBlock()->getParent()->getParent(),
10972               Intrinsic::ppc_cfence, {Inst->getType()}),
10973           {Inst});
10974     // FIXME: Can use isync for rmw operation.
10975     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10976   }
10977   return nullptr;
10978 }
10979 
10980 MachineBasicBlock *
10981 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10982                                     unsigned AtomicSize,
10983                                     unsigned BinOpcode,
10984                                     unsigned CmpOpcode,
10985                                     unsigned CmpPred) const {
10986   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10987   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10988 
10989   auto LoadMnemonic = PPC::LDARX;
10990   auto StoreMnemonic = PPC::STDCX;
10991   switch (AtomicSize) {
10992   default:
10993     llvm_unreachable("Unexpected size of atomic entity");
10994   case 1:
10995     LoadMnemonic = PPC::LBARX;
10996     StoreMnemonic = PPC::STBCX;
10997     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10998     break;
10999   case 2:
11000     LoadMnemonic = PPC::LHARX;
11001     StoreMnemonic = PPC::STHCX;
11002     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11003     break;
11004   case 4:
11005     LoadMnemonic = PPC::LWARX;
11006     StoreMnemonic = PPC::STWCX;
11007     break;
11008   case 8:
11009     LoadMnemonic = PPC::LDARX;
11010     StoreMnemonic = PPC::STDCX;
11011     break;
11012   }
11013 
11014   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11015   MachineFunction *F = BB->getParent();
11016   MachineFunction::iterator It = ++BB->getIterator();
11017 
11018   Register dest = MI.getOperand(0).getReg();
11019   Register ptrA = MI.getOperand(1).getReg();
11020   Register ptrB = MI.getOperand(2).getReg();
11021   Register incr = MI.getOperand(3).getReg();
11022   DebugLoc dl = MI.getDebugLoc();
11023 
11024   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11025   MachineBasicBlock *loop2MBB =
11026     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11027   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11028   F->insert(It, loopMBB);
11029   if (CmpOpcode)
11030     F->insert(It, loop2MBB);
11031   F->insert(It, exitMBB);
11032   exitMBB->splice(exitMBB->begin(), BB,
11033                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11034   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11035 
11036   MachineRegisterInfo &RegInfo = F->getRegInfo();
11037   Register TmpReg = (!BinOpcode) ? incr :
11038     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11039                                            : &PPC::GPRCRegClass);
11040 
11041   //  thisMBB:
11042   //   ...
11043   //   fallthrough --> loopMBB
11044   BB->addSuccessor(loopMBB);
11045 
11046   //  loopMBB:
11047   //   l[wd]arx dest, ptr
11048   //   add r0, dest, incr
11049   //   st[wd]cx. r0, ptr
11050   //   bne- loopMBB
11051   //   fallthrough --> exitMBB
11052 
11053   // For max/min...
11054   //  loopMBB:
11055   //   l[wd]arx dest, ptr
11056   //   cmpl?[wd] incr, dest
11057   //   bgt exitMBB
11058   //  loop2MBB:
11059   //   st[wd]cx. dest, ptr
11060   //   bne- loopMBB
11061   //   fallthrough --> exitMBB
11062 
11063   BB = loopMBB;
11064   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11065     .addReg(ptrA).addReg(ptrB);
11066   if (BinOpcode)
11067     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11068   if (CmpOpcode) {
11069     // Signed comparisons of byte or halfword values must be sign-extended.
11070     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11071       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11072       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11073               ExtReg).addReg(dest);
11074       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11075         .addReg(incr).addReg(ExtReg);
11076     } else
11077       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11078         .addReg(incr).addReg(dest);
11079 
11080     BuildMI(BB, dl, TII->get(PPC::BCC))
11081       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11082     BB->addSuccessor(loop2MBB);
11083     BB->addSuccessor(exitMBB);
11084     BB = loop2MBB;
11085   }
11086   BuildMI(BB, dl, TII->get(StoreMnemonic))
11087     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11088   BuildMI(BB, dl, TII->get(PPC::BCC))
11089     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11090   BB->addSuccessor(loopMBB);
11091   BB->addSuccessor(exitMBB);
11092 
11093   //  exitMBB:
11094   //   ...
11095   BB = exitMBB;
11096   return BB;
11097 }
11098 
11099 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11100     MachineInstr &MI, MachineBasicBlock *BB,
11101     bool is8bit, // operation
11102     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11103   // If we support part-word atomic mnemonics, just use them
11104   if (Subtarget.hasPartwordAtomics())
11105     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11106                             CmpPred);
11107 
11108   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11109   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11110   // In 64 bit mode we have to use 64 bits for addresses, even though the
11111   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11112   // registers without caring whether they're 32 or 64, but here we're
11113   // doing actual arithmetic on the addresses.
11114   bool is64bit = Subtarget.isPPC64();
11115   bool isLittleEndian = Subtarget.isLittleEndian();
11116   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11117 
11118   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11119   MachineFunction *F = BB->getParent();
11120   MachineFunction::iterator It = ++BB->getIterator();
11121 
11122   Register dest = MI.getOperand(0).getReg();
11123   Register ptrA = MI.getOperand(1).getReg();
11124   Register ptrB = MI.getOperand(2).getReg();
11125   Register incr = MI.getOperand(3).getReg();
11126   DebugLoc dl = MI.getDebugLoc();
11127 
11128   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11129   MachineBasicBlock *loop2MBB =
11130       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11131   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11132   F->insert(It, loopMBB);
11133   if (CmpOpcode)
11134     F->insert(It, loop2MBB);
11135   F->insert(It, exitMBB);
11136   exitMBB->splice(exitMBB->begin(), BB,
11137                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11138   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11139 
11140   MachineRegisterInfo &RegInfo = F->getRegInfo();
11141   const TargetRegisterClass *RC =
11142       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11143   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11144 
11145   Register PtrReg = RegInfo.createVirtualRegister(RC);
11146   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11147   Register ShiftReg =
11148       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11149   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11150   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11151   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11152   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11153   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11154   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11155   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11156   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11157   Register Ptr1Reg;
11158   Register TmpReg =
11159       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11160 
11161   //  thisMBB:
11162   //   ...
11163   //   fallthrough --> loopMBB
11164   BB->addSuccessor(loopMBB);
11165 
11166   // The 4-byte load must be aligned, while a char or short may be
11167   // anywhere in the word.  Hence all this nasty bookkeeping code.
11168   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11169   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11170   //   xori shift, shift1, 24 [16]
11171   //   rlwinm ptr, ptr1, 0, 0, 29
11172   //   slw incr2, incr, shift
11173   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11174   //   slw mask, mask2, shift
11175   //  loopMBB:
11176   //   lwarx tmpDest, ptr
11177   //   add tmp, tmpDest, incr2
11178   //   andc tmp2, tmpDest, mask
11179   //   and tmp3, tmp, mask
11180   //   or tmp4, tmp3, tmp2
11181   //   stwcx. tmp4, ptr
11182   //   bne- loopMBB
11183   //   fallthrough --> exitMBB
11184   //   srw dest, tmpDest, shift
11185   if (ptrA != ZeroReg) {
11186     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11187     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11188         .addReg(ptrA)
11189         .addReg(ptrB);
11190   } else {
11191     Ptr1Reg = ptrB;
11192   }
11193   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11194   // mode.
11195   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11196       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11197       .addImm(3)
11198       .addImm(27)
11199       .addImm(is8bit ? 28 : 27);
11200   if (!isLittleEndian)
11201     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11202         .addReg(Shift1Reg)
11203         .addImm(is8bit ? 24 : 16);
11204   if (is64bit)
11205     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11206         .addReg(Ptr1Reg)
11207         .addImm(0)
11208         .addImm(61);
11209   else
11210     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11211         .addReg(Ptr1Reg)
11212         .addImm(0)
11213         .addImm(0)
11214         .addImm(29);
11215   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11216   if (is8bit)
11217     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11218   else {
11219     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11220     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11221         .addReg(Mask3Reg)
11222         .addImm(65535);
11223   }
11224   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11225       .addReg(Mask2Reg)
11226       .addReg(ShiftReg);
11227 
11228   BB = loopMBB;
11229   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11230       .addReg(ZeroReg)
11231       .addReg(PtrReg);
11232   if (BinOpcode)
11233     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11234         .addReg(Incr2Reg)
11235         .addReg(TmpDestReg);
11236   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11237       .addReg(TmpDestReg)
11238       .addReg(MaskReg);
11239   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11240   if (CmpOpcode) {
11241     // For unsigned comparisons, we can directly compare the shifted values.
11242     // For signed comparisons we shift and sign extend.
11243     Register SReg = RegInfo.createVirtualRegister(GPRC);
11244     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11245         .addReg(TmpDestReg)
11246         .addReg(MaskReg);
11247     unsigned ValueReg = SReg;
11248     unsigned CmpReg = Incr2Reg;
11249     if (CmpOpcode == PPC::CMPW) {
11250       ValueReg = RegInfo.createVirtualRegister(GPRC);
11251       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11252           .addReg(SReg)
11253           .addReg(ShiftReg);
11254       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11255       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11256           .addReg(ValueReg);
11257       ValueReg = ValueSReg;
11258       CmpReg = incr;
11259     }
11260     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11261         .addReg(CmpReg)
11262         .addReg(ValueReg);
11263     BuildMI(BB, dl, TII->get(PPC::BCC))
11264         .addImm(CmpPred)
11265         .addReg(PPC::CR0)
11266         .addMBB(exitMBB);
11267     BB->addSuccessor(loop2MBB);
11268     BB->addSuccessor(exitMBB);
11269     BB = loop2MBB;
11270   }
11271   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11272   BuildMI(BB, dl, TII->get(PPC::STWCX))
11273       .addReg(Tmp4Reg)
11274       .addReg(ZeroReg)
11275       .addReg(PtrReg);
11276   BuildMI(BB, dl, TII->get(PPC::BCC))
11277       .addImm(PPC::PRED_NE)
11278       .addReg(PPC::CR0)
11279       .addMBB(loopMBB);
11280   BB->addSuccessor(loopMBB);
11281   BB->addSuccessor(exitMBB);
11282 
11283   //  exitMBB:
11284   //   ...
11285   BB = exitMBB;
11286   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11287       .addReg(TmpDestReg)
11288       .addReg(ShiftReg);
11289   return BB;
11290 }
11291 
11292 llvm::MachineBasicBlock *
11293 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11294                                     MachineBasicBlock *MBB) const {
11295   DebugLoc DL = MI.getDebugLoc();
11296   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11297   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11298 
11299   MachineFunction *MF = MBB->getParent();
11300   MachineRegisterInfo &MRI = MF->getRegInfo();
11301 
11302   const BasicBlock *BB = MBB->getBasicBlock();
11303   MachineFunction::iterator I = ++MBB->getIterator();
11304 
11305   Register DstReg = MI.getOperand(0).getReg();
11306   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11307   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11308   Register mainDstReg = MRI.createVirtualRegister(RC);
11309   Register restoreDstReg = MRI.createVirtualRegister(RC);
11310 
11311   MVT PVT = getPointerTy(MF->getDataLayout());
11312   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11313          "Invalid Pointer Size!");
11314   // For v = setjmp(buf), we generate
11315   //
11316   // thisMBB:
11317   //  SjLjSetup mainMBB
11318   //  bl mainMBB
11319   //  v_restore = 1
11320   //  b sinkMBB
11321   //
11322   // mainMBB:
11323   //  buf[LabelOffset] = LR
11324   //  v_main = 0
11325   //
11326   // sinkMBB:
11327   //  v = phi(main, restore)
11328   //
11329 
11330   MachineBasicBlock *thisMBB = MBB;
11331   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11332   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11333   MF->insert(I, mainMBB);
11334   MF->insert(I, sinkMBB);
11335 
11336   MachineInstrBuilder MIB;
11337 
11338   // Transfer the remainder of BB and its successor edges to sinkMBB.
11339   sinkMBB->splice(sinkMBB->begin(), MBB,
11340                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11341   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11342 
11343   // Note that the structure of the jmp_buf used here is not compatible
11344   // with that used by libc, and is not designed to be. Specifically, it
11345   // stores only those 'reserved' registers that LLVM does not otherwise
11346   // understand how to spill. Also, by convention, by the time this
11347   // intrinsic is called, Clang has already stored the frame address in the
11348   // first slot of the buffer and stack address in the third. Following the
11349   // X86 target code, we'll store the jump address in the second slot. We also
11350   // need to save the TOC pointer (R2) to handle jumps between shared
11351   // libraries, and that will be stored in the fourth slot. The thread
11352   // identifier (R13) is not affected.
11353 
11354   // thisMBB:
11355   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11356   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11357   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11358 
11359   // Prepare IP either in reg.
11360   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11361   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11362   Register BufReg = MI.getOperand(1).getReg();
11363 
11364   if (Subtarget.is64BitELFABI()) {
11365     setUsesTOCBasePtr(*MBB->getParent());
11366     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11367               .addReg(PPC::X2)
11368               .addImm(TOCOffset)
11369               .addReg(BufReg)
11370               .cloneMemRefs(MI);
11371   }
11372 
11373   // Naked functions never have a base pointer, and so we use r1. For all
11374   // other functions, this decision must be delayed until during PEI.
11375   unsigned BaseReg;
11376   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11377     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11378   else
11379     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11380 
11381   MIB = BuildMI(*thisMBB, MI, DL,
11382                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11383             .addReg(BaseReg)
11384             .addImm(BPOffset)
11385             .addReg(BufReg)
11386             .cloneMemRefs(MI);
11387 
11388   // Setup
11389   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11390   MIB.addRegMask(TRI->getNoPreservedMask());
11391 
11392   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11393 
11394   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11395           .addMBB(mainMBB);
11396   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11397 
11398   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11399   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11400 
11401   // mainMBB:
11402   //  mainDstReg = 0
11403   MIB =
11404       BuildMI(mainMBB, DL,
11405               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11406 
11407   // Store IP
11408   if (Subtarget.isPPC64()) {
11409     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11410             .addReg(LabelReg)
11411             .addImm(LabelOffset)
11412             .addReg(BufReg);
11413   } else {
11414     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11415             .addReg(LabelReg)
11416             .addImm(LabelOffset)
11417             .addReg(BufReg);
11418   }
11419   MIB.cloneMemRefs(MI);
11420 
11421   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11422   mainMBB->addSuccessor(sinkMBB);
11423 
11424   // sinkMBB:
11425   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11426           TII->get(PPC::PHI), DstReg)
11427     .addReg(mainDstReg).addMBB(mainMBB)
11428     .addReg(restoreDstReg).addMBB(thisMBB);
11429 
11430   MI.eraseFromParent();
11431   return sinkMBB;
11432 }
11433 
11434 MachineBasicBlock *
11435 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11436                                      MachineBasicBlock *MBB) const {
11437   DebugLoc DL = MI.getDebugLoc();
11438   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11439 
11440   MachineFunction *MF = MBB->getParent();
11441   MachineRegisterInfo &MRI = MF->getRegInfo();
11442 
11443   MVT PVT = getPointerTy(MF->getDataLayout());
11444   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11445          "Invalid Pointer Size!");
11446 
11447   const TargetRegisterClass *RC =
11448     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11449   Register Tmp = MRI.createVirtualRegister(RC);
11450   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11451   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11452   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11453   unsigned BP =
11454       (PVT == MVT::i64)
11455           ? PPC::X30
11456           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11457                                                               : PPC::R30);
11458 
11459   MachineInstrBuilder MIB;
11460 
11461   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11462   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11463   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11464   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11465 
11466   Register BufReg = MI.getOperand(0).getReg();
11467 
11468   // Reload FP (the jumped-to function may not have had a
11469   // frame pointer, and if so, then its r31 will be restored
11470   // as necessary).
11471   if (PVT == MVT::i64) {
11472     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11473             .addImm(0)
11474             .addReg(BufReg);
11475   } else {
11476     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11477             .addImm(0)
11478             .addReg(BufReg);
11479   }
11480   MIB.cloneMemRefs(MI);
11481 
11482   // Reload IP
11483   if (PVT == MVT::i64) {
11484     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11485             .addImm(LabelOffset)
11486             .addReg(BufReg);
11487   } else {
11488     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11489             .addImm(LabelOffset)
11490             .addReg(BufReg);
11491   }
11492   MIB.cloneMemRefs(MI);
11493 
11494   // Reload SP
11495   if (PVT == MVT::i64) {
11496     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11497             .addImm(SPOffset)
11498             .addReg(BufReg);
11499   } else {
11500     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11501             .addImm(SPOffset)
11502             .addReg(BufReg);
11503   }
11504   MIB.cloneMemRefs(MI);
11505 
11506   // Reload BP
11507   if (PVT == MVT::i64) {
11508     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11509             .addImm(BPOffset)
11510             .addReg(BufReg);
11511   } else {
11512     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11513             .addImm(BPOffset)
11514             .addReg(BufReg);
11515   }
11516   MIB.cloneMemRefs(MI);
11517 
11518   // Reload TOC
11519   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11520     setUsesTOCBasePtr(*MBB->getParent());
11521     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11522               .addImm(TOCOffset)
11523               .addReg(BufReg)
11524               .cloneMemRefs(MI);
11525   }
11526 
11527   // Jump
11528   BuildMI(*MBB, MI, DL,
11529           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11530   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11531 
11532   MI.eraseFromParent();
11533   return MBB;
11534 }
11535 
11536 MachineBasicBlock *
11537 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11538                                                MachineBasicBlock *BB) const {
11539   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11540       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11541     if (Subtarget.is64BitELFABI() &&
11542         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11543         !Subtarget.isUsingPCRelativeCalls()) {
11544       // Call lowering should have added an r2 operand to indicate a dependence
11545       // on the TOC base pointer value. It can't however, because there is no
11546       // way to mark the dependence as implicit there, and so the stackmap code
11547       // will confuse it with a regular operand. Instead, add the dependence
11548       // here.
11549       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11550     }
11551 
11552     return emitPatchPoint(MI, BB);
11553   }
11554 
11555   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11556       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11557     return emitEHSjLjSetJmp(MI, BB);
11558   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11559              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11560     return emitEHSjLjLongJmp(MI, BB);
11561   }
11562 
11563   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11564 
11565   // To "insert" these instructions we actually have to insert their
11566   // control-flow patterns.
11567   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11568   MachineFunction::iterator It = ++BB->getIterator();
11569 
11570   MachineFunction *F = BB->getParent();
11571 
11572   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11573       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11574       MI.getOpcode() == PPC::SELECT_I8) {
11575     SmallVector<MachineOperand, 2> Cond;
11576     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11577         MI.getOpcode() == PPC::SELECT_CC_I8)
11578       Cond.push_back(MI.getOperand(4));
11579     else
11580       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11581     Cond.push_back(MI.getOperand(1));
11582 
11583     DebugLoc dl = MI.getDebugLoc();
11584     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11585                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11586   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11587              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11588              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11589              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11590              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11591              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11592              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11593              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11594              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11595              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11596              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11597              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11598              MI.getOpcode() == PPC::SELECT_F4 ||
11599              MI.getOpcode() == PPC::SELECT_F8 ||
11600              MI.getOpcode() == PPC::SELECT_F16 ||
11601              MI.getOpcode() == PPC::SELECT_QFRC ||
11602              MI.getOpcode() == PPC::SELECT_QSRC ||
11603              MI.getOpcode() == PPC::SELECT_QBRC ||
11604              MI.getOpcode() == PPC::SELECT_SPE ||
11605              MI.getOpcode() == PPC::SELECT_SPE4 ||
11606              MI.getOpcode() == PPC::SELECT_VRRC ||
11607              MI.getOpcode() == PPC::SELECT_VSFRC ||
11608              MI.getOpcode() == PPC::SELECT_VSSRC ||
11609              MI.getOpcode() == PPC::SELECT_VSRC) {
11610     // The incoming instruction knows the destination vreg to set, the
11611     // condition code register to branch on, the true/false values to
11612     // select between, and a branch opcode to use.
11613 
11614     //  thisMBB:
11615     //  ...
11616     //   TrueVal = ...
11617     //   cmpTY ccX, r1, r2
11618     //   bCC copy1MBB
11619     //   fallthrough --> copy0MBB
11620     MachineBasicBlock *thisMBB = BB;
11621     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11622     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11623     DebugLoc dl = MI.getDebugLoc();
11624     F->insert(It, copy0MBB);
11625     F->insert(It, sinkMBB);
11626 
11627     // Transfer the remainder of BB and its successor edges to sinkMBB.
11628     sinkMBB->splice(sinkMBB->begin(), BB,
11629                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11630     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11631 
11632     // Next, add the true and fallthrough blocks as its successors.
11633     BB->addSuccessor(copy0MBB);
11634     BB->addSuccessor(sinkMBB);
11635 
11636     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11637         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11638         MI.getOpcode() == PPC::SELECT_F16 ||
11639         MI.getOpcode() == PPC::SELECT_SPE4 ||
11640         MI.getOpcode() == PPC::SELECT_SPE ||
11641         MI.getOpcode() == PPC::SELECT_QFRC ||
11642         MI.getOpcode() == PPC::SELECT_QSRC ||
11643         MI.getOpcode() == PPC::SELECT_QBRC ||
11644         MI.getOpcode() == PPC::SELECT_VRRC ||
11645         MI.getOpcode() == PPC::SELECT_VSFRC ||
11646         MI.getOpcode() == PPC::SELECT_VSSRC ||
11647         MI.getOpcode() == PPC::SELECT_VSRC) {
11648       BuildMI(BB, dl, TII->get(PPC::BC))
11649           .addReg(MI.getOperand(1).getReg())
11650           .addMBB(sinkMBB);
11651     } else {
11652       unsigned SelectPred = MI.getOperand(4).getImm();
11653       BuildMI(BB, dl, TII->get(PPC::BCC))
11654           .addImm(SelectPred)
11655           .addReg(MI.getOperand(1).getReg())
11656           .addMBB(sinkMBB);
11657     }
11658 
11659     //  copy0MBB:
11660     //   %FalseValue = ...
11661     //   # fallthrough to sinkMBB
11662     BB = copy0MBB;
11663 
11664     // Update machine-CFG edges
11665     BB->addSuccessor(sinkMBB);
11666 
11667     //  sinkMBB:
11668     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11669     //  ...
11670     BB = sinkMBB;
11671     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11672         .addReg(MI.getOperand(3).getReg())
11673         .addMBB(copy0MBB)
11674         .addReg(MI.getOperand(2).getReg())
11675         .addMBB(thisMBB);
11676   } else if (MI.getOpcode() == PPC::ReadTB) {
11677     // To read the 64-bit time-base register on a 32-bit target, we read the
11678     // two halves. Should the counter have wrapped while it was being read, we
11679     // need to try again.
11680     // ...
11681     // readLoop:
11682     // mfspr Rx,TBU # load from TBU
11683     // mfspr Ry,TB  # load from TB
11684     // mfspr Rz,TBU # load from TBU
11685     // cmpw crX,Rx,Rz # check if 'old'='new'
11686     // bne readLoop   # branch if they're not equal
11687     // ...
11688 
11689     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11690     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11691     DebugLoc dl = MI.getDebugLoc();
11692     F->insert(It, readMBB);
11693     F->insert(It, sinkMBB);
11694 
11695     // Transfer the remainder of BB and its successor edges to sinkMBB.
11696     sinkMBB->splice(sinkMBB->begin(), BB,
11697                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11698     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11699 
11700     BB->addSuccessor(readMBB);
11701     BB = readMBB;
11702 
11703     MachineRegisterInfo &RegInfo = F->getRegInfo();
11704     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11705     Register LoReg = MI.getOperand(0).getReg();
11706     Register HiReg = MI.getOperand(1).getReg();
11707 
11708     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11709     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11710     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11711 
11712     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11713 
11714     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11715         .addReg(HiReg)
11716         .addReg(ReadAgainReg);
11717     BuildMI(BB, dl, TII->get(PPC::BCC))
11718         .addImm(PPC::PRED_NE)
11719         .addReg(CmpReg)
11720         .addMBB(readMBB);
11721 
11722     BB->addSuccessor(readMBB);
11723     BB->addSuccessor(sinkMBB);
11724   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11725     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11726   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11727     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11728   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11729     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11730   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11731     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11732 
11733   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11734     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11735   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11736     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11737   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11738     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11739   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11740     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11741 
11742   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11743     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11744   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11745     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11746   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11747     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11748   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11749     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11750 
11751   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11752     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11753   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11754     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11755   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11756     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11757   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11758     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11759 
11760   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11761     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11762   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11763     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11764   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11765     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11766   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11767     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11768 
11769   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11770     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11771   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11772     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11773   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11774     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11775   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11776     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11777 
11778   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11779     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11780   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11781     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11782   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11783     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11784   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11785     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11786 
11787   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11788     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11789   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11790     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11791   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11792     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11793   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11794     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11795 
11796   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11797     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11798   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11799     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11800   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11801     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11802   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11803     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11804 
11805   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11806     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11807   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11808     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11809   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11810     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11811   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11812     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11813 
11814   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11815     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11816   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11817     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11818   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11819     BB = EmitAtomicBinary(MI, BB, 4, 0);
11820   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11821     BB = EmitAtomicBinary(MI, BB, 8, 0);
11822   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11823            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11824            (Subtarget.hasPartwordAtomics() &&
11825             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11826            (Subtarget.hasPartwordAtomics() &&
11827             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11828     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11829 
11830     auto LoadMnemonic = PPC::LDARX;
11831     auto StoreMnemonic = PPC::STDCX;
11832     switch (MI.getOpcode()) {
11833     default:
11834       llvm_unreachable("Compare and swap of unknown size");
11835     case PPC::ATOMIC_CMP_SWAP_I8:
11836       LoadMnemonic = PPC::LBARX;
11837       StoreMnemonic = PPC::STBCX;
11838       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11839       break;
11840     case PPC::ATOMIC_CMP_SWAP_I16:
11841       LoadMnemonic = PPC::LHARX;
11842       StoreMnemonic = PPC::STHCX;
11843       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11844       break;
11845     case PPC::ATOMIC_CMP_SWAP_I32:
11846       LoadMnemonic = PPC::LWARX;
11847       StoreMnemonic = PPC::STWCX;
11848       break;
11849     case PPC::ATOMIC_CMP_SWAP_I64:
11850       LoadMnemonic = PPC::LDARX;
11851       StoreMnemonic = PPC::STDCX;
11852       break;
11853     }
11854     Register dest = MI.getOperand(0).getReg();
11855     Register ptrA = MI.getOperand(1).getReg();
11856     Register ptrB = MI.getOperand(2).getReg();
11857     Register oldval = MI.getOperand(3).getReg();
11858     Register newval = MI.getOperand(4).getReg();
11859     DebugLoc dl = MI.getDebugLoc();
11860 
11861     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11862     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11863     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11864     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11865     F->insert(It, loop1MBB);
11866     F->insert(It, loop2MBB);
11867     F->insert(It, midMBB);
11868     F->insert(It, exitMBB);
11869     exitMBB->splice(exitMBB->begin(), BB,
11870                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11871     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11872 
11873     //  thisMBB:
11874     //   ...
11875     //   fallthrough --> loopMBB
11876     BB->addSuccessor(loop1MBB);
11877 
11878     // loop1MBB:
11879     //   l[bhwd]arx dest, ptr
11880     //   cmp[wd] dest, oldval
11881     //   bne- midMBB
11882     // loop2MBB:
11883     //   st[bhwd]cx. newval, ptr
11884     //   bne- loopMBB
11885     //   b exitBB
11886     // midMBB:
11887     //   st[bhwd]cx. dest, ptr
11888     // exitBB:
11889     BB = loop1MBB;
11890     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11891     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11892         .addReg(oldval)
11893         .addReg(dest);
11894     BuildMI(BB, dl, TII->get(PPC::BCC))
11895         .addImm(PPC::PRED_NE)
11896         .addReg(PPC::CR0)
11897         .addMBB(midMBB);
11898     BB->addSuccessor(loop2MBB);
11899     BB->addSuccessor(midMBB);
11900 
11901     BB = loop2MBB;
11902     BuildMI(BB, dl, TII->get(StoreMnemonic))
11903         .addReg(newval)
11904         .addReg(ptrA)
11905         .addReg(ptrB);
11906     BuildMI(BB, dl, TII->get(PPC::BCC))
11907         .addImm(PPC::PRED_NE)
11908         .addReg(PPC::CR0)
11909         .addMBB(loop1MBB);
11910     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11911     BB->addSuccessor(loop1MBB);
11912     BB->addSuccessor(exitMBB);
11913 
11914     BB = midMBB;
11915     BuildMI(BB, dl, TII->get(StoreMnemonic))
11916         .addReg(dest)
11917         .addReg(ptrA)
11918         .addReg(ptrB);
11919     BB->addSuccessor(exitMBB);
11920 
11921     //  exitMBB:
11922     //   ...
11923     BB = exitMBB;
11924   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11925              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11926     // We must use 64-bit registers for addresses when targeting 64-bit,
11927     // since we're actually doing arithmetic on them.  Other registers
11928     // can be 32-bit.
11929     bool is64bit = Subtarget.isPPC64();
11930     bool isLittleEndian = Subtarget.isLittleEndian();
11931     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11932 
11933     Register dest = MI.getOperand(0).getReg();
11934     Register ptrA = MI.getOperand(1).getReg();
11935     Register ptrB = MI.getOperand(2).getReg();
11936     Register oldval = MI.getOperand(3).getReg();
11937     Register newval = MI.getOperand(4).getReg();
11938     DebugLoc dl = MI.getDebugLoc();
11939 
11940     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11941     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11942     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11943     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11944     F->insert(It, loop1MBB);
11945     F->insert(It, loop2MBB);
11946     F->insert(It, midMBB);
11947     F->insert(It, exitMBB);
11948     exitMBB->splice(exitMBB->begin(), BB,
11949                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11950     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11951 
11952     MachineRegisterInfo &RegInfo = F->getRegInfo();
11953     const TargetRegisterClass *RC =
11954         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11955     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11956 
11957     Register PtrReg = RegInfo.createVirtualRegister(RC);
11958     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11959     Register ShiftReg =
11960         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11961     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11962     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11963     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11964     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11965     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11966     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11967     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11968     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11969     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11970     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11971     Register Ptr1Reg;
11972     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11973     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11974     //  thisMBB:
11975     //   ...
11976     //   fallthrough --> loopMBB
11977     BB->addSuccessor(loop1MBB);
11978 
11979     // The 4-byte load must be aligned, while a char or short may be
11980     // anywhere in the word.  Hence all this nasty bookkeeping code.
11981     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11982     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11983     //   xori shift, shift1, 24 [16]
11984     //   rlwinm ptr, ptr1, 0, 0, 29
11985     //   slw newval2, newval, shift
11986     //   slw oldval2, oldval,shift
11987     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11988     //   slw mask, mask2, shift
11989     //   and newval3, newval2, mask
11990     //   and oldval3, oldval2, mask
11991     // loop1MBB:
11992     //   lwarx tmpDest, ptr
11993     //   and tmp, tmpDest, mask
11994     //   cmpw tmp, oldval3
11995     //   bne- midMBB
11996     // loop2MBB:
11997     //   andc tmp2, tmpDest, mask
11998     //   or tmp4, tmp2, newval3
11999     //   stwcx. tmp4, ptr
12000     //   bne- loop1MBB
12001     //   b exitBB
12002     // midMBB:
12003     //   stwcx. tmpDest, ptr
12004     // exitBB:
12005     //   srw dest, tmpDest, shift
12006     if (ptrA != ZeroReg) {
12007       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12008       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12009           .addReg(ptrA)
12010           .addReg(ptrB);
12011     } else {
12012       Ptr1Reg = ptrB;
12013     }
12014 
12015     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12016     // mode.
12017     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12018         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12019         .addImm(3)
12020         .addImm(27)
12021         .addImm(is8bit ? 28 : 27);
12022     if (!isLittleEndian)
12023       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12024           .addReg(Shift1Reg)
12025           .addImm(is8bit ? 24 : 16);
12026     if (is64bit)
12027       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12028           .addReg(Ptr1Reg)
12029           .addImm(0)
12030           .addImm(61);
12031     else
12032       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12033           .addReg(Ptr1Reg)
12034           .addImm(0)
12035           .addImm(0)
12036           .addImm(29);
12037     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12038         .addReg(newval)
12039         .addReg(ShiftReg);
12040     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12041         .addReg(oldval)
12042         .addReg(ShiftReg);
12043     if (is8bit)
12044       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12045     else {
12046       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12047       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12048           .addReg(Mask3Reg)
12049           .addImm(65535);
12050     }
12051     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12052         .addReg(Mask2Reg)
12053         .addReg(ShiftReg);
12054     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12055         .addReg(NewVal2Reg)
12056         .addReg(MaskReg);
12057     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12058         .addReg(OldVal2Reg)
12059         .addReg(MaskReg);
12060 
12061     BB = loop1MBB;
12062     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12063         .addReg(ZeroReg)
12064         .addReg(PtrReg);
12065     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12066         .addReg(TmpDestReg)
12067         .addReg(MaskReg);
12068     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12069         .addReg(TmpReg)
12070         .addReg(OldVal3Reg);
12071     BuildMI(BB, dl, TII->get(PPC::BCC))
12072         .addImm(PPC::PRED_NE)
12073         .addReg(PPC::CR0)
12074         .addMBB(midMBB);
12075     BB->addSuccessor(loop2MBB);
12076     BB->addSuccessor(midMBB);
12077 
12078     BB = loop2MBB;
12079     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12080         .addReg(TmpDestReg)
12081         .addReg(MaskReg);
12082     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12083         .addReg(Tmp2Reg)
12084         .addReg(NewVal3Reg);
12085     BuildMI(BB, dl, TII->get(PPC::STWCX))
12086         .addReg(Tmp4Reg)
12087         .addReg(ZeroReg)
12088         .addReg(PtrReg);
12089     BuildMI(BB, dl, TII->get(PPC::BCC))
12090         .addImm(PPC::PRED_NE)
12091         .addReg(PPC::CR0)
12092         .addMBB(loop1MBB);
12093     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12094     BB->addSuccessor(loop1MBB);
12095     BB->addSuccessor(exitMBB);
12096 
12097     BB = midMBB;
12098     BuildMI(BB, dl, TII->get(PPC::STWCX))
12099         .addReg(TmpDestReg)
12100         .addReg(ZeroReg)
12101         .addReg(PtrReg);
12102     BB->addSuccessor(exitMBB);
12103 
12104     //  exitMBB:
12105     //   ...
12106     BB = exitMBB;
12107     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12108         .addReg(TmpReg)
12109         .addReg(ShiftReg);
12110   } else if (MI.getOpcode() == PPC::FADDrtz) {
12111     // This pseudo performs an FADD with rounding mode temporarily forced
12112     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12113     // is not modeled at the SelectionDAG level.
12114     Register Dest = MI.getOperand(0).getReg();
12115     Register Src1 = MI.getOperand(1).getReg();
12116     Register Src2 = MI.getOperand(2).getReg();
12117     DebugLoc dl = MI.getDebugLoc();
12118 
12119     MachineRegisterInfo &RegInfo = F->getRegInfo();
12120     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12121 
12122     // Save FPSCR value.
12123     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12124 
12125     // Set rounding mode to round-to-zero.
12126     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
12127     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
12128 
12129     // Perform addition.
12130     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12131 
12132     // Restore FPSCR value.
12133     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12134   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12135              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12136              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12137              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12138     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12139                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12140                           ? PPC::ANDI8_rec
12141                           : PPC::ANDI_rec;
12142     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12143                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12144 
12145     MachineRegisterInfo &RegInfo = F->getRegInfo();
12146     Register Dest = RegInfo.createVirtualRegister(
12147         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12148 
12149     DebugLoc Dl = MI.getDebugLoc();
12150     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12151         .addReg(MI.getOperand(1).getReg())
12152         .addImm(1);
12153     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12154             MI.getOperand(0).getReg())
12155         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12156   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12157     DebugLoc Dl = MI.getDebugLoc();
12158     MachineRegisterInfo &RegInfo = F->getRegInfo();
12159     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12160     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12161     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12162             MI.getOperand(0).getReg())
12163         .addReg(CRReg);
12164   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12165     DebugLoc Dl = MI.getDebugLoc();
12166     unsigned Imm = MI.getOperand(1).getImm();
12167     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12168     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12169             MI.getOperand(0).getReg())
12170         .addReg(PPC::CR0EQ);
12171   } else if (MI.getOpcode() == PPC::SETRNDi) {
12172     DebugLoc dl = MI.getDebugLoc();
12173     Register OldFPSCRReg = MI.getOperand(0).getReg();
12174 
12175     // Save FPSCR value.
12176     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12177 
12178     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12179     // the following settings:
12180     //   00 Round to nearest
12181     //   01 Round to 0
12182     //   10 Round to +inf
12183     //   11 Round to -inf
12184 
12185     // When the operand is immediate, using the two least significant bits of
12186     // the immediate to set the bits 62:63 of FPSCR.
12187     unsigned Mode = MI.getOperand(1).getImm();
12188     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12189       .addImm(31);
12190 
12191     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12192       .addImm(30);
12193   } else if (MI.getOpcode() == PPC::SETRND) {
12194     DebugLoc dl = MI.getDebugLoc();
12195 
12196     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12197     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12198     // If the target doesn't have DirectMove, we should use stack to do the
12199     // conversion, because the target doesn't have the instructions like mtvsrd
12200     // or mfvsrd to do this conversion directly.
12201     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12202       if (Subtarget.hasDirectMove()) {
12203         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12204           .addReg(SrcReg);
12205       } else {
12206         // Use stack to do the register copy.
12207         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12208         MachineRegisterInfo &RegInfo = F->getRegInfo();
12209         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12210         if (RC == &PPC::F8RCRegClass) {
12211           // Copy register from F8RCRegClass to G8RCRegclass.
12212           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12213                  "Unsupported RegClass.");
12214 
12215           StoreOp = PPC::STFD;
12216           LoadOp = PPC::LD;
12217         } else {
12218           // Copy register from G8RCRegClass to F8RCRegclass.
12219           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12220                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12221                  "Unsupported RegClass.");
12222         }
12223 
12224         MachineFrameInfo &MFI = F->getFrameInfo();
12225         int FrameIdx = MFI.CreateStackObject(8, 8, false);
12226 
12227         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12228             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12229             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12230             MFI.getObjectAlign(FrameIdx));
12231 
12232         // Store the SrcReg into the stack.
12233         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12234           .addReg(SrcReg)
12235           .addImm(0)
12236           .addFrameIndex(FrameIdx)
12237           .addMemOperand(MMOStore);
12238 
12239         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12240             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12241             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12242             MFI.getObjectAlign(FrameIdx));
12243 
12244         // Load from the stack where SrcReg is stored, and save to DestReg,
12245         // so we have done the RegClass conversion from RegClass::SrcReg to
12246         // RegClass::DestReg.
12247         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12248           .addImm(0)
12249           .addFrameIndex(FrameIdx)
12250           .addMemOperand(MMOLoad);
12251       }
12252     };
12253 
12254     Register OldFPSCRReg = MI.getOperand(0).getReg();
12255 
12256     // Save FPSCR value.
12257     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12258 
12259     // When the operand is gprc register, use two least significant bits of the
12260     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12261     //
12262     // copy OldFPSCRTmpReg, OldFPSCRReg
12263     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12264     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12265     // copy NewFPSCRReg, NewFPSCRTmpReg
12266     // mtfsf 255, NewFPSCRReg
12267     MachineOperand SrcOp = MI.getOperand(1);
12268     MachineRegisterInfo &RegInfo = F->getRegInfo();
12269     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12270 
12271     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12272 
12273     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12274     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12275 
12276     // The first operand of INSERT_SUBREG should be a register which has
12277     // subregisters, we only care about its RegClass, so we should use an
12278     // IMPLICIT_DEF register.
12279     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12280     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12281       .addReg(ImDefReg)
12282       .add(SrcOp)
12283       .addImm(1);
12284 
12285     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12286     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12287       .addReg(OldFPSCRTmpReg)
12288       .addReg(ExtSrcReg)
12289       .addImm(0)
12290       .addImm(62);
12291 
12292     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12293     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12294 
12295     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12296     // bits of FPSCR.
12297     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12298       .addImm(255)
12299       .addReg(NewFPSCRReg)
12300       .addImm(0)
12301       .addImm(0);
12302   } else {
12303     llvm_unreachable("Unexpected instr type to insert");
12304   }
12305 
12306   MI.eraseFromParent(); // The pseudo instruction is gone now.
12307   return BB;
12308 }
12309 
12310 //===----------------------------------------------------------------------===//
12311 // Target Optimization Hooks
12312 //===----------------------------------------------------------------------===//
12313 
12314 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12315   // For the estimates, convergence is quadratic, so we essentially double the
12316   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12317   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12318   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12319   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12320   if (VT.getScalarType() == MVT::f64)
12321     RefinementSteps++;
12322   return RefinementSteps;
12323 }
12324 
12325 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12326                                            int Enabled, int &RefinementSteps,
12327                                            bool &UseOneConstNR,
12328                                            bool Reciprocal) const {
12329   EVT VT = Operand.getValueType();
12330   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12331       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12332       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12333       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12334       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12335       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12336     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12337       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12338 
12339     // The Newton-Raphson computation with a single constant does not provide
12340     // enough accuracy on some CPUs.
12341     UseOneConstNR = !Subtarget.needsTwoConstNR();
12342     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12343   }
12344   return SDValue();
12345 }
12346 
12347 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12348                                             int Enabled,
12349                                             int &RefinementSteps) const {
12350   EVT VT = Operand.getValueType();
12351   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12352       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12353       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12354       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
12355       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
12356       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
12357     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12358       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12359     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12360   }
12361   return SDValue();
12362 }
12363 
12364 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12365   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12366   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12367   // enabled for division), this functionality is redundant with the default
12368   // combiner logic (once the division -> reciprocal/multiply transformation
12369   // has taken place). As a result, this matters more for older cores than for
12370   // newer ones.
12371 
12372   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12373   // reciprocal if there are two or more FDIVs (for embedded cores with only
12374   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12375   switch (Subtarget.getCPUDirective()) {
12376   default:
12377     return 3;
12378   case PPC::DIR_440:
12379   case PPC::DIR_A2:
12380   case PPC::DIR_E500:
12381   case PPC::DIR_E500mc:
12382   case PPC::DIR_E5500:
12383     return 2;
12384   }
12385 }
12386 
12387 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12388 // collapsed, and so we need to look through chains of them.
12389 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12390                                      int64_t& Offset, SelectionDAG &DAG) {
12391   if (DAG.isBaseWithConstantOffset(Loc)) {
12392     Base = Loc.getOperand(0);
12393     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12394 
12395     // The base might itself be a base plus an offset, and if so, accumulate
12396     // that as well.
12397     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12398   }
12399 }
12400 
12401 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12402                             unsigned Bytes, int Dist,
12403                             SelectionDAG &DAG) {
12404   if (VT.getSizeInBits() / 8 != Bytes)
12405     return false;
12406 
12407   SDValue BaseLoc = Base->getBasePtr();
12408   if (Loc.getOpcode() == ISD::FrameIndex) {
12409     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12410       return false;
12411     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12412     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12413     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12414     int FS  = MFI.getObjectSize(FI);
12415     int BFS = MFI.getObjectSize(BFI);
12416     if (FS != BFS || FS != (int)Bytes) return false;
12417     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12418   }
12419 
12420   SDValue Base1 = Loc, Base2 = BaseLoc;
12421   int64_t Offset1 = 0, Offset2 = 0;
12422   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12423   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12424   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12425     return true;
12426 
12427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12428   const GlobalValue *GV1 = nullptr;
12429   const GlobalValue *GV2 = nullptr;
12430   Offset1 = 0;
12431   Offset2 = 0;
12432   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12433   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12434   if (isGA1 && isGA2 && GV1 == GV2)
12435     return Offset1 == (Offset2 + Dist*Bytes);
12436   return false;
12437 }
12438 
12439 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12440 // not enforce equality of the chain operands.
12441 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12442                             unsigned Bytes, int Dist,
12443                             SelectionDAG &DAG) {
12444   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12445     EVT VT = LS->getMemoryVT();
12446     SDValue Loc = LS->getBasePtr();
12447     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12448   }
12449 
12450   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12451     EVT VT;
12452     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12453     default: return false;
12454     case Intrinsic::ppc_qpx_qvlfd:
12455     case Intrinsic::ppc_qpx_qvlfda:
12456       VT = MVT::v4f64;
12457       break;
12458     case Intrinsic::ppc_qpx_qvlfs:
12459     case Intrinsic::ppc_qpx_qvlfsa:
12460       VT = MVT::v4f32;
12461       break;
12462     case Intrinsic::ppc_qpx_qvlfcd:
12463     case Intrinsic::ppc_qpx_qvlfcda:
12464       VT = MVT::v2f64;
12465       break;
12466     case Intrinsic::ppc_qpx_qvlfcs:
12467     case Intrinsic::ppc_qpx_qvlfcsa:
12468       VT = MVT::v2f32;
12469       break;
12470     case Intrinsic::ppc_qpx_qvlfiwa:
12471     case Intrinsic::ppc_qpx_qvlfiwz:
12472     case Intrinsic::ppc_altivec_lvx:
12473     case Intrinsic::ppc_altivec_lvxl:
12474     case Intrinsic::ppc_vsx_lxvw4x:
12475     case Intrinsic::ppc_vsx_lxvw4x_be:
12476       VT = MVT::v4i32;
12477       break;
12478     case Intrinsic::ppc_vsx_lxvd2x:
12479     case Intrinsic::ppc_vsx_lxvd2x_be:
12480       VT = MVT::v2f64;
12481       break;
12482     case Intrinsic::ppc_altivec_lvebx:
12483       VT = MVT::i8;
12484       break;
12485     case Intrinsic::ppc_altivec_lvehx:
12486       VT = MVT::i16;
12487       break;
12488     case Intrinsic::ppc_altivec_lvewx:
12489       VT = MVT::i32;
12490       break;
12491     }
12492 
12493     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12494   }
12495 
12496   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12497     EVT VT;
12498     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12499     default: return false;
12500     case Intrinsic::ppc_qpx_qvstfd:
12501     case Intrinsic::ppc_qpx_qvstfda:
12502       VT = MVT::v4f64;
12503       break;
12504     case Intrinsic::ppc_qpx_qvstfs:
12505     case Intrinsic::ppc_qpx_qvstfsa:
12506       VT = MVT::v4f32;
12507       break;
12508     case Intrinsic::ppc_qpx_qvstfcd:
12509     case Intrinsic::ppc_qpx_qvstfcda:
12510       VT = MVT::v2f64;
12511       break;
12512     case Intrinsic::ppc_qpx_qvstfcs:
12513     case Intrinsic::ppc_qpx_qvstfcsa:
12514       VT = MVT::v2f32;
12515       break;
12516     case Intrinsic::ppc_qpx_qvstfiw:
12517     case Intrinsic::ppc_qpx_qvstfiwa:
12518     case Intrinsic::ppc_altivec_stvx:
12519     case Intrinsic::ppc_altivec_stvxl:
12520     case Intrinsic::ppc_vsx_stxvw4x:
12521       VT = MVT::v4i32;
12522       break;
12523     case Intrinsic::ppc_vsx_stxvd2x:
12524       VT = MVT::v2f64;
12525       break;
12526     case Intrinsic::ppc_vsx_stxvw4x_be:
12527       VT = MVT::v4i32;
12528       break;
12529     case Intrinsic::ppc_vsx_stxvd2x_be:
12530       VT = MVT::v2f64;
12531       break;
12532     case Intrinsic::ppc_altivec_stvebx:
12533       VT = MVT::i8;
12534       break;
12535     case Intrinsic::ppc_altivec_stvehx:
12536       VT = MVT::i16;
12537       break;
12538     case Intrinsic::ppc_altivec_stvewx:
12539       VT = MVT::i32;
12540       break;
12541     }
12542 
12543     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12544   }
12545 
12546   return false;
12547 }
12548 
12549 // Return true is there is a nearyby consecutive load to the one provided
12550 // (regardless of alignment). We search up and down the chain, looking though
12551 // token factors and other loads (but nothing else). As a result, a true result
12552 // indicates that it is safe to create a new consecutive load adjacent to the
12553 // load provided.
12554 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12555   SDValue Chain = LD->getChain();
12556   EVT VT = LD->getMemoryVT();
12557 
12558   SmallSet<SDNode *, 16> LoadRoots;
12559   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12560   SmallSet<SDNode *, 16> Visited;
12561 
12562   // First, search up the chain, branching to follow all token-factor operands.
12563   // If we find a consecutive load, then we're done, otherwise, record all
12564   // nodes just above the top-level loads and token factors.
12565   while (!Queue.empty()) {
12566     SDNode *ChainNext = Queue.pop_back_val();
12567     if (!Visited.insert(ChainNext).second)
12568       continue;
12569 
12570     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12571       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12572         return true;
12573 
12574       if (!Visited.count(ChainLD->getChain().getNode()))
12575         Queue.push_back(ChainLD->getChain().getNode());
12576     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12577       for (const SDUse &O : ChainNext->ops())
12578         if (!Visited.count(O.getNode()))
12579           Queue.push_back(O.getNode());
12580     } else
12581       LoadRoots.insert(ChainNext);
12582   }
12583 
12584   // Second, search down the chain, starting from the top-level nodes recorded
12585   // in the first phase. These top-level nodes are the nodes just above all
12586   // loads and token factors. Starting with their uses, recursively look though
12587   // all loads (just the chain uses) and token factors to find a consecutive
12588   // load.
12589   Visited.clear();
12590   Queue.clear();
12591 
12592   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12593        IE = LoadRoots.end(); I != IE; ++I) {
12594     Queue.push_back(*I);
12595 
12596     while (!Queue.empty()) {
12597       SDNode *LoadRoot = Queue.pop_back_val();
12598       if (!Visited.insert(LoadRoot).second)
12599         continue;
12600 
12601       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12602         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12603           return true;
12604 
12605       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12606            UE = LoadRoot->use_end(); UI != UE; ++UI)
12607         if (((isa<MemSDNode>(*UI) &&
12608             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12609             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12610           Queue.push_back(*UI);
12611     }
12612   }
12613 
12614   return false;
12615 }
12616 
12617 /// This function is called when we have proved that a SETCC node can be replaced
12618 /// by subtraction (and other supporting instructions) so that the result of
12619 /// comparison is kept in a GPR instead of CR. This function is purely for
12620 /// codegen purposes and has some flags to guide the codegen process.
12621 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12622                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12623   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12624 
12625   // Zero extend the operands to the largest legal integer. Originally, they
12626   // must be of a strictly smaller size.
12627   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12628                          DAG.getConstant(Size, DL, MVT::i32));
12629   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12630                          DAG.getConstant(Size, DL, MVT::i32));
12631 
12632   // Swap if needed. Depends on the condition code.
12633   if (Swap)
12634     std::swap(Op0, Op1);
12635 
12636   // Subtract extended integers.
12637   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12638 
12639   // Move the sign bit to the least significant position and zero out the rest.
12640   // Now the least significant bit carries the result of original comparison.
12641   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12642                              DAG.getConstant(Size - 1, DL, MVT::i32));
12643   auto Final = Shifted;
12644 
12645   // Complement the result if needed. Based on the condition code.
12646   if (Complement)
12647     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12648                         DAG.getConstant(1, DL, MVT::i64));
12649 
12650   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12651 }
12652 
12653 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12654                                                   DAGCombinerInfo &DCI) const {
12655   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12656 
12657   SelectionDAG &DAG = DCI.DAG;
12658   SDLoc DL(N);
12659 
12660   // Size of integers being compared has a critical role in the following
12661   // analysis, so we prefer to do this when all types are legal.
12662   if (!DCI.isAfterLegalizeDAG())
12663     return SDValue();
12664 
12665   // If all users of SETCC extend its value to a legal integer type
12666   // then we replace SETCC with a subtraction
12667   for (SDNode::use_iterator UI = N->use_begin(),
12668        UE = N->use_end(); UI != UE; ++UI) {
12669     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12670       return SDValue();
12671   }
12672 
12673   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12674   auto OpSize = N->getOperand(0).getValueSizeInBits();
12675 
12676   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12677 
12678   if (OpSize < Size) {
12679     switch (CC) {
12680     default: break;
12681     case ISD::SETULT:
12682       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12683     case ISD::SETULE:
12684       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12685     case ISD::SETUGT:
12686       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12687     case ISD::SETUGE:
12688       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12689     }
12690   }
12691 
12692   return SDValue();
12693 }
12694 
12695 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12696                                                   DAGCombinerInfo &DCI) const {
12697   SelectionDAG &DAG = DCI.DAG;
12698   SDLoc dl(N);
12699 
12700   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12701   // If we're tracking CR bits, we need to be careful that we don't have:
12702   //   trunc(binary-ops(zext(x), zext(y)))
12703   // or
12704   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12705   // such that we're unnecessarily moving things into GPRs when it would be
12706   // better to keep them in CR bits.
12707 
12708   // Note that trunc here can be an actual i1 trunc, or can be the effective
12709   // truncation that comes from a setcc or select_cc.
12710   if (N->getOpcode() == ISD::TRUNCATE &&
12711       N->getValueType(0) != MVT::i1)
12712     return SDValue();
12713 
12714   if (N->getOperand(0).getValueType() != MVT::i32 &&
12715       N->getOperand(0).getValueType() != MVT::i64)
12716     return SDValue();
12717 
12718   if (N->getOpcode() == ISD::SETCC ||
12719       N->getOpcode() == ISD::SELECT_CC) {
12720     // If we're looking at a comparison, then we need to make sure that the
12721     // high bits (all except for the first) don't matter the result.
12722     ISD::CondCode CC =
12723       cast<CondCodeSDNode>(N->getOperand(
12724         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12725     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12726 
12727     if (ISD::isSignedIntSetCC(CC)) {
12728       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12729           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12730         return SDValue();
12731     } else if (ISD::isUnsignedIntSetCC(CC)) {
12732       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12733                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12734           !DAG.MaskedValueIsZero(N->getOperand(1),
12735                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12736         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12737                                              : SDValue());
12738     } else {
12739       // This is neither a signed nor an unsigned comparison, just make sure
12740       // that the high bits are equal.
12741       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12742       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12743 
12744       // We don't really care about what is known about the first bit (if
12745       // anything), so clear it in all masks prior to comparing them.
12746       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12747       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12748 
12749       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12750         return SDValue();
12751     }
12752   }
12753 
12754   // We now know that the higher-order bits are irrelevant, we just need to
12755   // make sure that all of the intermediate operations are bit operations, and
12756   // all inputs are extensions.
12757   if (N->getOperand(0).getOpcode() != ISD::AND &&
12758       N->getOperand(0).getOpcode() != ISD::OR  &&
12759       N->getOperand(0).getOpcode() != ISD::XOR &&
12760       N->getOperand(0).getOpcode() != ISD::SELECT &&
12761       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12762       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12763       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12764       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12765       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12766     return SDValue();
12767 
12768   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12769       N->getOperand(1).getOpcode() != ISD::AND &&
12770       N->getOperand(1).getOpcode() != ISD::OR  &&
12771       N->getOperand(1).getOpcode() != ISD::XOR &&
12772       N->getOperand(1).getOpcode() != ISD::SELECT &&
12773       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12774       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12775       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12776       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12777       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12778     return SDValue();
12779 
12780   SmallVector<SDValue, 4> Inputs;
12781   SmallVector<SDValue, 8> BinOps, PromOps;
12782   SmallPtrSet<SDNode *, 16> Visited;
12783 
12784   for (unsigned i = 0; i < 2; ++i) {
12785     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12786           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12787           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12788           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12789         isa<ConstantSDNode>(N->getOperand(i)))
12790       Inputs.push_back(N->getOperand(i));
12791     else
12792       BinOps.push_back(N->getOperand(i));
12793 
12794     if (N->getOpcode() == ISD::TRUNCATE)
12795       break;
12796   }
12797 
12798   // Visit all inputs, collect all binary operations (and, or, xor and
12799   // select) that are all fed by extensions.
12800   while (!BinOps.empty()) {
12801     SDValue BinOp = BinOps.back();
12802     BinOps.pop_back();
12803 
12804     if (!Visited.insert(BinOp.getNode()).second)
12805       continue;
12806 
12807     PromOps.push_back(BinOp);
12808 
12809     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12810       // The condition of the select is not promoted.
12811       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12812         continue;
12813       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12814         continue;
12815 
12816       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12817             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12818             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12819            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12820           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12821         Inputs.push_back(BinOp.getOperand(i));
12822       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12823                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12824                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12825                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12826                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12827                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12828                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12829                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12830                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12831         BinOps.push_back(BinOp.getOperand(i));
12832       } else {
12833         // We have an input that is not an extension or another binary
12834         // operation; we'll abort this transformation.
12835         return SDValue();
12836       }
12837     }
12838   }
12839 
12840   // Make sure that this is a self-contained cluster of operations (which
12841   // is not quite the same thing as saying that everything has only one
12842   // use).
12843   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12844     if (isa<ConstantSDNode>(Inputs[i]))
12845       continue;
12846 
12847     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12848                               UE = Inputs[i].getNode()->use_end();
12849          UI != UE; ++UI) {
12850       SDNode *User = *UI;
12851       if (User != N && !Visited.count(User))
12852         return SDValue();
12853 
12854       // Make sure that we're not going to promote the non-output-value
12855       // operand(s) or SELECT or SELECT_CC.
12856       // FIXME: Although we could sometimes handle this, and it does occur in
12857       // practice that one of the condition inputs to the select is also one of
12858       // the outputs, we currently can't deal with this.
12859       if (User->getOpcode() == ISD::SELECT) {
12860         if (User->getOperand(0) == Inputs[i])
12861           return SDValue();
12862       } else if (User->getOpcode() == ISD::SELECT_CC) {
12863         if (User->getOperand(0) == Inputs[i] ||
12864             User->getOperand(1) == Inputs[i])
12865           return SDValue();
12866       }
12867     }
12868   }
12869 
12870   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12871     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12872                               UE = PromOps[i].getNode()->use_end();
12873          UI != UE; ++UI) {
12874       SDNode *User = *UI;
12875       if (User != N && !Visited.count(User))
12876         return SDValue();
12877 
12878       // Make sure that we're not going to promote the non-output-value
12879       // operand(s) or SELECT or SELECT_CC.
12880       // FIXME: Although we could sometimes handle this, and it does occur in
12881       // practice that one of the condition inputs to the select is also one of
12882       // the outputs, we currently can't deal with this.
12883       if (User->getOpcode() == ISD::SELECT) {
12884         if (User->getOperand(0) == PromOps[i])
12885           return SDValue();
12886       } else if (User->getOpcode() == ISD::SELECT_CC) {
12887         if (User->getOperand(0) == PromOps[i] ||
12888             User->getOperand(1) == PromOps[i])
12889           return SDValue();
12890       }
12891     }
12892   }
12893 
12894   // Replace all inputs with the extension operand.
12895   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12896     // Constants may have users outside the cluster of to-be-promoted nodes,
12897     // and so we need to replace those as we do the promotions.
12898     if (isa<ConstantSDNode>(Inputs[i]))
12899       continue;
12900     else
12901       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12902   }
12903 
12904   std::list<HandleSDNode> PromOpHandles;
12905   for (auto &PromOp : PromOps)
12906     PromOpHandles.emplace_back(PromOp);
12907 
12908   // Replace all operations (these are all the same, but have a different
12909   // (i1) return type). DAG.getNode will validate that the types of
12910   // a binary operator match, so go through the list in reverse so that
12911   // we've likely promoted both operands first. Any intermediate truncations or
12912   // extensions disappear.
12913   while (!PromOpHandles.empty()) {
12914     SDValue PromOp = PromOpHandles.back().getValue();
12915     PromOpHandles.pop_back();
12916 
12917     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12918         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12919         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12920         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12921       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12922           PromOp.getOperand(0).getValueType() != MVT::i1) {
12923         // The operand is not yet ready (see comment below).
12924         PromOpHandles.emplace_front(PromOp);
12925         continue;
12926       }
12927 
12928       SDValue RepValue = PromOp.getOperand(0);
12929       if (isa<ConstantSDNode>(RepValue))
12930         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12931 
12932       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12933       continue;
12934     }
12935 
12936     unsigned C;
12937     switch (PromOp.getOpcode()) {
12938     default:             C = 0; break;
12939     case ISD::SELECT:    C = 1; break;
12940     case ISD::SELECT_CC: C = 2; break;
12941     }
12942 
12943     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12944          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12945         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12946          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12947       // The to-be-promoted operands of this node have not yet been
12948       // promoted (this should be rare because we're going through the
12949       // list backward, but if one of the operands has several users in
12950       // this cluster of to-be-promoted nodes, it is possible).
12951       PromOpHandles.emplace_front(PromOp);
12952       continue;
12953     }
12954 
12955     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12956                                 PromOp.getNode()->op_end());
12957 
12958     // If there are any constant inputs, make sure they're replaced now.
12959     for (unsigned i = 0; i < 2; ++i)
12960       if (isa<ConstantSDNode>(Ops[C+i]))
12961         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12962 
12963     DAG.ReplaceAllUsesOfValueWith(PromOp,
12964       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12965   }
12966 
12967   // Now we're left with the initial truncation itself.
12968   if (N->getOpcode() == ISD::TRUNCATE)
12969     return N->getOperand(0);
12970 
12971   // Otherwise, this is a comparison. The operands to be compared have just
12972   // changed type (to i1), but everything else is the same.
12973   return SDValue(N, 0);
12974 }
12975 
12976 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12977                                                   DAGCombinerInfo &DCI) const {
12978   SelectionDAG &DAG = DCI.DAG;
12979   SDLoc dl(N);
12980 
12981   // If we're tracking CR bits, we need to be careful that we don't have:
12982   //   zext(binary-ops(trunc(x), trunc(y)))
12983   // or
12984   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12985   // such that we're unnecessarily moving things into CR bits that can more
12986   // efficiently stay in GPRs. Note that if we're not certain that the high
12987   // bits are set as required by the final extension, we still may need to do
12988   // some masking to get the proper behavior.
12989 
12990   // This same functionality is important on PPC64 when dealing with
12991   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12992   // the return values of functions. Because it is so similar, it is handled
12993   // here as well.
12994 
12995   if (N->getValueType(0) != MVT::i32 &&
12996       N->getValueType(0) != MVT::i64)
12997     return SDValue();
12998 
12999   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13000         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13001     return SDValue();
13002 
13003   if (N->getOperand(0).getOpcode() != ISD::AND &&
13004       N->getOperand(0).getOpcode() != ISD::OR  &&
13005       N->getOperand(0).getOpcode() != ISD::XOR &&
13006       N->getOperand(0).getOpcode() != ISD::SELECT &&
13007       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13008     return SDValue();
13009 
13010   SmallVector<SDValue, 4> Inputs;
13011   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13012   SmallPtrSet<SDNode *, 16> Visited;
13013 
13014   // Visit all inputs, collect all binary operations (and, or, xor and
13015   // select) that are all fed by truncations.
13016   while (!BinOps.empty()) {
13017     SDValue BinOp = BinOps.back();
13018     BinOps.pop_back();
13019 
13020     if (!Visited.insert(BinOp.getNode()).second)
13021       continue;
13022 
13023     PromOps.push_back(BinOp);
13024 
13025     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13026       // The condition of the select is not promoted.
13027       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13028         continue;
13029       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13030         continue;
13031 
13032       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13033           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13034         Inputs.push_back(BinOp.getOperand(i));
13035       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13036                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13037                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13038                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13039                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13040         BinOps.push_back(BinOp.getOperand(i));
13041       } else {
13042         // We have an input that is not a truncation or another binary
13043         // operation; we'll abort this transformation.
13044         return SDValue();
13045       }
13046     }
13047   }
13048 
13049   // The operands of a select that must be truncated when the select is
13050   // promoted because the operand is actually part of the to-be-promoted set.
13051   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13052 
13053   // Make sure that this is a self-contained cluster of operations (which
13054   // is not quite the same thing as saying that everything has only one
13055   // use).
13056   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13057     if (isa<ConstantSDNode>(Inputs[i]))
13058       continue;
13059 
13060     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13061                               UE = Inputs[i].getNode()->use_end();
13062          UI != UE; ++UI) {
13063       SDNode *User = *UI;
13064       if (User != N && !Visited.count(User))
13065         return SDValue();
13066 
13067       // If we're going to promote the non-output-value operand(s) or SELECT or
13068       // SELECT_CC, record them for truncation.
13069       if (User->getOpcode() == ISD::SELECT) {
13070         if (User->getOperand(0) == Inputs[i])
13071           SelectTruncOp[0].insert(std::make_pair(User,
13072                                     User->getOperand(0).getValueType()));
13073       } else if (User->getOpcode() == ISD::SELECT_CC) {
13074         if (User->getOperand(0) == Inputs[i])
13075           SelectTruncOp[0].insert(std::make_pair(User,
13076                                     User->getOperand(0).getValueType()));
13077         if (User->getOperand(1) == Inputs[i])
13078           SelectTruncOp[1].insert(std::make_pair(User,
13079                                     User->getOperand(1).getValueType()));
13080       }
13081     }
13082   }
13083 
13084   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13085     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13086                               UE = PromOps[i].getNode()->use_end();
13087          UI != UE; ++UI) {
13088       SDNode *User = *UI;
13089       if (User != N && !Visited.count(User))
13090         return SDValue();
13091 
13092       // If we're going to promote the non-output-value operand(s) or SELECT or
13093       // SELECT_CC, record them for truncation.
13094       if (User->getOpcode() == ISD::SELECT) {
13095         if (User->getOperand(0) == PromOps[i])
13096           SelectTruncOp[0].insert(std::make_pair(User,
13097                                     User->getOperand(0).getValueType()));
13098       } else if (User->getOpcode() == ISD::SELECT_CC) {
13099         if (User->getOperand(0) == PromOps[i])
13100           SelectTruncOp[0].insert(std::make_pair(User,
13101                                     User->getOperand(0).getValueType()));
13102         if (User->getOperand(1) == PromOps[i])
13103           SelectTruncOp[1].insert(std::make_pair(User,
13104                                     User->getOperand(1).getValueType()));
13105       }
13106     }
13107   }
13108 
13109   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13110   bool ReallyNeedsExt = false;
13111   if (N->getOpcode() != ISD::ANY_EXTEND) {
13112     // If all of the inputs are not already sign/zero extended, then
13113     // we'll still need to do that at the end.
13114     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13115       if (isa<ConstantSDNode>(Inputs[i]))
13116         continue;
13117 
13118       unsigned OpBits =
13119         Inputs[i].getOperand(0).getValueSizeInBits();
13120       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13121 
13122       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13123            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13124                                   APInt::getHighBitsSet(OpBits,
13125                                                         OpBits-PromBits))) ||
13126           (N->getOpcode() == ISD::SIGN_EXTEND &&
13127            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13128              (OpBits-(PromBits-1)))) {
13129         ReallyNeedsExt = true;
13130         break;
13131       }
13132     }
13133   }
13134 
13135   // Replace all inputs, either with the truncation operand, or a
13136   // truncation or extension to the final output type.
13137   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13138     // Constant inputs need to be replaced with the to-be-promoted nodes that
13139     // use them because they might have users outside of the cluster of
13140     // promoted nodes.
13141     if (isa<ConstantSDNode>(Inputs[i]))
13142       continue;
13143 
13144     SDValue InSrc = Inputs[i].getOperand(0);
13145     if (Inputs[i].getValueType() == N->getValueType(0))
13146       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13147     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13148       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13149         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13150     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13151       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13152         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13153     else
13154       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13155         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13156   }
13157 
13158   std::list<HandleSDNode> PromOpHandles;
13159   for (auto &PromOp : PromOps)
13160     PromOpHandles.emplace_back(PromOp);
13161 
13162   // Replace all operations (these are all the same, but have a different
13163   // (promoted) return type). DAG.getNode will validate that the types of
13164   // a binary operator match, so go through the list in reverse so that
13165   // we've likely promoted both operands first.
13166   while (!PromOpHandles.empty()) {
13167     SDValue PromOp = PromOpHandles.back().getValue();
13168     PromOpHandles.pop_back();
13169 
13170     unsigned C;
13171     switch (PromOp.getOpcode()) {
13172     default:             C = 0; break;
13173     case ISD::SELECT:    C = 1; break;
13174     case ISD::SELECT_CC: C = 2; break;
13175     }
13176 
13177     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13178          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13179         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13180          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13181       // The to-be-promoted operands of this node have not yet been
13182       // promoted (this should be rare because we're going through the
13183       // list backward, but if one of the operands has several users in
13184       // this cluster of to-be-promoted nodes, it is possible).
13185       PromOpHandles.emplace_front(PromOp);
13186       continue;
13187     }
13188 
13189     // For SELECT and SELECT_CC nodes, we do a similar check for any
13190     // to-be-promoted comparison inputs.
13191     if (PromOp.getOpcode() == ISD::SELECT ||
13192         PromOp.getOpcode() == ISD::SELECT_CC) {
13193       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13194            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13195           (SelectTruncOp[1].count(PromOp.getNode()) &&
13196            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13197         PromOpHandles.emplace_front(PromOp);
13198         continue;
13199       }
13200     }
13201 
13202     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13203                                 PromOp.getNode()->op_end());
13204 
13205     // If this node has constant inputs, then they'll need to be promoted here.
13206     for (unsigned i = 0; i < 2; ++i) {
13207       if (!isa<ConstantSDNode>(Ops[C+i]))
13208         continue;
13209       if (Ops[C+i].getValueType() == N->getValueType(0))
13210         continue;
13211 
13212       if (N->getOpcode() == ISD::SIGN_EXTEND)
13213         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13214       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13215         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13216       else
13217         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13218     }
13219 
13220     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13221     // truncate them again to the original value type.
13222     if (PromOp.getOpcode() == ISD::SELECT ||
13223         PromOp.getOpcode() == ISD::SELECT_CC) {
13224       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13225       if (SI0 != SelectTruncOp[0].end())
13226         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13227       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13228       if (SI1 != SelectTruncOp[1].end())
13229         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13230     }
13231 
13232     DAG.ReplaceAllUsesOfValueWith(PromOp,
13233       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13234   }
13235 
13236   // Now we're left with the initial extension itself.
13237   if (!ReallyNeedsExt)
13238     return N->getOperand(0);
13239 
13240   // To zero extend, just mask off everything except for the first bit (in the
13241   // i1 case).
13242   if (N->getOpcode() == ISD::ZERO_EXTEND)
13243     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13244                        DAG.getConstant(APInt::getLowBitsSet(
13245                                          N->getValueSizeInBits(0), PromBits),
13246                                        dl, N->getValueType(0)));
13247 
13248   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13249          "Invalid extension type");
13250   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13251   SDValue ShiftCst =
13252       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13253   return DAG.getNode(
13254       ISD::SRA, dl, N->getValueType(0),
13255       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13256       ShiftCst);
13257 }
13258 
13259 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13260                                         DAGCombinerInfo &DCI) const {
13261   assert(N->getOpcode() == ISD::SETCC &&
13262          "Should be called with a SETCC node");
13263 
13264   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13265   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13266     SDValue LHS = N->getOperand(0);
13267     SDValue RHS = N->getOperand(1);
13268 
13269     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13270     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13271         LHS.hasOneUse())
13272       std::swap(LHS, RHS);
13273 
13274     // x == 0-y --> x+y == 0
13275     // x != 0-y --> x+y != 0
13276     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13277         RHS.hasOneUse()) {
13278       SDLoc DL(N);
13279       SelectionDAG &DAG = DCI.DAG;
13280       EVT VT = N->getValueType(0);
13281       EVT OpVT = LHS.getValueType();
13282       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13283       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13284     }
13285   }
13286 
13287   return DAGCombineTruncBoolExt(N, DCI);
13288 }
13289 
13290 // Is this an extending load from an f32 to an f64?
13291 static bool isFPExtLoad(SDValue Op) {
13292   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13293     return LD->getExtensionType() == ISD::EXTLOAD &&
13294       Op.getValueType() == MVT::f64;
13295   return false;
13296 }
13297 
13298 /// Reduces the number of fp-to-int conversion when building a vector.
13299 ///
13300 /// If this vector is built out of floating to integer conversions,
13301 /// transform it to a vector built out of floating point values followed by a
13302 /// single floating to integer conversion of the vector.
13303 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13304 /// becomes (fptosi (build_vector ($A, $B, ...)))
13305 SDValue PPCTargetLowering::
13306 combineElementTruncationToVectorTruncation(SDNode *N,
13307                                            DAGCombinerInfo &DCI) const {
13308   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13309          "Should be called with a BUILD_VECTOR node");
13310 
13311   SelectionDAG &DAG = DCI.DAG;
13312   SDLoc dl(N);
13313 
13314   SDValue FirstInput = N->getOperand(0);
13315   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13316          "The input operand must be an fp-to-int conversion.");
13317 
13318   // This combine happens after legalization so the fp_to_[su]i nodes are
13319   // already converted to PPCSISD nodes.
13320   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13321   if (FirstConversion == PPCISD::FCTIDZ ||
13322       FirstConversion == PPCISD::FCTIDUZ ||
13323       FirstConversion == PPCISD::FCTIWZ ||
13324       FirstConversion == PPCISD::FCTIWUZ) {
13325     bool IsSplat = true;
13326     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13327       FirstConversion == PPCISD::FCTIWUZ;
13328     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13329     SmallVector<SDValue, 4> Ops;
13330     EVT TargetVT = N->getValueType(0);
13331     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13332       SDValue NextOp = N->getOperand(i);
13333       if (NextOp.getOpcode() != PPCISD::MFVSR)
13334         return SDValue();
13335       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13336       if (NextConversion != FirstConversion)
13337         return SDValue();
13338       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13339       // This is not valid if the input was originally double precision. It is
13340       // also not profitable to do unless this is an extending load in which
13341       // case doing this combine will allow us to combine consecutive loads.
13342       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13343         return SDValue();
13344       if (N->getOperand(i) != FirstInput)
13345         IsSplat = false;
13346     }
13347 
13348     // If this is a splat, we leave it as-is since there will be only a single
13349     // fp-to-int conversion followed by a splat of the integer. This is better
13350     // for 32-bit and smaller ints and neutral for 64-bit ints.
13351     if (IsSplat)
13352       return SDValue();
13353 
13354     // Now that we know we have the right type of node, get its operands
13355     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13356       SDValue In = N->getOperand(i).getOperand(0);
13357       if (Is32Bit) {
13358         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13359         // here, we know that all inputs are extending loads so this is safe).
13360         if (In.isUndef())
13361           Ops.push_back(DAG.getUNDEF(SrcVT));
13362         else {
13363           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13364                                       MVT::f32, In.getOperand(0),
13365                                       DAG.getIntPtrConstant(1, dl));
13366           Ops.push_back(Trunc);
13367         }
13368       } else
13369         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13370     }
13371 
13372     unsigned Opcode;
13373     if (FirstConversion == PPCISD::FCTIDZ ||
13374         FirstConversion == PPCISD::FCTIWZ)
13375       Opcode = ISD::FP_TO_SINT;
13376     else
13377       Opcode = ISD::FP_TO_UINT;
13378 
13379     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13380     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13381     return DAG.getNode(Opcode, dl, TargetVT, BV);
13382   }
13383   return SDValue();
13384 }
13385 
13386 /// Reduce the number of loads when building a vector.
13387 ///
13388 /// Building a vector out of multiple loads can be converted to a load
13389 /// of the vector type if the loads are consecutive. If the loads are
13390 /// consecutive but in descending order, a shuffle is added at the end
13391 /// to reorder the vector.
13392 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13393   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13394          "Should be called with a BUILD_VECTOR node");
13395 
13396   SDLoc dl(N);
13397 
13398   // Return early for non byte-sized type, as they can't be consecutive.
13399   if (!N->getValueType(0).getVectorElementType().isByteSized())
13400     return SDValue();
13401 
13402   bool InputsAreConsecutiveLoads = true;
13403   bool InputsAreReverseConsecutive = true;
13404   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13405   SDValue FirstInput = N->getOperand(0);
13406   bool IsRoundOfExtLoad = false;
13407 
13408   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13409       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13410     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13411     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13412   }
13413   // Not a build vector of (possibly fp_rounded) loads.
13414   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13415       N->getNumOperands() == 1)
13416     return SDValue();
13417 
13418   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13419     // If any inputs are fp_round(extload), they all must be.
13420     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13421       return SDValue();
13422 
13423     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13424       N->getOperand(i);
13425     if (NextInput.getOpcode() != ISD::LOAD)
13426       return SDValue();
13427 
13428     SDValue PreviousInput =
13429       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13430     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13431     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13432 
13433     // If any inputs are fp_round(extload), they all must be.
13434     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13435       return SDValue();
13436 
13437     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13438       InputsAreConsecutiveLoads = false;
13439     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13440       InputsAreReverseConsecutive = false;
13441 
13442     // Exit early if the loads are neither consecutive nor reverse consecutive.
13443     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13444       return SDValue();
13445   }
13446 
13447   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13448          "The loads cannot be both consecutive and reverse consecutive.");
13449 
13450   SDValue FirstLoadOp =
13451     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13452   SDValue LastLoadOp =
13453     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13454                        N->getOperand(N->getNumOperands()-1);
13455 
13456   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13457   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13458   if (InputsAreConsecutiveLoads) {
13459     assert(LD1 && "Input needs to be a LoadSDNode.");
13460     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13461                        LD1->getBasePtr(), LD1->getPointerInfo(),
13462                        LD1->getAlignment());
13463   }
13464   if (InputsAreReverseConsecutive) {
13465     assert(LDL && "Input needs to be a LoadSDNode.");
13466     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13467                                LDL->getBasePtr(), LDL->getPointerInfo(),
13468                                LDL->getAlignment());
13469     SmallVector<int, 16> Ops;
13470     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13471       Ops.push_back(i);
13472 
13473     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13474                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13475   }
13476   return SDValue();
13477 }
13478 
13479 // This function adds the required vector_shuffle needed to get
13480 // the elements of the vector extract in the correct position
13481 // as specified by the CorrectElems encoding.
13482 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13483                                       SDValue Input, uint64_t Elems,
13484                                       uint64_t CorrectElems) {
13485   SDLoc dl(N);
13486 
13487   unsigned NumElems = Input.getValueType().getVectorNumElements();
13488   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13489 
13490   // Knowing the element indices being extracted from the original
13491   // vector and the order in which they're being inserted, just put
13492   // them at element indices required for the instruction.
13493   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13494     if (DAG.getDataLayout().isLittleEndian())
13495       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13496     else
13497       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13498     CorrectElems = CorrectElems >> 8;
13499     Elems = Elems >> 8;
13500   }
13501 
13502   SDValue Shuffle =
13503       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13504                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13505 
13506   EVT VT = N->getValueType(0);
13507   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13508 
13509   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13510                                Input.getValueType().getVectorElementType(),
13511                                VT.getVectorNumElements());
13512   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13513                      DAG.getValueType(ExtVT));
13514 }
13515 
13516 // Look for build vector patterns where input operands come from sign
13517 // extended vector_extract elements of specific indices. If the correct indices
13518 // aren't used, add a vector shuffle to fix up the indices and create
13519 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13520 // during instruction selection.
13521 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13522   // This array encodes the indices that the vector sign extend instructions
13523   // extract from when extending from one type to another for both BE and LE.
13524   // The right nibble of each byte corresponds to the LE incides.
13525   // and the left nibble of each byte corresponds to the BE incides.
13526   // For example: 0x3074B8FC  byte->word
13527   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13528   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13529   // For example: 0x000070F8  byte->double word
13530   // For LE: the allowed indices are: 0x0,0x8
13531   // For BE: the allowed indices are: 0x7,0xF
13532   uint64_t TargetElems[] = {
13533       0x3074B8FC, // b->w
13534       0x000070F8, // b->d
13535       0x10325476, // h->w
13536       0x00003074, // h->d
13537       0x00001032, // w->d
13538   };
13539 
13540   uint64_t Elems = 0;
13541   int Index;
13542   SDValue Input;
13543 
13544   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13545     if (!Op)
13546       return false;
13547     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13548         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13549       return false;
13550 
13551     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13552     // of the right width.
13553     SDValue Extract = Op.getOperand(0);
13554     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13555       Extract = Extract.getOperand(0);
13556     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13557       return false;
13558 
13559     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13560     if (!ExtOp)
13561       return false;
13562 
13563     Index = ExtOp->getZExtValue();
13564     if (Input && Input != Extract.getOperand(0))
13565       return false;
13566 
13567     if (!Input)
13568       Input = Extract.getOperand(0);
13569 
13570     Elems = Elems << 8;
13571     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13572     Elems |= Index;
13573 
13574     return true;
13575   };
13576 
13577   // If the build vector operands aren't sign extended vector extracts,
13578   // of the same input vector, then return.
13579   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13580     if (!isSExtOfVecExtract(N->getOperand(i))) {
13581       return SDValue();
13582     }
13583   }
13584 
13585   // If the vector extract indicies are not correct, add the appropriate
13586   // vector_shuffle.
13587   int TgtElemArrayIdx;
13588   int InputSize = Input.getValueType().getScalarSizeInBits();
13589   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13590   if (InputSize + OutputSize == 40)
13591     TgtElemArrayIdx = 0;
13592   else if (InputSize + OutputSize == 72)
13593     TgtElemArrayIdx = 1;
13594   else if (InputSize + OutputSize == 48)
13595     TgtElemArrayIdx = 2;
13596   else if (InputSize + OutputSize == 80)
13597     TgtElemArrayIdx = 3;
13598   else if (InputSize + OutputSize == 96)
13599     TgtElemArrayIdx = 4;
13600   else
13601     return SDValue();
13602 
13603   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13604   CorrectElems = DAG.getDataLayout().isLittleEndian()
13605                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13606                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13607   if (Elems != CorrectElems) {
13608     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13609   }
13610 
13611   // Regular lowering will catch cases where a shuffle is not needed.
13612   return SDValue();
13613 }
13614 
13615 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13616                                                  DAGCombinerInfo &DCI) const {
13617   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13618          "Should be called with a BUILD_VECTOR node");
13619 
13620   SelectionDAG &DAG = DCI.DAG;
13621   SDLoc dl(N);
13622 
13623   if (!Subtarget.hasVSX())
13624     return SDValue();
13625 
13626   // The target independent DAG combiner will leave a build_vector of
13627   // float-to-int conversions intact. We can generate MUCH better code for
13628   // a float-to-int conversion of a vector of floats.
13629   SDValue FirstInput = N->getOperand(0);
13630   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13631     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13632     if (Reduced)
13633       return Reduced;
13634   }
13635 
13636   // If we're building a vector out of consecutive loads, just load that
13637   // vector type.
13638   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13639   if (Reduced)
13640     return Reduced;
13641 
13642   // If we're building a vector out of extended elements from another vector
13643   // we have P9 vector integer extend instructions. The code assumes legal
13644   // input types (i.e. it can't handle things like v4i16) so do not run before
13645   // legalization.
13646   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13647     Reduced = combineBVOfVecSExt(N, DAG);
13648     if (Reduced)
13649       return Reduced;
13650   }
13651 
13652 
13653   if (N->getValueType(0) != MVT::v2f64)
13654     return SDValue();
13655 
13656   // Looking for:
13657   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13658   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13659       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13660     return SDValue();
13661   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13662       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13663     return SDValue();
13664   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13665     return SDValue();
13666 
13667   SDValue Ext1 = FirstInput.getOperand(0);
13668   SDValue Ext2 = N->getOperand(1).getOperand(0);
13669   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13670      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13671     return SDValue();
13672 
13673   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13674   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13675   if (!Ext1Op || !Ext2Op)
13676     return SDValue();
13677   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13678       Ext1.getOperand(0) != Ext2.getOperand(0))
13679     return SDValue();
13680 
13681   int FirstElem = Ext1Op->getZExtValue();
13682   int SecondElem = Ext2Op->getZExtValue();
13683   int SubvecIdx;
13684   if (FirstElem == 0 && SecondElem == 1)
13685     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13686   else if (FirstElem == 2 && SecondElem == 3)
13687     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13688   else
13689     return SDValue();
13690 
13691   SDValue SrcVec = Ext1.getOperand(0);
13692   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13693     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13694   return DAG.getNode(NodeType, dl, MVT::v2f64,
13695                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13696 }
13697 
13698 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13699                                               DAGCombinerInfo &DCI) const {
13700   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13701           N->getOpcode() == ISD::UINT_TO_FP) &&
13702          "Need an int -> FP conversion node here");
13703 
13704   if (useSoftFloat() || !Subtarget.has64BitSupport())
13705     return SDValue();
13706 
13707   SelectionDAG &DAG = DCI.DAG;
13708   SDLoc dl(N);
13709   SDValue Op(N, 0);
13710 
13711   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13712   // from the hardware.
13713   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13714     return SDValue();
13715   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13716       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13717     return SDValue();
13718 
13719   SDValue FirstOperand(Op.getOperand(0));
13720   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13721     (FirstOperand.getValueType() == MVT::i8 ||
13722      FirstOperand.getValueType() == MVT::i16);
13723   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13724     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13725     bool DstDouble = Op.getValueType() == MVT::f64;
13726     unsigned ConvOp = Signed ?
13727       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13728       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13729     SDValue WidthConst =
13730       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13731                             dl, false);
13732     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13733     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13734     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13735                                          DAG.getVTList(MVT::f64, MVT::Other),
13736                                          Ops, MVT::i8, LDN->getMemOperand());
13737 
13738     // For signed conversion, we need to sign-extend the value in the VSR
13739     if (Signed) {
13740       SDValue ExtOps[] = { Ld, WidthConst };
13741       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13742       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13743     } else
13744       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13745   }
13746 
13747 
13748   // For i32 intermediate values, unfortunately, the conversion functions
13749   // leave the upper 32 bits of the value are undefined. Within the set of
13750   // scalar instructions, we have no method for zero- or sign-extending the
13751   // value. Thus, we cannot handle i32 intermediate values here.
13752   if (Op.getOperand(0).getValueType() == MVT::i32)
13753     return SDValue();
13754 
13755   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13756          "UINT_TO_FP is supported only with FPCVT");
13757 
13758   // If we have FCFIDS, then use it when converting to single-precision.
13759   // Otherwise, convert to double-precision and then round.
13760   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13761                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13762                                                             : PPCISD::FCFIDS)
13763                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13764                                                             : PPCISD::FCFID);
13765   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13766                   ? MVT::f32
13767                   : MVT::f64;
13768 
13769   // If we're converting from a float, to an int, and back to a float again,
13770   // then we don't need the store/load pair at all.
13771   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13772        Subtarget.hasFPCVT()) ||
13773       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13774     SDValue Src = Op.getOperand(0).getOperand(0);
13775     if (Src.getValueType() == MVT::f32) {
13776       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13777       DCI.AddToWorklist(Src.getNode());
13778     } else if (Src.getValueType() != MVT::f64) {
13779       // Make sure that we don't pick up a ppc_fp128 source value.
13780       return SDValue();
13781     }
13782 
13783     unsigned FCTOp =
13784       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13785                                                         PPCISD::FCTIDUZ;
13786 
13787     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13788     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13789 
13790     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13791       FP = DAG.getNode(ISD::FP_ROUND, dl,
13792                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13793       DCI.AddToWorklist(FP.getNode());
13794     }
13795 
13796     return FP;
13797   }
13798 
13799   return SDValue();
13800 }
13801 
13802 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13803 // builtins) into loads with swaps.
13804 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13805                                               DAGCombinerInfo &DCI) const {
13806   SelectionDAG &DAG = DCI.DAG;
13807   SDLoc dl(N);
13808   SDValue Chain;
13809   SDValue Base;
13810   MachineMemOperand *MMO;
13811 
13812   switch (N->getOpcode()) {
13813   default:
13814     llvm_unreachable("Unexpected opcode for little endian VSX load");
13815   case ISD::LOAD: {
13816     LoadSDNode *LD = cast<LoadSDNode>(N);
13817     Chain = LD->getChain();
13818     Base = LD->getBasePtr();
13819     MMO = LD->getMemOperand();
13820     // If the MMO suggests this isn't a load of a full vector, leave
13821     // things alone.  For a built-in, we have to make the change for
13822     // correctness, so if there is a size problem that will be a bug.
13823     if (MMO->getSize() < 16)
13824       return SDValue();
13825     break;
13826   }
13827   case ISD::INTRINSIC_W_CHAIN: {
13828     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13829     Chain = Intrin->getChain();
13830     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13831     // us what we want. Get operand 2 instead.
13832     Base = Intrin->getOperand(2);
13833     MMO = Intrin->getMemOperand();
13834     break;
13835   }
13836   }
13837 
13838   MVT VecTy = N->getValueType(0).getSimpleVT();
13839 
13840   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13841   // aligned and the type is a vector with elements up to 4 bytes
13842   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13843       VecTy.getScalarSizeInBits() <= 32) {
13844     return SDValue();
13845   }
13846 
13847   SDValue LoadOps[] = { Chain, Base };
13848   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13849                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13850                                          LoadOps, MVT::v2f64, MMO);
13851 
13852   DCI.AddToWorklist(Load.getNode());
13853   Chain = Load.getValue(1);
13854   SDValue Swap = DAG.getNode(
13855       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13856   DCI.AddToWorklist(Swap.getNode());
13857 
13858   // Add a bitcast if the resulting load type doesn't match v2f64.
13859   if (VecTy != MVT::v2f64) {
13860     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13861     DCI.AddToWorklist(N.getNode());
13862     // Package {bitcast value, swap's chain} to match Load's shape.
13863     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13864                        N, Swap.getValue(1));
13865   }
13866 
13867   return Swap;
13868 }
13869 
13870 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13871 // builtins) into stores with swaps.
13872 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13873                                                DAGCombinerInfo &DCI) const {
13874   SelectionDAG &DAG = DCI.DAG;
13875   SDLoc dl(N);
13876   SDValue Chain;
13877   SDValue Base;
13878   unsigned SrcOpnd;
13879   MachineMemOperand *MMO;
13880 
13881   switch (N->getOpcode()) {
13882   default:
13883     llvm_unreachable("Unexpected opcode for little endian VSX store");
13884   case ISD::STORE: {
13885     StoreSDNode *ST = cast<StoreSDNode>(N);
13886     Chain = ST->getChain();
13887     Base = ST->getBasePtr();
13888     MMO = ST->getMemOperand();
13889     SrcOpnd = 1;
13890     // If the MMO suggests this isn't a store of a full vector, leave
13891     // things alone.  For a built-in, we have to make the change for
13892     // correctness, so if there is a size problem that will be a bug.
13893     if (MMO->getSize() < 16)
13894       return SDValue();
13895     break;
13896   }
13897   case ISD::INTRINSIC_VOID: {
13898     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13899     Chain = Intrin->getChain();
13900     // Intrin->getBasePtr() oddly does not get what we want.
13901     Base = Intrin->getOperand(3);
13902     MMO = Intrin->getMemOperand();
13903     SrcOpnd = 2;
13904     break;
13905   }
13906   }
13907 
13908   SDValue Src = N->getOperand(SrcOpnd);
13909   MVT VecTy = Src.getValueType().getSimpleVT();
13910 
13911   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13912   // aligned and the type is a vector with elements up to 4 bytes
13913   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13914       VecTy.getScalarSizeInBits() <= 32) {
13915     return SDValue();
13916   }
13917 
13918   // All stores are done as v2f64 and possible bit cast.
13919   if (VecTy != MVT::v2f64) {
13920     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13921     DCI.AddToWorklist(Src.getNode());
13922   }
13923 
13924   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13925                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13926   DCI.AddToWorklist(Swap.getNode());
13927   Chain = Swap.getValue(1);
13928   SDValue StoreOps[] = { Chain, Swap, Base };
13929   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13930                                           DAG.getVTList(MVT::Other),
13931                                           StoreOps, VecTy, MMO);
13932   DCI.AddToWorklist(Store.getNode());
13933   return Store;
13934 }
13935 
13936 // Handle DAG combine for STORE (FP_TO_INT F).
13937 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13938                                                DAGCombinerInfo &DCI) const {
13939 
13940   SelectionDAG &DAG = DCI.DAG;
13941   SDLoc dl(N);
13942   unsigned Opcode = N->getOperand(1).getOpcode();
13943 
13944   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13945          && "Not a FP_TO_INT Instruction!");
13946 
13947   SDValue Val = N->getOperand(1).getOperand(0);
13948   EVT Op1VT = N->getOperand(1).getValueType();
13949   EVT ResVT = Val.getValueType();
13950 
13951   // Floating point types smaller than 32 bits are not legal on Power.
13952   if (ResVT.getScalarSizeInBits() < 32)
13953     return SDValue();
13954 
13955   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13956   bool ValidTypeForStoreFltAsInt =
13957         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13958          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13959 
13960   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13961       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13962     return SDValue();
13963 
13964   // Extend f32 values to f64
13965   if (ResVT.getScalarSizeInBits() == 32) {
13966     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13967     DCI.AddToWorklist(Val.getNode());
13968   }
13969 
13970   // Set signed or unsigned conversion opcode.
13971   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13972                           PPCISD::FP_TO_SINT_IN_VSR :
13973                           PPCISD::FP_TO_UINT_IN_VSR;
13974 
13975   Val = DAG.getNode(ConvOpcode,
13976                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13977   DCI.AddToWorklist(Val.getNode());
13978 
13979   // Set number of bytes being converted.
13980   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13981   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13982                     DAG.getIntPtrConstant(ByteSize, dl, false),
13983                     DAG.getValueType(Op1VT) };
13984 
13985   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13986           DAG.getVTList(MVT::Other), Ops,
13987           cast<StoreSDNode>(N)->getMemoryVT(),
13988           cast<StoreSDNode>(N)->getMemOperand());
13989 
13990   DCI.AddToWorklist(Val.getNode());
13991   return Val;
13992 }
13993 
13994 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13995                                                 LSBaseSDNode *LSBase,
13996                                                 DAGCombinerInfo &DCI) const {
13997   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13998         "Not a reverse memop pattern!");
13999 
14000   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14001     auto Mask = SVN->getMask();
14002     int i = 0;
14003     auto I = Mask.rbegin();
14004     auto E = Mask.rend();
14005 
14006     for (; I != E; ++I) {
14007       if (*I != i)
14008         return false;
14009       i++;
14010     }
14011     return true;
14012   };
14013 
14014   SelectionDAG &DAG = DCI.DAG;
14015   EVT VT = SVN->getValueType(0);
14016 
14017   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14018     return SDValue();
14019 
14020   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14021   // See comment in PPCVSXSwapRemoval.cpp.
14022   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14023   if (!Subtarget.hasP9Vector())
14024     return SDValue();
14025 
14026   if(!IsElementReverse(SVN))
14027     return SDValue();
14028 
14029   if (LSBase->getOpcode() == ISD::LOAD) {
14030     SDLoc dl(SVN);
14031     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14032     return DAG.getMemIntrinsicNode(
14033         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14034         LSBase->getMemoryVT(), LSBase->getMemOperand());
14035   }
14036 
14037   if (LSBase->getOpcode() == ISD::STORE) {
14038     SDLoc dl(LSBase);
14039     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14040                           LSBase->getBasePtr()};
14041     return DAG.getMemIntrinsicNode(
14042         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14043         LSBase->getMemoryVT(), LSBase->getMemOperand());
14044   }
14045 
14046   llvm_unreachable("Expected a load or store node here");
14047 }
14048 
14049 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14050                                              DAGCombinerInfo &DCI) const {
14051   SelectionDAG &DAG = DCI.DAG;
14052   SDLoc dl(N);
14053   switch (N->getOpcode()) {
14054   default: break;
14055   case ISD::ADD:
14056     return combineADD(N, DCI);
14057   case ISD::SHL:
14058     return combineSHL(N, DCI);
14059   case ISD::SRA:
14060     return combineSRA(N, DCI);
14061   case ISD::SRL:
14062     return combineSRL(N, DCI);
14063   case ISD::MUL:
14064     return combineMUL(N, DCI);
14065   case PPCISD::SHL:
14066     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14067         return N->getOperand(0);
14068     break;
14069   case PPCISD::SRL:
14070     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14071         return N->getOperand(0);
14072     break;
14073   case PPCISD::SRA:
14074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14075       if (C->isNullValue() ||   //  0 >>s V -> 0.
14076           C->isAllOnesValue())    // -1 >>s V -> -1.
14077         return N->getOperand(0);
14078     }
14079     break;
14080   case ISD::SIGN_EXTEND:
14081   case ISD::ZERO_EXTEND:
14082   case ISD::ANY_EXTEND:
14083     return DAGCombineExtBoolTrunc(N, DCI);
14084   case ISD::TRUNCATE:
14085     return combineTRUNCATE(N, DCI);
14086   case ISD::SETCC:
14087     if (SDValue CSCC = combineSetCC(N, DCI))
14088       return CSCC;
14089     LLVM_FALLTHROUGH;
14090   case ISD::SELECT_CC:
14091     return DAGCombineTruncBoolExt(N, DCI);
14092   case ISD::SINT_TO_FP:
14093   case ISD::UINT_TO_FP:
14094     return combineFPToIntToFP(N, DCI);
14095   case ISD::VECTOR_SHUFFLE:
14096     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14097       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14098       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14099     }
14100     break;
14101   case ISD::STORE: {
14102 
14103     EVT Op1VT = N->getOperand(1).getValueType();
14104     unsigned Opcode = N->getOperand(1).getOpcode();
14105 
14106     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14107       SDValue Val= combineStoreFPToInt(N, DCI);
14108       if (Val)
14109         return Val;
14110     }
14111 
14112     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14113       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14114       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14115       if (Val)
14116         return Val;
14117     }
14118 
14119     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14120     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14121         N->getOperand(1).getNode()->hasOneUse() &&
14122         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14123          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14124 
14125       // STBRX can only handle simple types and it makes no sense to store less
14126       // two bytes in byte-reversed order.
14127       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14128       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14129         break;
14130 
14131       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14132       // Do an any-extend to 32-bits if this is a half-word input.
14133       if (BSwapOp.getValueType() == MVT::i16)
14134         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14135 
14136       // If the type of BSWAP operand is wider than stored memory width
14137       // it need to be shifted to the right side before STBRX.
14138       if (Op1VT.bitsGT(mVT)) {
14139         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14140         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14141                               DAG.getConstant(Shift, dl, MVT::i32));
14142         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14143         if (Op1VT == MVT::i64)
14144           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14145       }
14146 
14147       SDValue Ops[] = {
14148         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14149       };
14150       return
14151         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14152                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14153                                 cast<StoreSDNode>(N)->getMemOperand());
14154     }
14155 
14156     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14157     // So it can increase the chance of CSE constant construction.
14158     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14159         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14160       // Need to sign-extended to 64-bits to handle negative values.
14161       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14162       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14163                                     MemVT.getSizeInBits());
14164       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14165 
14166       // DAG.getTruncStore() can't be used here because it doesn't accept
14167       // the general (base + offset) addressing mode.
14168       // So we use UpdateNodeOperands and setTruncatingStore instead.
14169       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14170                              N->getOperand(3));
14171       cast<StoreSDNode>(N)->setTruncatingStore(true);
14172       return SDValue(N, 0);
14173     }
14174 
14175     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14176     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14177     if (Op1VT.isSimple()) {
14178       MVT StoreVT = Op1VT.getSimpleVT();
14179       if (Subtarget.needsSwapsForVSXMemOps() &&
14180           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14181            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14182         return expandVSXStoreForLE(N, DCI);
14183     }
14184     break;
14185   }
14186   case ISD::LOAD: {
14187     LoadSDNode *LD = cast<LoadSDNode>(N);
14188     EVT VT = LD->getValueType(0);
14189 
14190     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14191     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14192     if (VT.isSimple()) {
14193       MVT LoadVT = VT.getSimpleVT();
14194       if (Subtarget.needsSwapsForVSXMemOps() &&
14195           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14196            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14197         return expandVSXLoadForLE(N, DCI);
14198     }
14199 
14200     // We sometimes end up with a 64-bit integer load, from which we extract
14201     // two single-precision floating-point numbers. This happens with
14202     // std::complex<float>, and other similar structures, because of the way we
14203     // canonicalize structure copies. However, if we lack direct moves,
14204     // then the final bitcasts from the extracted integer values to the
14205     // floating-point numbers turn into store/load pairs. Even with direct moves,
14206     // just loading the two floating-point numbers is likely better.
14207     auto ReplaceTwoFloatLoad = [&]() {
14208       if (VT != MVT::i64)
14209         return false;
14210 
14211       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14212           LD->isVolatile())
14213         return false;
14214 
14215       //  We're looking for a sequence like this:
14216       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14217       //      t16: i64 = srl t13, Constant:i32<32>
14218       //    t17: i32 = truncate t16
14219       //  t18: f32 = bitcast t17
14220       //    t19: i32 = truncate t13
14221       //  t20: f32 = bitcast t19
14222 
14223       if (!LD->hasNUsesOfValue(2, 0))
14224         return false;
14225 
14226       auto UI = LD->use_begin();
14227       while (UI.getUse().getResNo() != 0) ++UI;
14228       SDNode *Trunc = *UI++;
14229       while (UI.getUse().getResNo() != 0) ++UI;
14230       SDNode *RightShift = *UI;
14231       if (Trunc->getOpcode() != ISD::TRUNCATE)
14232         std::swap(Trunc, RightShift);
14233 
14234       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14235           Trunc->getValueType(0) != MVT::i32 ||
14236           !Trunc->hasOneUse())
14237         return false;
14238       if (RightShift->getOpcode() != ISD::SRL ||
14239           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14240           RightShift->getConstantOperandVal(1) != 32 ||
14241           !RightShift->hasOneUse())
14242         return false;
14243 
14244       SDNode *Trunc2 = *RightShift->use_begin();
14245       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14246           Trunc2->getValueType(0) != MVT::i32 ||
14247           !Trunc2->hasOneUse())
14248         return false;
14249 
14250       SDNode *Bitcast = *Trunc->use_begin();
14251       SDNode *Bitcast2 = *Trunc2->use_begin();
14252 
14253       if (Bitcast->getOpcode() != ISD::BITCAST ||
14254           Bitcast->getValueType(0) != MVT::f32)
14255         return false;
14256       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14257           Bitcast2->getValueType(0) != MVT::f32)
14258         return false;
14259 
14260       if (Subtarget.isLittleEndian())
14261         std::swap(Bitcast, Bitcast2);
14262 
14263       // Bitcast has the second float (in memory-layout order) and Bitcast2
14264       // has the first one.
14265 
14266       SDValue BasePtr = LD->getBasePtr();
14267       if (LD->isIndexed()) {
14268         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14269                "Non-pre-inc AM on PPC?");
14270         BasePtr =
14271           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14272                       LD->getOffset());
14273       }
14274 
14275       auto MMOFlags =
14276           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14277       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14278                                       LD->getPointerInfo(), LD->getAlignment(),
14279                                       MMOFlags, LD->getAAInfo());
14280       SDValue AddPtr =
14281         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14282                     BasePtr, DAG.getIntPtrConstant(4, dl));
14283       SDValue FloatLoad2 = DAG.getLoad(
14284           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14285           LD->getPointerInfo().getWithOffset(4),
14286           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14287 
14288       if (LD->isIndexed()) {
14289         // Note that DAGCombine should re-form any pre-increment load(s) from
14290         // what is produced here if that makes sense.
14291         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14292       }
14293 
14294       DCI.CombineTo(Bitcast2, FloatLoad);
14295       DCI.CombineTo(Bitcast, FloatLoad2);
14296 
14297       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14298                                     SDValue(FloatLoad2.getNode(), 1));
14299       return true;
14300     };
14301 
14302     if (ReplaceTwoFloatLoad())
14303       return SDValue(N, 0);
14304 
14305     EVT MemVT = LD->getMemoryVT();
14306     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14307     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
14308     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
14309     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
14310     if (LD->isUnindexed() && VT.isVector() &&
14311         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14312           // P8 and later hardware should just use LOAD.
14313           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
14314                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
14315          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
14316           LD->getAlignment() >= ScalarABIAlignment)) &&
14317         LD->getAlignment() < ABIAlignment) {
14318       // This is a type-legal unaligned Altivec or QPX load.
14319       SDValue Chain = LD->getChain();
14320       SDValue Ptr = LD->getBasePtr();
14321       bool isLittleEndian = Subtarget.isLittleEndian();
14322 
14323       // This implements the loading of unaligned vectors as described in
14324       // the venerable Apple Velocity Engine overview. Specifically:
14325       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14326       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14327       //
14328       // The general idea is to expand a sequence of one or more unaligned
14329       // loads into an alignment-based permutation-control instruction (lvsl
14330       // or lvsr), a series of regular vector loads (which always truncate
14331       // their input address to an aligned address), and a series of
14332       // permutations.  The results of these permutations are the requested
14333       // loaded values.  The trick is that the last "extra" load is not taken
14334       // from the address you might suspect (sizeof(vector) bytes after the
14335       // last requested load), but rather sizeof(vector) - 1 bytes after the
14336       // last requested vector. The point of this is to avoid a page fault if
14337       // the base address happened to be aligned. This works because if the
14338       // base address is aligned, then adding less than a full vector length
14339       // will cause the last vector in the sequence to be (re)loaded.
14340       // Otherwise, the next vector will be fetched as you might suspect was
14341       // necessary.
14342 
14343       // We might be able to reuse the permutation generation from
14344       // a different base address offset from this one by an aligned amount.
14345       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14346       // optimization later.
14347       Intrinsic::ID Intr, IntrLD, IntrPerm;
14348       MVT PermCntlTy, PermTy, LDTy;
14349       if (Subtarget.hasAltivec()) {
14350         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
14351                                  Intrinsic::ppc_altivec_lvsl;
14352         IntrLD = Intrinsic::ppc_altivec_lvx;
14353         IntrPerm = Intrinsic::ppc_altivec_vperm;
14354         PermCntlTy = MVT::v16i8;
14355         PermTy = MVT::v4i32;
14356         LDTy = MVT::v4i32;
14357       } else {
14358         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
14359                                        Intrinsic::ppc_qpx_qvlpcls;
14360         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
14361                                        Intrinsic::ppc_qpx_qvlfs;
14362         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
14363         PermCntlTy = MVT::v4f64;
14364         PermTy = MVT::v4f64;
14365         LDTy = MemVT.getSimpleVT();
14366       }
14367 
14368       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14369 
14370       // Create the new MMO for the new base load. It is like the original MMO,
14371       // but represents an area in memory almost twice the vector size centered
14372       // on the original address. If the address is unaligned, we might start
14373       // reading up to (sizeof(vector)-1) bytes below the address of the
14374       // original unaligned load.
14375       MachineFunction &MF = DAG.getMachineFunction();
14376       MachineMemOperand *BaseMMO =
14377         MF.getMachineMemOperand(LD->getMemOperand(),
14378                                 -(long)MemVT.getStoreSize()+1,
14379                                 2*MemVT.getStoreSize()-1);
14380 
14381       // Create the new base load.
14382       SDValue LDXIntID =
14383           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14384       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14385       SDValue BaseLoad =
14386         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14387                                 DAG.getVTList(PermTy, MVT::Other),
14388                                 BaseLoadOps, LDTy, BaseMMO);
14389 
14390       // Note that the value of IncOffset (which is provided to the next
14391       // load's pointer info offset value, and thus used to calculate the
14392       // alignment), and the value of IncValue (which is actually used to
14393       // increment the pointer value) are different! This is because we
14394       // require the next load to appear to be aligned, even though it
14395       // is actually offset from the base pointer by a lesser amount.
14396       int IncOffset = VT.getSizeInBits() / 8;
14397       int IncValue = IncOffset;
14398 
14399       // Walk (both up and down) the chain looking for another load at the real
14400       // (aligned) offset (the alignment of the other load does not matter in
14401       // this case). If found, then do not use the offset reduction trick, as
14402       // that will prevent the loads from being later combined (as they would
14403       // otherwise be duplicates).
14404       if (!findConsecutiveLoad(LD, DAG))
14405         --IncValue;
14406 
14407       SDValue Increment =
14408           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14409       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14410 
14411       MachineMemOperand *ExtraMMO =
14412         MF.getMachineMemOperand(LD->getMemOperand(),
14413                                 1, 2*MemVT.getStoreSize()-1);
14414       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14415       SDValue ExtraLoad =
14416         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14417                                 DAG.getVTList(PermTy, MVT::Other),
14418                                 ExtraLoadOps, LDTy, ExtraMMO);
14419 
14420       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14421         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14422 
14423       // Because vperm has a big-endian bias, we must reverse the order
14424       // of the input vectors and complement the permute control vector
14425       // when generating little endian code.  We have already handled the
14426       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14427       // and ExtraLoad here.
14428       SDValue Perm;
14429       if (isLittleEndian)
14430         Perm = BuildIntrinsicOp(IntrPerm,
14431                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14432       else
14433         Perm = BuildIntrinsicOp(IntrPerm,
14434                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14435 
14436       if (VT != PermTy)
14437         Perm = Subtarget.hasAltivec() ?
14438                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14439                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14440                                DAG.getTargetConstant(1, dl, MVT::i64));
14441                                // second argument is 1 because this rounding
14442                                // is always exact.
14443 
14444       // The output of the permutation is our loaded result, the TokenFactor is
14445       // our new chain.
14446       DCI.CombineTo(N, Perm, TF);
14447       return SDValue(N, 0);
14448     }
14449     }
14450     break;
14451     case ISD::INTRINSIC_WO_CHAIN: {
14452       bool isLittleEndian = Subtarget.isLittleEndian();
14453       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14454       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14455                                            : Intrinsic::ppc_altivec_lvsl);
14456       if ((IID == Intr ||
14457            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14458            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14459         N->getOperand(1)->getOpcode() == ISD::ADD) {
14460         SDValue Add = N->getOperand(1);
14461 
14462         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14463                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14464 
14465         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14466                                   APInt::getAllOnesValue(Bits /* alignment */)
14467                                       .zext(Add.getScalarValueSizeInBits()))) {
14468           SDNode *BasePtr = Add->getOperand(0).getNode();
14469           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14470                                     UE = BasePtr->use_end();
14471                UI != UE; ++UI) {
14472             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14473                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14474               // We've found another LVSL/LVSR, and this address is an aligned
14475               // multiple of that one. The results will be the same, so use the
14476               // one we've just found instead.
14477 
14478               return SDValue(*UI, 0);
14479             }
14480           }
14481         }
14482 
14483         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14484           SDNode *BasePtr = Add->getOperand(0).getNode();
14485           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14486                UE = BasePtr->use_end(); UI != UE; ++UI) {
14487             if (UI->getOpcode() == ISD::ADD &&
14488                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14489                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14490                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14491                 (1ULL << Bits) == 0) {
14492               SDNode *OtherAdd = *UI;
14493               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14494                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14495                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14496                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14497                   return SDValue(*VI, 0);
14498                 }
14499               }
14500             }
14501           }
14502         }
14503       }
14504 
14505       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14506       // Expose the vabsduw/h/b opportunity for down stream
14507       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14508           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14509            IID == Intrinsic::ppc_altivec_vmaxsh ||
14510            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14511         SDValue V1 = N->getOperand(1);
14512         SDValue V2 = N->getOperand(2);
14513         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14514              V1.getSimpleValueType() == MVT::v8i16 ||
14515              V1.getSimpleValueType() == MVT::v16i8) &&
14516             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14517           // (0-a, a)
14518           if (V1.getOpcode() == ISD::SUB &&
14519               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14520               V1.getOperand(1) == V2) {
14521             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14522           }
14523           // (a, 0-a)
14524           if (V2.getOpcode() == ISD::SUB &&
14525               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14526               V2.getOperand(1) == V1) {
14527             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14528           }
14529           // (x-y, y-x)
14530           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14531               V1.getOperand(0) == V2.getOperand(1) &&
14532               V1.getOperand(1) == V2.getOperand(0)) {
14533             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14534           }
14535         }
14536       }
14537     }
14538 
14539     break;
14540   case ISD::INTRINSIC_W_CHAIN:
14541     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14542     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14543     if (Subtarget.needsSwapsForVSXMemOps()) {
14544       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14545       default:
14546         break;
14547       case Intrinsic::ppc_vsx_lxvw4x:
14548       case Intrinsic::ppc_vsx_lxvd2x:
14549         return expandVSXLoadForLE(N, DCI);
14550       }
14551     }
14552     break;
14553   case ISD::INTRINSIC_VOID:
14554     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14555     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14556     if (Subtarget.needsSwapsForVSXMemOps()) {
14557       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14558       default:
14559         break;
14560       case Intrinsic::ppc_vsx_stxvw4x:
14561       case Intrinsic::ppc_vsx_stxvd2x:
14562         return expandVSXStoreForLE(N, DCI);
14563       }
14564     }
14565     break;
14566   case ISD::BSWAP:
14567     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14568     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14569         N->getOperand(0).hasOneUse() &&
14570         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14571          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14572           N->getValueType(0) == MVT::i64))) {
14573       SDValue Load = N->getOperand(0);
14574       LoadSDNode *LD = cast<LoadSDNode>(Load);
14575       // Create the byte-swapping load.
14576       SDValue Ops[] = {
14577         LD->getChain(),    // Chain
14578         LD->getBasePtr(),  // Ptr
14579         DAG.getValueType(N->getValueType(0)) // VT
14580       };
14581       SDValue BSLoad =
14582         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14583                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14584                                               MVT::i64 : MVT::i32, MVT::Other),
14585                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14586 
14587       // If this is an i16 load, insert the truncate.
14588       SDValue ResVal = BSLoad;
14589       if (N->getValueType(0) == MVT::i16)
14590         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14591 
14592       // First, combine the bswap away.  This makes the value produced by the
14593       // load dead.
14594       DCI.CombineTo(N, ResVal);
14595 
14596       // Next, combine the load away, we give it a bogus result value but a real
14597       // chain result.  The result value is dead because the bswap is dead.
14598       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14599 
14600       // Return N so it doesn't get rechecked!
14601       return SDValue(N, 0);
14602     }
14603     break;
14604   case PPCISD::VCMP:
14605     // If a VCMPo node already exists with exactly the same operands as this
14606     // node, use its result instead of this node (VCMPo computes both a CR6 and
14607     // a normal output).
14608     //
14609     if (!N->getOperand(0).hasOneUse() &&
14610         !N->getOperand(1).hasOneUse() &&
14611         !N->getOperand(2).hasOneUse()) {
14612 
14613       // Scan all of the users of the LHS, looking for VCMPo's that match.
14614       SDNode *VCMPoNode = nullptr;
14615 
14616       SDNode *LHSN = N->getOperand(0).getNode();
14617       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14618            UI != E; ++UI)
14619         if (UI->getOpcode() == PPCISD::VCMPo &&
14620             UI->getOperand(1) == N->getOperand(1) &&
14621             UI->getOperand(2) == N->getOperand(2) &&
14622             UI->getOperand(0) == N->getOperand(0)) {
14623           VCMPoNode = *UI;
14624           break;
14625         }
14626 
14627       // If there is no VCMPo node, or if the flag value has a single use, don't
14628       // transform this.
14629       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14630         break;
14631 
14632       // Look at the (necessarily single) use of the flag value.  If it has a
14633       // chain, this transformation is more complex.  Note that multiple things
14634       // could use the value result, which we should ignore.
14635       SDNode *FlagUser = nullptr;
14636       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14637            FlagUser == nullptr; ++UI) {
14638         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14639         SDNode *User = *UI;
14640         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14641           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14642             FlagUser = User;
14643             break;
14644           }
14645         }
14646       }
14647 
14648       // If the user is a MFOCRF instruction, we know this is safe.
14649       // Otherwise we give up for right now.
14650       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14651         return SDValue(VCMPoNode, 0);
14652     }
14653     break;
14654   case ISD::BRCOND: {
14655     SDValue Cond = N->getOperand(1);
14656     SDValue Target = N->getOperand(2);
14657 
14658     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14659         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14660           Intrinsic::loop_decrement) {
14661 
14662       // We now need to make the intrinsic dead (it cannot be instruction
14663       // selected).
14664       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14665       assert(Cond.getNode()->hasOneUse() &&
14666              "Counter decrement has more than one use");
14667 
14668       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14669                          N->getOperand(0), Target);
14670     }
14671   }
14672   break;
14673   case ISD::BR_CC: {
14674     // If this is a branch on an altivec predicate comparison, lower this so
14675     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14676     // lowering is done pre-legalize, because the legalizer lowers the predicate
14677     // compare down to code that is difficult to reassemble.
14678     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14679     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14680 
14681     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14682     // value. If so, pass-through the AND to get to the intrinsic.
14683     if (LHS.getOpcode() == ISD::AND &&
14684         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14685         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14686           Intrinsic::loop_decrement &&
14687         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14688         !isNullConstant(LHS.getOperand(1)))
14689       LHS = LHS.getOperand(0);
14690 
14691     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14692         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14693           Intrinsic::loop_decrement &&
14694         isa<ConstantSDNode>(RHS)) {
14695       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14696              "Counter decrement comparison is not EQ or NE");
14697 
14698       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14699       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14700                     (CC == ISD::SETNE && !Val);
14701 
14702       // We now need to make the intrinsic dead (it cannot be instruction
14703       // selected).
14704       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14705       assert(LHS.getNode()->hasOneUse() &&
14706              "Counter decrement has more than one use");
14707 
14708       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14709                          N->getOperand(0), N->getOperand(4));
14710     }
14711 
14712     int CompareOpc;
14713     bool isDot;
14714 
14715     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14716         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14717         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14718       assert(isDot && "Can't compare against a vector result!");
14719 
14720       // If this is a comparison against something other than 0/1, then we know
14721       // that the condition is never/always true.
14722       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14723       if (Val != 0 && Val != 1) {
14724         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14725           return N->getOperand(0);
14726         // Always !=, turn it into an unconditional branch.
14727         return DAG.getNode(ISD::BR, dl, MVT::Other,
14728                            N->getOperand(0), N->getOperand(4));
14729       }
14730 
14731       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14732 
14733       // Create the PPCISD altivec 'dot' comparison node.
14734       SDValue Ops[] = {
14735         LHS.getOperand(2),  // LHS of compare
14736         LHS.getOperand(3),  // RHS of compare
14737         DAG.getConstant(CompareOpc, dl, MVT::i32)
14738       };
14739       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14740       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14741 
14742       // Unpack the result based on how the target uses it.
14743       PPC::Predicate CompOpc;
14744       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14745       default:  // Can't happen, don't crash on invalid number though.
14746       case 0:   // Branch on the value of the EQ bit of CR6.
14747         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14748         break;
14749       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14750         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14751         break;
14752       case 2:   // Branch on the value of the LT bit of CR6.
14753         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14754         break;
14755       case 3:   // Branch on the inverted value of the LT bit of CR6.
14756         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14757         break;
14758       }
14759 
14760       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14761                          DAG.getConstant(CompOpc, dl, MVT::i32),
14762                          DAG.getRegister(PPC::CR6, MVT::i32),
14763                          N->getOperand(4), CompNode.getValue(1));
14764     }
14765     break;
14766   }
14767   case ISD::BUILD_VECTOR:
14768     return DAGCombineBuildVector(N, DCI);
14769   case ISD::ABS:
14770     return combineABS(N, DCI);
14771   case ISD::VSELECT:
14772     return combineVSelect(N, DCI);
14773   }
14774 
14775   return SDValue();
14776 }
14777 
14778 SDValue
14779 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14780                                  SelectionDAG &DAG,
14781                                  SmallVectorImpl<SDNode *> &Created) const {
14782   // fold (sdiv X, pow2)
14783   EVT VT = N->getValueType(0);
14784   if (VT == MVT::i64 && !Subtarget.isPPC64())
14785     return SDValue();
14786   if ((VT != MVT::i32 && VT != MVT::i64) ||
14787       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14788     return SDValue();
14789 
14790   SDLoc DL(N);
14791   SDValue N0 = N->getOperand(0);
14792 
14793   bool IsNegPow2 = (-Divisor).isPowerOf2();
14794   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14795   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14796 
14797   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14798   Created.push_back(Op.getNode());
14799 
14800   if (IsNegPow2) {
14801     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14802     Created.push_back(Op.getNode());
14803   }
14804 
14805   return Op;
14806 }
14807 
14808 //===----------------------------------------------------------------------===//
14809 // Inline Assembly Support
14810 //===----------------------------------------------------------------------===//
14811 
14812 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14813                                                       KnownBits &Known,
14814                                                       const APInt &DemandedElts,
14815                                                       const SelectionDAG &DAG,
14816                                                       unsigned Depth) const {
14817   Known.resetAll();
14818   switch (Op.getOpcode()) {
14819   default: break;
14820   case PPCISD::LBRX: {
14821     // lhbrx is known to have the top bits cleared out.
14822     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14823       Known.Zero = 0xFFFF0000;
14824     break;
14825   }
14826   case ISD::INTRINSIC_WO_CHAIN: {
14827     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14828     default: break;
14829     case Intrinsic::ppc_altivec_vcmpbfp_p:
14830     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14831     case Intrinsic::ppc_altivec_vcmpequb_p:
14832     case Intrinsic::ppc_altivec_vcmpequh_p:
14833     case Intrinsic::ppc_altivec_vcmpequw_p:
14834     case Intrinsic::ppc_altivec_vcmpequd_p:
14835     case Intrinsic::ppc_altivec_vcmpgefp_p:
14836     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14837     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14838     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14839     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14840     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14841     case Intrinsic::ppc_altivec_vcmpgtub_p:
14842     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14843     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14844     case Intrinsic::ppc_altivec_vcmpgtud_p:
14845       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14846       break;
14847     }
14848   }
14849   }
14850 }
14851 
14852 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14853   switch (Subtarget.getCPUDirective()) {
14854   default: break;
14855   case PPC::DIR_970:
14856   case PPC::DIR_PWR4:
14857   case PPC::DIR_PWR5:
14858   case PPC::DIR_PWR5X:
14859   case PPC::DIR_PWR6:
14860   case PPC::DIR_PWR6X:
14861   case PPC::DIR_PWR7:
14862   case PPC::DIR_PWR8:
14863   case PPC::DIR_PWR9:
14864   case PPC::DIR_PWR_FUTURE: {
14865     if (!ML)
14866       break;
14867 
14868     if (!DisableInnermostLoopAlign32) {
14869       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14870       // so that we can decrease cache misses and branch-prediction misses.
14871       // Actual alignment of the loop will depend on the hotness check and other
14872       // logic in alignBlocks.
14873       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14874         return Align(32);
14875     }
14876 
14877     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14878 
14879     // For small loops (between 5 and 8 instructions), align to a 32-byte
14880     // boundary so that the entire loop fits in one instruction-cache line.
14881     uint64_t LoopSize = 0;
14882     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14883       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14884         LoopSize += TII->getInstSizeInBytes(*J);
14885         if (LoopSize > 32)
14886           break;
14887       }
14888 
14889     if (LoopSize > 16 && LoopSize <= 32)
14890       return Align(32);
14891 
14892     break;
14893   }
14894   }
14895 
14896   return TargetLowering::getPrefLoopAlignment(ML);
14897 }
14898 
14899 /// getConstraintType - Given a constraint, return the type of
14900 /// constraint it is for this target.
14901 PPCTargetLowering::ConstraintType
14902 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14903   if (Constraint.size() == 1) {
14904     switch (Constraint[0]) {
14905     default: break;
14906     case 'b':
14907     case 'r':
14908     case 'f':
14909     case 'd':
14910     case 'v':
14911     case 'y':
14912       return C_RegisterClass;
14913     case 'Z':
14914       // FIXME: While Z does indicate a memory constraint, it specifically
14915       // indicates an r+r address (used in conjunction with the 'y' modifier
14916       // in the replacement string). Currently, we're forcing the base
14917       // register to be r0 in the asm printer (which is interpreted as zero)
14918       // and forming the complete address in the second register. This is
14919       // suboptimal.
14920       return C_Memory;
14921     }
14922   } else if (Constraint == "wc") { // individual CR bits.
14923     return C_RegisterClass;
14924   } else if (Constraint == "wa" || Constraint == "wd" ||
14925              Constraint == "wf" || Constraint == "ws" ||
14926              Constraint == "wi" || Constraint == "ww") {
14927     return C_RegisterClass; // VSX registers.
14928   }
14929   return TargetLowering::getConstraintType(Constraint);
14930 }
14931 
14932 /// Examine constraint type and operand type and determine a weight value.
14933 /// This object must already have been set up with the operand type
14934 /// and the current alternative constraint selected.
14935 TargetLowering::ConstraintWeight
14936 PPCTargetLowering::getSingleConstraintMatchWeight(
14937     AsmOperandInfo &info, const char *constraint) const {
14938   ConstraintWeight weight = CW_Invalid;
14939   Value *CallOperandVal = info.CallOperandVal;
14940     // If we don't have a value, we can't do a match,
14941     // but allow it at the lowest weight.
14942   if (!CallOperandVal)
14943     return CW_Default;
14944   Type *type = CallOperandVal->getType();
14945 
14946   // Look at the constraint type.
14947   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14948     return CW_Register; // an individual CR bit.
14949   else if ((StringRef(constraint) == "wa" ||
14950             StringRef(constraint) == "wd" ||
14951             StringRef(constraint) == "wf") &&
14952            type->isVectorTy())
14953     return CW_Register;
14954   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14955     return CW_Register; // just hold 64-bit integers data.
14956   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14957     return CW_Register;
14958   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14959     return CW_Register;
14960 
14961   switch (*constraint) {
14962   default:
14963     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14964     break;
14965   case 'b':
14966     if (type->isIntegerTy())
14967       weight = CW_Register;
14968     break;
14969   case 'f':
14970     if (type->isFloatTy())
14971       weight = CW_Register;
14972     break;
14973   case 'd':
14974     if (type->isDoubleTy())
14975       weight = CW_Register;
14976     break;
14977   case 'v':
14978     if (type->isVectorTy())
14979       weight = CW_Register;
14980     break;
14981   case 'y':
14982     weight = CW_Register;
14983     break;
14984   case 'Z':
14985     weight = CW_Memory;
14986     break;
14987   }
14988   return weight;
14989 }
14990 
14991 std::pair<unsigned, const TargetRegisterClass *>
14992 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14993                                                 StringRef Constraint,
14994                                                 MVT VT) const {
14995   if (Constraint.size() == 1) {
14996     // GCC RS6000 Constraint Letters
14997     switch (Constraint[0]) {
14998     case 'b':   // R1-R31
14999       if (VT == MVT::i64 && Subtarget.isPPC64())
15000         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15001       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15002     case 'r':   // R0-R31
15003       if (VT == MVT::i64 && Subtarget.isPPC64())
15004         return std::make_pair(0U, &PPC::G8RCRegClass);
15005       return std::make_pair(0U, &PPC::GPRCRegClass);
15006     // 'd' and 'f' constraints are both defined to be "the floating point
15007     // registers", where one is for 32-bit and the other for 64-bit. We don't
15008     // really care overly much here so just give them all the same reg classes.
15009     case 'd':
15010     case 'f':
15011       if (Subtarget.hasSPE()) {
15012         if (VT == MVT::f32 || VT == MVT::i32)
15013           return std::make_pair(0U, &PPC::GPRCRegClass);
15014         if (VT == MVT::f64 || VT == MVT::i64)
15015           return std::make_pair(0U, &PPC::SPERCRegClass);
15016       } else {
15017         if (VT == MVT::f32 || VT == MVT::i32)
15018           return std::make_pair(0U, &PPC::F4RCRegClass);
15019         if (VT == MVT::f64 || VT == MVT::i64)
15020           return std::make_pair(0U, &PPC::F8RCRegClass);
15021         if (VT == MVT::v4f64 && Subtarget.hasQPX())
15022           return std::make_pair(0U, &PPC::QFRCRegClass);
15023         if (VT == MVT::v4f32 && Subtarget.hasQPX())
15024           return std::make_pair(0U, &PPC::QSRCRegClass);
15025       }
15026       break;
15027     case 'v':
15028       if (VT == MVT::v4f64 && Subtarget.hasQPX())
15029         return std::make_pair(0U, &PPC::QFRCRegClass);
15030       if (VT == MVT::v4f32 && Subtarget.hasQPX())
15031         return std::make_pair(0U, &PPC::QSRCRegClass);
15032       if (Subtarget.hasAltivec())
15033         return std::make_pair(0U, &PPC::VRRCRegClass);
15034       break;
15035     case 'y':   // crrc
15036       return std::make_pair(0U, &PPC::CRRCRegClass);
15037     }
15038   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15039     // An individual CR bit.
15040     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15041   } else if ((Constraint == "wa" || Constraint == "wd" ||
15042              Constraint == "wf" || Constraint == "wi") &&
15043              Subtarget.hasVSX()) {
15044     return std::make_pair(0U, &PPC::VSRCRegClass);
15045   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15046     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15047       return std::make_pair(0U, &PPC::VSSRCRegClass);
15048     else
15049       return std::make_pair(0U, &PPC::VSFRCRegClass);
15050   }
15051 
15052   // If we name a VSX register, we can't defer to the base class because it
15053   // will not recognize the correct register (their names will be VSL{0-31}
15054   // and V{0-31} so they won't match). So we match them here.
15055   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15056     int VSNum = atoi(Constraint.data() + 3);
15057     assert(VSNum >= 0 && VSNum <= 63 &&
15058            "Attempted to access a vsr out of range");
15059     if (VSNum < 32)
15060       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15061     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15062   }
15063   std::pair<unsigned, const TargetRegisterClass *> R =
15064       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15065 
15066   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15067   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15068   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15069   // register.
15070   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15071   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15072   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15073       PPC::GPRCRegClass.contains(R.first))
15074     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15075                             PPC::sub_32, &PPC::G8RCRegClass),
15076                           &PPC::G8RCRegClass);
15077 
15078   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15079   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15080     R.first = PPC::CR0;
15081     R.second = &PPC::CRRCRegClass;
15082   }
15083 
15084   return R;
15085 }
15086 
15087 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15088 /// vector.  If it is invalid, don't add anything to Ops.
15089 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15090                                                      std::string &Constraint,
15091                                                      std::vector<SDValue>&Ops,
15092                                                      SelectionDAG &DAG) const {
15093   SDValue Result;
15094 
15095   // Only support length 1 constraints.
15096   if (Constraint.length() > 1) return;
15097 
15098   char Letter = Constraint[0];
15099   switch (Letter) {
15100   default: break;
15101   case 'I':
15102   case 'J':
15103   case 'K':
15104   case 'L':
15105   case 'M':
15106   case 'N':
15107   case 'O':
15108   case 'P': {
15109     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15110     if (!CST) return; // Must be an immediate to match.
15111     SDLoc dl(Op);
15112     int64_t Value = CST->getSExtValue();
15113     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15114                          // numbers are printed as such.
15115     switch (Letter) {
15116     default: llvm_unreachable("Unknown constraint letter!");
15117     case 'I':  // "I" is a signed 16-bit constant.
15118       if (isInt<16>(Value))
15119         Result = DAG.getTargetConstant(Value, dl, TCVT);
15120       break;
15121     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15122       if (isShiftedUInt<16, 16>(Value))
15123         Result = DAG.getTargetConstant(Value, dl, TCVT);
15124       break;
15125     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15126       if (isShiftedInt<16, 16>(Value))
15127         Result = DAG.getTargetConstant(Value, dl, TCVT);
15128       break;
15129     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15130       if (isUInt<16>(Value))
15131         Result = DAG.getTargetConstant(Value, dl, TCVT);
15132       break;
15133     case 'M':  // "M" is a constant that is greater than 31.
15134       if (Value > 31)
15135         Result = DAG.getTargetConstant(Value, dl, TCVT);
15136       break;
15137     case 'N':  // "N" is a positive constant that is an exact power of two.
15138       if (Value > 0 && isPowerOf2_64(Value))
15139         Result = DAG.getTargetConstant(Value, dl, TCVT);
15140       break;
15141     case 'O':  // "O" is the constant zero.
15142       if (Value == 0)
15143         Result = DAG.getTargetConstant(Value, dl, TCVT);
15144       break;
15145     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15146       if (isInt<16>(-Value))
15147         Result = DAG.getTargetConstant(Value, dl, TCVT);
15148       break;
15149     }
15150     break;
15151   }
15152   }
15153 
15154   if (Result.getNode()) {
15155     Ops.push_back(Result);
15156     return;
15157   }
15158 
15159   // Handle standard constraint letters.
15160   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15161 }
15162 
15163 // isLegalAddressingMode - Return true if the addressing mode represented
15164 // by AM is legal for this target, for a load/store of the specified type.
15165 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15166                                               const AddrMode &AM, Type *Ty,
15167                                               unsigned AS, Instruction *I) const {
15168   // PPC does not allow r+i addressing modes for vectors!
15169   if (Ty->isVectorTy() && AM.BaseOffs != 0)
15170     return false;
15171 
15172   // PPC allows a sign-extended 16-bit immediate field.
15173   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15174     return false;
15175 
15176   // No global is ever allowed as a base.
15177   if (AM.BaseGV)
15178     return false;
15179 
15180   // PPC only support r+r,
15181   switch (AM.Scale) {
15182   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15183     break;
15184   case 1:
15185     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15186       return false;
15187     // Otherwise we have r+r or r+i.
15188     break;
15189   case 2:
15190     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15191       return false;
15192     // Allow 2*r as r+r.
15193     break;
15194   default:
15195     // No other scales are supported.
15196     return false;
15197   }
15198 
15199   return true;
15200 }
15201 
15202 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15203                                            SelectionDAG &DAG) const {
15204   MachineFunction &MF = DAG.getMachineFunction();
15205   MachineFrameInfo &MFI = MF.getFrameInfo();
15206   MFI.setReturnAddressIsTaken(true);
15207 
15208   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15209     return SDValue();
15210 
15211   SDLoc dl(Op);
15212   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15213 
15214   // Make sure the function does not optimize away the store of the RA to
15215   // the stack.
15216   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15217   FuncInfo->setLRStoreRequired();
15218   bool isPPC64 = Subtarget.isPPC64();
15219   auto PtrVT = getPointerTy(MF.getDataLayout());
15220 
15221   if (Depth > 0) {
15222     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15223     SDValue Offset =
15224         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15225                         isPPC64 ? MVT::i64 : MVT::i32);
15226     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15227                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15228                        MachinePointerInfo());
15229   }
15230 
15231   // Just load the return address off the stack.
15232   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15233   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15234                      MachinePointerInfo());
15235 }
15236 
15237 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15238                                           SelectionDAG &DAG) const {
15239   SDLoc dl(Op);
15240   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15241 
15242   MachineFunction &MF = DAG.getMachineFunction();
15243   MachineFrameInfo &MFI = MF.getFrameInfo();
15244   MFI.setFrameAddressIsTaken(true);
15245 
15246   EVT PtrVT = getPointerTy(MF.getDataLayout());
15247   bool isPPC64 = PtrVT == MVT::i64;
15248 
15249   // Naked functions never have a frame pointer, and so we use r1. For all
15250   // other functions, this decision must be delayed until during PEI.
15251   unsigned FrameReg;
15252   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15253     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15254   else
15255     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15256 
15257   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15258                                          PtrVT);
15259   while (Depth--)
15260     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15261                             FrameAddr, MachinePointerInfo());
15262   return FrameAddr;
15263 }
15264 
15265 // FIXME? Maybe this could be a TableGen attribute on some registers and
15266 // this table could be generated automatically from RegInfo.
15267 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15268                                               const MachineFunction &MF) const {
15269   bool isPPC64 = Subtarget.isPPC64();
15270 
15271   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15272   if (!is64Bit && VT != LLT::scalar(32))
15273     report_fatal_error("Invalid register global variable type");
15274 
15275   Register Reg = StringSwitch<Register>(RegName)
15276                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15277                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15278                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15279                      .Default(Register());
15280 
15281   if (Reg)
15282     return Reg;
15283   report_fatal_error("Invalid register name global variable");
15284 }
15285 
15286 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15287   // 32-bit SVR4 ABI access everything as got-indirect.
15288   if (Subtarget.is32BitELFABI())
15289     return true;
15290 
15291   // AIX accesses everything indirectly through the TOC, which is similar to
15292   // the GOT.
15293   if (Subtarget.isAIXABI())
15294     return true;
15295 
15296   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15297   // If it is small or large code model, module locals are accessed
15298   // indirectly by loading their address from .toc/.got.
15299   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15300     return true;
15301 
15302   // JumpTable and BlockAddress are accessed as got-indirect.
15303   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15304     return true;
15305 
15306   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15307     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15308 
15309   return false;
15310 }
15311 
15312 bool
15313 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15314   // The PowerPC target isn't yet aware of offsets.
15315   return false;
15316 }
15317 
15318 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15319                                            const CallInst &I,
15320                                            MachineFunction &MF,
15321                                            unsigned Intrinsic) const {
15322   switch (Intrinsic) {
15323   case Intrinsic::ppc_qpx_qvlfd:
15324   case Intrinsic::ppc_qpx_qvlfs:
15325   case Intrinsic::ppc_qpx_qvlfcd:
15326   case Intrinsic::ppc_qpx_qvlfcs:
15327   case Intrinsic::ppc_qpx_qvlfiwa:
15328   case Intrinsic::ppc_qpx_qvlfiwz:
15329   case Intrinsic::ppc_altivec_lvx:
15330   case Intrinsic::ppc_altivec_lvxl:
15331   case Intrinsic::ppc_altivec_lvebx:
15332   case Intrinsic::ppc_altivec_lvehx:
15333   case Intrinsic::ppc_altivec_lvewx:
15334   case Intrinsic::ppc_vsx_lxvd2x:
15335   case Intrinsic::ppc_vsx_lxvw4x: {
15336     EVT VT;
15337     switch (Intrinsic) {
15338     case Intrinsic::ppc_altivec_lvebx:
15339       VT = MVT::i8;
15340       break;
15341     case Intrinsic::ppc_altivec_lvehx:
15342       VT = MVT::i16;
15343       break;
15344     case Intrinsic::ppc_altivec_lvewx:
15345       VT = MVT::i32;
15346       break;
15347     case Intrinsic::ppc_vsx_lxvd2x:
15348       VT = MVT::v2f64;
15349       break;
15350     case Intrinsic::ppc_qpx_qvlfd:
15351       VT = MVT::v4f64;
15352       break;
15353     case Intrinsic::ppc_qpx_qvlfs:
15354       VT = MVT::v4f32;
15355       break;
15356     case Intrinsic::ppc_qpx_qvlfcd:
15357       VT = MVT::v2f64;
15358       break;
15359     case Intrinsic::ppc_qpx_qvlfcs:
15360       VT = MVT::v2f32;
15361       break;
15362     default:
15363       VT = MVT::v4i32;
15364       break;
15365     }
15366 
15367     Info.opc = ISD::INTRINSIC_W_CHAIN;
15368     Info.memVT = VT;
15369     Info.ptrVal = I.getArgOperand(0);
15370     Info.offset = -VT.getStoreSize()+1;
15371     Info.size = 2*VT.getStoreSize()-1;
15372     Info.align = Align(1);
15373     Info.flags = MachineMemOperand::MOLoad;
15374     return true;
15375   }
15376   case Intrinsic::ppc_qpx_qvlfda:
15377   case Intrinsic::ppc_qpx_qvlfsa:
15378   case Intrinsic::ppc_qpx_qvlfcda:
15379   case Intrinsic::ppc_qpx_qvlfcsa:
15380   case Intrinsic::ppc_qpx_qvlfiwaa:
15381   case Intrinsic::ppc_qpx_qvlfiwza: {
15382     EVT VT;
15383     switch (Intrinsic) {
15384     case Intrinsic::ppc_qpx_qvlfda:
15385       VT = MVT::v4f64;
15386       break;
15387     case Intrinsic::ppc_qpx_qvlfsa:
15388       VT = MVT::v4f32;
15389       break;
15390     case Intrinsic::ppc_qpx_qvlfcda:
15391       VT = MVT::v2f64;
15392       break;
15393     case Intrinsic::ppc_qpx_qvlfcsa:
15394       VT = MVT::v2f32;
15395       break;
15396     default:
15397       VT = MVT::v4i32;
15398       break;
15399     }
15400 
15401     Info.opc = ISD::INTRINSIC_W_CHAIN;
15402     Info.memVT = VT;
15403     Info.ptrVal = I.getArgOperand(0);
15404     Info.offset = 0;
15405     Info.size = VT.getStoreSize();
15406     Info.align = Align(1);
15407     Info.flags = MachineMemOperand::MOLoad;
15408     return true;
15409   }
15410   case Intrinsic::ppc_qpx_qvstfd:
15411   case Intrinsic::ppc_qpx_qvstfs:
15412   case Intrinsic::ppc_qpx_qvstfcd:
15413   case Intrinsic::ppc_qpx_qvstfcs:
15414   case Intrinsic::ppc_qpx_qvstfiw:
15415   case Intrinsic::ppc_altivec_stvx:
15416   case Intrinsic::ppc_altivec_stvxl:
15417   case Intrinsic::ppc_altivec_stvebx:
15418   case Intrinsic::ppc_altivec_stvehx:
15419   case Intrinsic::ppc_altivec_stvewx:
15420   case Intrinsic::ppc_vsx_stxvd2x:
15421   case Intrinsic::ppc_vsx_stxvw4x: {
15422     EVT VT;
15423     switch (Intrinsic) {
15424     case Intrinsic::ppc_altivec_stvebx:
15425       VT = MVT::i8;
15426       break;
15427     case Intrinsic::ppc_altivec_stvehx:
15428       VT = MVT::i16;
15429       break;
15430     case Intrinsic::ppc_altivec_stvewx:
15431       VT = MVT::i32;
15432       break;
15433     case Intrinsic::ppc_vsx_stxvd2x:
15434       VT = MVT::v2f64;
15435       break;
15436     case Intrinsic::ppc_qpx_qvstfd:
15437       VT = MVT::v4f64;
15438       break;
15439     case Intrinsic::ppc_qpx_qvstfs:
15440       VT = MVT::v4f32;
15441       break;
15442     case Intrinsic::ppc_qpx_qvstfcd:
15443       VT = MVT::v2f64;
15444       break;
15445     case Intrinsic::ppc_qpx_qvstfcs:
15446       VT = MVT::v2f32;
15447       break;
15448     default:
15449       VT = MVT::v4i32;
15450       break;
15451     }
15452 
15453     Info.opc = ISD::INTRINSIC_VOID;
15454     Info.memVT = VT;
15455     Info.ptrVal = I.getArgOperand(1);
15456     Info.offset = -VT.getStoreSize()+1;
15457     Info.size = 2*VT.getStoreSize()-1;
15458     Info.align = Align(1);
15459     Info.flags = MachineMemOperand::MOStore;
15460     return true;
15461   }
15462   case Intrinsic::ppc_qpx_qvstfda:
15463   case Intrinsic::ppc_qpx_qvstfsa:
15464   case Intrinsic::ppc_qpx_qvstfcda:
15465   case Intrinsic::ppc_qpx_qvstfcsa:
15466   case Intrinsic::ppc_qpx_qvstfiwa: {
15467     EVT VT;
15468     switch (Intrinsic) {
15469     case Intrinsic::ppc_qpx_qvstfda:
15470       VT = MVT::v4f64;
15471       break;
15472     case Intrinsic::ppc_qpx_qvstfsa:
15473       VT = MVT::v4f32;
15474       break;
15475     case Intrinsic::ppc_qpx_qvstfcda:
15476       VT = MVT::v2f64;
15477       break;
15478     case Intrinsic::ppc_qpx_qvstfcsa:
15479       VT = MVT::v2f32;
15480       break;
15481     default:
15482       VT = MVT::v4i32;
15483       break;
15484     }
15485 
15486     Info.opc = ISD::INTRINSIC_VOID;
15487     Info.memVT = VT;
15488     Info.ptrVal = I.getArgOperand(1);
15489     Info.offset = 0;
15490     Info.size = VT.getStoreSize();
15491     Info.align = Align(1);
15492     Info.flags = MachineMemOperand::MOStore;
15493     return true;
15494   }
15495   default:
15496     break;
15497   }
15498 
15499   return false;
15500 }
15501 
15502 /// It returns EVT::Other if the type should be determined using generic
15503 /// target-independent logic.
15504 EVT PPCTargetLowering::getOptimalMemOpType(
15505     const MemOp &Op, const AttributeList &FuncAttributes) const {
15506   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15507     // When expanding a memset, require at least two QPX instructions to cover
15508     // the cost of loading the value to be stored from the constant pool.
15509     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15510         (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) &&
15511         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15512       return MVT::v4f64;
15513     }
15514 
15515     // We should use Altivec/VSX loads and stores when available. For unaligned
15516     // addresses, unaligned VSX loads are only fast starting with the P8.
15517     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15518         (Op.isAligned(Align(16)) ||
15519          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15520       return MVT::v4i32;
15521   }
15522 
15523   if (Subtarget.isPPC64()) {
15524     return MVT::i64;
15525   }
15526 
15527   return MVT::i32;
15528 }
15529 
15530 /// Returns true if it is beneficial to convert a load of a constant
15531 /// to just the constant itself.
15532 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15533                                                           Type *Ty) const {
15534   assert(Ty->isIntegerTy());
15535 
15536   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15537   return !(BitSize == 0 || BitSize > 64);
15538 }
15539 
15540 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15541   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15542     return false;
15543   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15544   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15545   return NumBits1 == 64 && NumBits2 == 32;
15546 }
15547 
15548 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15549   if (!VT1.isInteger() || !VT2.isInteger())
15550     return false;
15551   unsigned NumBits1 = VT1.getSizeInBits();
15552   unsigned NumBits2 = VT2.getSizeInBits();
15553   return NumBits1 == 64 && NumBits2 == 32;
15554 }
15555 
15556 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15557   // Generally speaking, zexts are not free, but they are free when they can be
15558   // folded with other operations.
15559   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15560     EVT MemVT = LD->getMemoryVT();
15561     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15562          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15563         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15564          LD->getExtensionType() == ISD::ZEXTLOAD))
15565       return true;
15566   }
15567 
15568   // FIXME: Add other cases...
15569   //  - 32-bit shifts with a zext to i64
15570   //  - zext after ctlz, bswap, etc.
15571   //  - zext after and by a constant mask
15572 
15573   return TargetLowering::isZExtFree(Val, VT2);
15574 }
15575 
15576 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15577   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15578          "invalid fpext types");
15579   // Extending to float128 is not free.
15580   if (DestVT == MVT::f128)
15581     return false;
15582   return true;
15583 }
15584 
15585 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15586   return isInt<16>(Imm) || isUInt<16>(Imm);
15587 }
15588 
15589 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15590   return isInt<16>(Imm) || isUInt<16>(Imm);
15591 }
15592 
15593 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15594                                                        unsigned,
15595                                                        unsigned,
15596                                                        MachineMemOperand::Flags,
15597                                                        bool *Fast) const {
15598   if (DisablePPCUnaligned)
15599     return false;
15600 
15601   // PowerPC supports unaligned memory access for simple non-vector types.
15602   // Although accessing unaligned addresses is not as efficient as accessing
15603   // aligned addresses, it is generally more efficient than manual expansion,
15604   // and generally only traps for software emulation when crossing page
15605   // boundaries.
15606 
15607   if (!VT.isSimple())
15608     return false;
15609 
15610   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15611     return false;
15612 
15613   if (VT.getSimpleVT().isVector()) {
15614     if (Subtarget.hasVSX()) {
15615       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15616           VT != MVT::v4f32 && VT != MVT::v4i32)
15617         return false;
15618     } else {
15619       return false;
15620     }
15621   }
15622 
15623   if (VT == MVT::ppcf128)
15624     return false;
15625 
15626   if (Fast)
15627     *Fast = true;
15628 
15629   return true;
15630 }
15631 
15632 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15633                                                    EVT VT) const {
15634   return isFMAFasterThanFMulAndFAdd(
15635       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15636 }
15637 
15638 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15639                                                    Type *Ty) const {
15640   switch (Ty->getScalarType()->getTypeID()) {
15641   case Type::FloatTyID:
15642   case Type::DoubleTyID:
15643     return true;
15644   case Type::FP128TyID:
15645     return EnableQuadPrecision && Subtarget.hasP9Vector();
15646   default:
15647     return false;
15648   }
15649 }
15650 
15651 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist.
15652 // FIXME: add more patterns which are profitable to hoist.
15653 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15654   if (I->getOpcode() != Instruction::FMul)
15655     return true;
15656 
15657   if (!I->hasOneUse())
15658     return true;
15659 
15660   Instruction *User = I->user_back();
15661   assert(User && "A single use instruction with no uses.");
15662 
15663   if (User->getOpcode() != Instruction::FSub &&
15664       User->getOpcode() != Instruction::FAdd)
15665     return true;
15666 
15667   const TargetOptions &Options = getTargetMachine().Options;
15668   const Function *F = I->getFunction();
15669   const DataLayout &DL = F->getParent()->getDataLayout();
15670   Type *Ty = User->getOperand(0)->getType();
15671 
15672   return !(
15673       isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15674       isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15675       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15676 }
15677 
15678 const MCPhysReg *
15679 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15680   // LR is a callee-save register, but we must treat it as clobbered by any call
15681   // site. Hence we include LR in the scratch registers, which are in turn added
15682   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15683   // to CTR, which is used by any indirect call.
15684   static const MCPhysReg ScratchRegs[] = {
15685     PPC::X12, PPC::LR8, PPC::CTR8, 0
15686   };
15687 
15688   return ScratchRegs;
15689 }
15690 
15691 Register PPCTargetLowering::getExceptionPointerRegister(
15692     const Constant *PersonalityFn) const {
15693   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15694 }
15695 
15696 Register PPCTargetLowering::getExceptionSelectorRegister(
15697     const Constant *PersonalityFn) const {
15698   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15699 }
15700 
15701 bool
15702 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15703                      EVT VT , unsigned DefinedValues) const {
15704   if (VT == MVT::v2i64)
15705     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15706 
15707   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15708     return true;
15709 
15710   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15711 }
15712 
15713 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15714   if (DisableILPPref || Subtarget.enableMachineScheduler())
15715     return TargetLowering::getSchedulingPreference(N);
15716 
15717   return Sched::ILP;
15718 }
15719 
15720 // Create a fast isel object.
15721 FastISel *
15722 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15723                                   const TargetLibraryInfo *LibInfo) const {
15724   return PPC::createFastISel(FuncInfo, LibInfo);
15725 }
15726 
15727 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15728   if (!Subtarget.isPPC64()) return;
15729 
15730   // Update IsSplitCSR in PPCFunctionInfo
15731   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15732   PFI->setIsSplitCSR(true);
15733 }
15734 
15735 void PPCTargetLowering::insertCopiesSplitCSR(
15736   MachineBasicBlock *Entry,
15737   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15738   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15739   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15740   if (!IStart)
15741     return;
15742 
15743   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15744   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15745   MachineBasicBlock::iterator MBBI = Entry->begin();
15746   for (const MCPhysReg *I = IStart; *I; ++I) {
15747     const TargetRegisterClass *RC = nullptr;
15748     if (PPC::G8RCRegClass.contains(*I))
15749       RC = &PPC::G8RCRegClass;
15750     else if (PPC::F8RCRegClass.contains(*I))
15751       RC = &PPC::F8RCRegClass;
15752     else if (PPC::CRRCRegClass.contains(*I))
15753       RC = &PPC::CRRCRegClass;
15754     else if (PPC::VRRCRegClass.contains(*I))
15755       RC = &PPC::VRRCRegClass;
15756     else
15757       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15758 
15759     Register NewVR = MRI->createVirtualRegister(RC);
15760     // Create copy from CSR to a virtual register.
15761     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15762     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15763     // nounwind. If we want to generalize this later, we may need to emit
15764     // CFI pseudo-instructions.
15765     assert(Entry->getParent()->getFunction().hasFnAttribute(
15766              Attribute::NoUnwind) &&
15767            "Function should be nounwind in insertCopiesSplitCSR!");
15768     Entry->addLiveIn(*I);
15769     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15770       .addReg(*I);
15771 
15772     // Insert the copy-back instructions right before the terminator.
15773     for (auto *Exit : Exits)
15774       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15775               TII->get(TargetOpcode::COPY), *I)
15776         .addReg(NewVR);
15777   }
15778 }
15779 
15780 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15781 bool PPCTargetLowering::useLoadStackGuardNode() const {
15782   if (!Subtarget.isTargetLinux())
15783     return TargetLowering::useLoadStackGuardNode();
15784   return true;
15785 }
15786 
15787 // Override to disable global variable loading on Linux.
15788 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15789   if (!Subtarget.isTargetLinux())
15790     return TargetLowering::insertSSPDeclarations(M);
15791 }
15792 
15793 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15794                                      bool ForCodeSize) const {
15795   if (!VT.isSimple() || !Subtarget.hasVSX())
15796     return false;
15797 
15798   switch(VT.getSimpleVT().SimpleTy) {
15799   default:
15800     // For FP types that are currently not supported by PPC backend, return
15801     // false. Examples: f16, f80.
15802     return false;
15803   case MVT::f32:
15804   case MVT::f64:
15805   case MVT::ppcf128:
15806     return Imm.isPosZero();
15807   }
15808 }
15809 
15810 // For vector shift operation op, fold
15811 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15812 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15813                                   SelectionDAG &DAG) {
15814   SDValue N0 = N->getOperand(0);
15815   SDValue N1 = N->getOperand(1);
15816   EVT VT = N0.getValueType();
15817   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15818   unsigned Opcode = N->getOpcode();
15819   unsigned TargetOpcode;
15820 
15821   switch (Opcode) {
15822   default:
15823     llvm_unreachable("Unexpected shift operation");
15824   case ISD::SHL:
15825     TargetOpcode = PPCISD::SHL;
15826     break;
15827   case ISD::SRL:
15828     TargetOpcode = PPCISD::SRL;
15829     break;
15830   case ISD::SRA:
15831     TargetOpcode = PPCISD::SRA;
15832     break;
15833   }
15834 
15835   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15836       N1->getOpcode() == ISD::AND)
15837     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15838       if (Mask->getZExtValue() == OpSizeInBits - 1)
15839         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15840 
15841   return SDValue();
15842 }
15843 
15844 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15845   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15846     return Value;
15847 
15848   SDValue N0 = N->getOperand(0);
15849   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15850   if (!Subtarget.isISA3_0() ||
15851       N0.getOpcode() != ISD::SIGN_EXTEND ||
15852       N0.getOperand(0).getValueType() != MVT::i32 ||
15853       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15854     return SDValue();
15855 
15856   // We can't save an operation here if the value is already extended, and
15857   // the existing shift is easier to combine.
15858   SDValue ExtsSrc = N0.getOperand(0);
15859   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15860       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15861     return SDValue();
15862 
15863   SDLoc DL(N0);
15864   SDValue ShiftBy = SDValue(CN1, 0);
15865   // We want the shift amount to be i32 on the extswli, but the shift could
15866   // have an i64.
15867   if (ShiftBy.getValueType() == MVT::i64)
15868     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15869 
15870   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15871                          ShiftBy);
15872 }
15873 
15874 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15875   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15876     return Value;
15877 
15878   return SDValue();
15879 }
15880 
15881 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15882   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15883     return Value;
15884 
15885   return SDValue();
15886 }
15887 
15888 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15889 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15890 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15891 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15892 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15893                                  const PPCSubtarget &Subtarget) {
15894   if (!Subtarget.isPPC64())
15895     return SDValue();
15896 
15897   SDValue LHS = N->getOperand(0);
15898   SDValue RHS = N->getOperand(1);
15899 
15900   auto isZextOfCompareWithConstant = [](SDValue Op) {
15901     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15902         Op.getValueType() != MVT::i64)
15903       return false;
15904 
15905     SDValue Cmp = Op.getOperand(0);
15906     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15907         Cmp.getOperand(0).getValueType() != MVT::i64)
15908       return false;
15909 
15910     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15911       int64_t NegConstant = 0 - Constant->getSExtValue();
15912       // Due to the limitations of the addi instruction,
15913       // -C is required to be [-32768, 32767].
15914       return isInt<16>(NegConstant);
15915     }
15916 
15917     return false;
15918   };
15919 
15920   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15921   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15922 
15923   // If there is a pattern, canonicalize a zext operand to the RHS.
15924   if (LHSHasPattern && !RHSHasPattern)
15925     std::swap(LHS, RHS);
15926   else if (!LHSHasPattern && !RHSHasPattern)
15927     return SDValue();
15928 
15929   SDLoc DL(N);
15930   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15931   SDValue Cmp = RHS.getOperand(0);
15932   SDValue Z = Cmp.getOperand(0);
15933   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15934 
15935   assert(Constant && "Constant Should not be a null pointer.");
15936   int64_t NegConstant = 0 - Constant->getSExtValue();
15937 
15938   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15939   default: break;
15940   case ISD::SETNE: {
15941     //                                 when C == 0
15942     //                             --> addze X, (addic Z, -1).carry
15943     //                            /
15944     // add X, (zext(setne Z, C))--
15945     //                            \    when -32768 <= -C <= 32767 && C != 0
15946     //                             --> addze X, (addic (addi Z, -C), -1).carry
15947     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15948                               DAG.getConstant(NegConstant, DL, MVT::i64));
15949     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15950     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15951                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15952     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15953                        SDValue(Addc.getNode(), 1));
15954     }
15955   case ISD::SETEQ: {
15956     //                                 when C == 0
15957     //                             --> addze X, (subfic Z, 0).carry
15958     //                            /
15959     // add X, (zext(sete  Z, C))--
15960     //                            \    when -32768 <= -C <= 32767 && C != 0
15961     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15962     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15963                               DAG.getConstant(NegConstant, DL, MVT::i64));
15964     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15965     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15966                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15967     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15968                        SDValue(Subc.getNode(), 1));
15969     }
15970   }
15971 
15972   return SDValue();
15973 }
15974 
15975 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15976   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15977     return Value;
15978 
15979   return SDValue();
15980 }
15981 
15982 // Detect TRUNCATE operations on bitcasts of float128 values.
15983 // What we are looking for here is the situtation where we extract a subset
15984 // of bits from a 128 bit float.
15985 // This can be of two forms:
15986 // 1) BITCAST of f128 feeding TRUNCATE
15987 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15988 // The reason this is required is because we do not have a legal i128 type
15989 // and so we want to prevent having to store the f128 and then reload part
15990 // of it.
15991 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15992                                            DAGCombinerInfo &DCI) const {
15993   // If we are using CRBits then try that first.
15994   if (Subtarget.useCRBits()) {
15995     // Check if CRBits did anything and return that if it did.
15996     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15997       return CRTruncValue;
15998   }
15999 
16000   SDLoc dl(N);
16001   SDValue Op0 = N->getOperand(0);
16002 
16003   // Looking for a truncate of i128 to i64.
16004   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16005     return SDValue();
16006 
16007   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16008 
16009   // SRL feeding TRUNCATE.
16010   if (Op0.getOpcode() == ISD::SRL) {
16011     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16012     // The right shift has to be by 64 bits.
16013     if (!ConstNode || ConstNode->getZExtValue() != 64)
16014       return SDValue();
16015 
16016     // Switch the element number to extract.
16017     EltToExtract = EltToExtract ? 0 : 1;
16018     // Update Op0 past the SRL.
16019     Op0 = Op0.getOperand(0);
16020   }
16021 
16022   // BITCAST feeding a TRUNCATE possibly via SRL.
16023   if (Op0.getOpcode() == ISD::BITCAST &&
16024       Op0.getValueType() == MVT::i128 &&
16025       Op0.getOperand(0).getValueType() == MVT::f128) {
16026     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16027     return DCI.DAG.getNode(
16028         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16029         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16030   }
16031   return SDValue();
16032 }
16033 
16034 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16035   SelectionDAG &DAG = DCI.DAG;
16036 
16037   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16038   if (!ConstOpOrElement)
16039     return SDValue();
16040 
16041   // An imul is usually smaller than the alternative sequence for legal type.
16042   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16043       isOperationLegal(ISD::MUL, N->getValueType(0)))
16044     return SDValue();
16045 
16046   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16047     switch (this->Subtarget.getCPUDirective()) {
16048     default:
16049       // TODO: enhance the condition for subtarget before pwr8
16050       return false;
16051     case PPC::DIR_PWR8:
16052       //  type        mul     add    shl
16053       // scalar        4       1      1
16054       // vector        7       2      2
16055       return true;
16056     case PPC::DIR_PWR9:
16057     case PPC::DIR_PWR_FUTURE:
16058       //  type        mul     add    shl
16059       // scalar        5       2      2
16060       // vector        7       2      2
16061 
16062       // The cycle RATIO of related operations are showed as a table above.
16063       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16064       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16065       // are 4, it is always profitable; but for 3 instrs patterns
16066       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16067       // So we should only do it for vector type.
16068       return IsAddOne && IsNeg ? VT.isVector() : true;
16069     }
16070   };
16071 
16072   EVT VT = N->getValueType(0);
16073   SDLoc DL(N);
16074 
16075   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16076   bool IsNeg = MulAmt.isNegative();
16077   APInt MulAmtAbs = MulAmt.abs();
16078 
16079   if ((MulAmtAbs - 1).isPowerOf2()) {
16080     // (mul x, 2^N + 1) => (add (shl x, N), x)
16081     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16082 
16083     if (!IsProfitable(IsNeg, true, VT))
16084       return SDValue();
16085 
16086     SDValue Op0 = N->getOperand(0);
16087     SDValue Op1 =
16088         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16089                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16090     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16091 
16092     if (!IsNeg)
16093       return Res;
16094 
16095     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16096   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16097     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16098     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16099 
16100     if (!IsProfitable(IsNeg, false, VT))
16101       return SDValue();
16102 
16103     SDValue Op0 = N->getOperand(0);
16104     SDValue Op1 =
16105         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16106                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16107 
16108     if (!IsNeg)
16109       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16110     else
16111       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16112 
16113   } else {
16114     return SDValue();
16115   }
16116 }
16117 
16118 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16119   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16120   if (!Subtarget.is64BitELFABI())
16121     return false;
16122 
16123   // If not a tail call then no need to proceed.
16124   if (!CI->isTailCall())
16125     return false;
16126 
16127   // If sibling calls have been disabled and tail-calls aren't guaranteed
16128   // there is no reason to duplicate.
16129   auto &TM = getTargetMachine();
16130   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16131     return false;
16132 
16133   // Can't tail call a function called indirectly, or if it has variadic args.
16134   const Function *Callee = CI->getCalledFunction();
16135   if (!Callee || Callee->isVarArg())
16136     return false;
16137 
16138   // Make sure the callee and caller calling conventions are eligible for tco.
16139   const Function *Caller = CI->getParent()->getParent();
16140   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16141                                            CI->getCallingConv()))
16142       return false;
16143 
16144   // If the function is local then we have a good chance at tail-calling it
16145   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16146 }
16147 
16148 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16149   if (!Subtarget.hasVSX())
16150     return false;
16151   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16152     return true;
16153   return VT == MVT::f32 || VT == MVT::f64 ||
16154     VT == MVT::v4f32 || VT == MVT::v2f64;
16155 }
16156 
16157 bool PPCTargetLowering::
16158 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16159   const Value *Mask = AndI.getOperand(1);
16160   // If the mask is suitable for andi. or andis. we should sink the and.
16161   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16162     // Can't handle constants wider than 64-bits.
16163     if (CI->getBitWidth() > 64)
16164       return false;
16165     int64_t ConstVal = CI->getZExtValue();
16166     return isUInt<16>(ConstVal) ||
16167       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16168   }
16169 
16170   // For non-constant masks, we can always use the record-form and.
16171   return true;
16172 }
16173 
16174 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16175 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16176 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16177 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16178 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16179 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16180   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16181   assert(Subtarget.hasP9Altivec() &&
16182          "Only combine this when P9 altivec supported!");
16183   EVT VT = N->getValueType(0);
16184   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16185     return SDValue();
16186 
16187   SelectionDAG &DAG = DCI.DAG;
16188   SDLoc dl(N);
16189   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16190     // Even for signed integers, if it's known to be positive (as signed
16191     // integer) due to zero-extended inputs.
16192     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16193     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16194     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16195          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16196         (SubOpcd1 == ISD::ZERO_EXTEND ||
16197          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16198       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16199                          N->getOperand(0)->getOperand(0),
16200                          N->getOperand(0)->getOperand(1),
16201                          DAG.getTargetConstant(0, dl, MVT::i32));
16202     }
16203 
16204     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16205     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16206         N->getOperand(0).hasOneUse()) {
16207       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16208                          N->getOperand(0)->getOperand(0),
16209                          N->getOperand(0)->getOperand(1),
16210                          DAG.getTargetConstant(1, dl, MVT::i32));
16211     }
16212   }
16213 
16214   return SDValue();
16215 }
16216 
16217 // For type v4i32/v8ii16/v16i8, transform
16218 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16219 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16220 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16221 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16222 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16223                                           DAGCombinerInfo &DCI) const {
16224   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16225   assert(Subtarget.hasP9Altivec() &&
16226          "Only combine this when P9 altivec supported!");
16227 
16228   SelectionDAG &DAG = DCI.DAG;
16229   SDLoc dl(N);
16230   SDValue Cond = N->getOperand(0);
16231   SDValue TrueOpnd = N->getOperand(1);
16232   SDValue FalseOpnd = N->getOperand(2);
16233   EVT VT = N->getOperand(1).getValueType();
16234 
16235   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16236       FalseOpnd.getOpcode() != ISD::SUB)
16237     return SDValue();
16238 
16239   // ABSD only available for type v4i32/v8i16/v16i8
16240   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16241     return SDValue();
16242 
16243   // At least to save one more dependent computation
16244   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16245     return SDValue();
16246 
16247   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16248 
16249   // Can only handle unsigned comparison here
16250   switch (CC) {
16251   default:
16252     return SDValue();
16253   case ISD::SETUGT:
16254   case ISD::SETUGE:
16255     break;
16256   case ISD::SETULT:
16257   case ISD::SETULE:
16258     std::swap(TrueOpnd, FalseOpnd);
16259     break;
16260   }
16261 
16262   SDValue CmpOpnd1 = Cond.getOperand(0);
16263   SDValue CmpOpnd2 = Cond.getOperand(1);
16264 
16265   // SETCC CmpOpnd1 CmpOpnd2 cond
16266   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16267   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16268   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16269       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16270       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16271       FalseOpnd.getOperand(1) == CmpOpnd1) {
16272     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16273                        CmpOpnd1, CmpOpnd2,
16274                        DAG.getTargetConstant(0, dl, MVT::i32));
16275   }
16276 
16277   return SDValue();
16278 }
16279